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 {
  ACTIVE_SHELL_MAX_LINES,
  AT_COMMAND_PATH_REGEX_SOURCE,
  AppContext_default,
  BaseSelectionList,
  Box_default,
  BuiltinCommandLoader,
  COMPACT_TOOL_SUBVIEW_MAX_LINES,
  COMPLETED_SHELL_MAX_LINES,
  CliSpinner,
  Command,
  CommandService,
  ConfigContext,
  ConsolePatcher,
  ContextUsageDisplay,
  DEFAULT_THEME,
  DOUBLE_CLICK_DISTANCE_TOLERANCE,
  DOUBLE_CLICK_THRESHOLD_MS,
  DefaultLight,
  DialogFooter,
  ESC,
  EXPAND_HINT_DURATION_MS,
  ExpandableText,
  FileCommandLoader,
  Footer,
  GIT_COMMIT_INFO,
  INK_NAME_TO_HEX_MAP,
  INK_SUPPORTED_NAMES,
  InputContext,
  KEYBOARD_SHORTCUTS_URL,
  KeyBinding,
  KeyMatchersProvider,
  KeypressProvider,
  LARGE_PASTE_CHAR_THRESHOLD,
  LARGE_PASTE_LINE_THRESHOLD,
  LRU_BUFFER_PERF_CACHE_LIMIT,
  MAX_GEMINI_MESSAGE_LINES,
  MAX_MCP_RESOURCES_TO_SHOW,
  MAX_SHELL_OUTPUT_SIZE,
  MAX_WIDTH,
  McpPromptLoader,
  MultiFolderTrustDialog,
  Newline,
  PASTED_TEXT_PLACEHOLDER_REGEX,
  QUEUE_ERROR_DISPLAY_DURATION_MS,
  QUOTA_USED_CRITICAL_THRESHOLD,
  QUOTA_USED_WARNING_THRESHOLD,
  RadioButtonSelect,
  ResizeObserver,
  SHELL_ACTION_REQUIRED_TITLE_DELAY_MS,
  SHELL_COMMAND_NAME,
  SHELL_FOCUS_HINT_DELAY_MS,
  SHELL_NAME,
  SHELL_OUTPUT_TRUNCATION_BUFFER,
  SHELL_SILENT_WORKING_TITLE_DELAY_MS,
  SKILLS_DOCS_URL,
  SUBAGENT_MAX_LINES,
  SettingScope,
  SettingsContext,
  Static,
  StaticRender,
  StyledLine,
  TOGGLE_TYPES,
  TOOL_STATUS,
  TOOL_SUCCESS_RATE_HIGH,
  TOOL_SUCCESS_RATE_MEDIUM,
  TerminalCapabilityManager,
  Text,
  TextInput,
  Transform,
  UIStateContext,
  USER_AGREEMENT_RATE_HIGH,
  USER_AGREEMENT_RATE_MEDIUM,
  VimModeProvider,
  WARNING_PROMPT_DURATION_MS,
  batchAddDirectories,
  build_default,
  calculateTransformationsForLine,
  calculateTransformedLine,
  checkPermissions,
  cleanMessage,
  cleanupOldClipboardImages,
  cleanupTerminalOnExit,
  clipboardHasImage,
  clipboardy_default,
  convertSessionToHistoryFormats,
  cpIndexToOffset,
  cpLen,
  cpSlice,
  debugState,
  defaultKeyBindingConfig,
  escapeAnsiCtrlCodes,
  escapeAtSymbols,
  expandHomeDir,
  expandPastePlaceholders,
  formatBytes,
  formatDuration,
  formatRelativeTime,
  formatResetTime,
  getAsciiArtWidth,
  getBoundingBox,
  getCachedStringWidth,
  getFormattedSettingValue,
  getLuminance,
  getSafeLowColorBackground,
  getSessionFiles,
  getSettingsSchema,
  getStatusColor,
  getTransformUnderCursor,
  getUsedStatusColor,
  handleAtCommand,
  handleAutoUpdate,
  interpolateColor,
  isAlternateBufferEnabled,
  isAtCommand,
  isAutoExecutableCommand,
  isBrowser,
  isContextUsageHigh,
  isDevelopment,
  isIncompleteMouseSequence,
  isLoadableSettingScope,
  isSlashCommand,
  isTodoList,
  isUltraTier,
  isWorkspaceTrusted,
  loadKeyMatchers,
  loadTrustedFolders,
  logicalPosToOffset,
  mapCoreStatusToDisplayStatus,
  measure_element_default,
  normalizeEscapedNewlines,
  openFileInEditor,
  parseColor,
  parseMouseEvent,
  parseSlashCommand,
  persistentState,
  pickDefaultThemeName,
  profiler,
  registerCleanup,
  relaunchApp,
  render_default,
  requestConsentInteractive,
  require_jsx_runtime,
  require_react,
  require_semver,
  require_source,
  require_tinygradient,
  resolveColor,
  runExitCleanup,
  sanitizeForDisplay,
  saveClipboardImage,
  setUpdateHandler,
  setupTtyCheck,
  shouldSwitchTheme,
  stringWidth,
  stripUnsafeCharacters,
  styledCharsWidth,
  styledLineToString,
  terminalCapabilityManager,
  theme,
  themeManager,
  toCodePoints,
  toStyledCharacters,
  useAlternateBuffer,
  useConfig,
  useConfirmUpdateRequests,
  useExtensionUpdates,
  useFocus,
  useHistory,
  useIdeTrustListener,
  useInputState,
  useKeyMatchers,
  useKeypress,
  useSearchBuffer,
  useSessionBrowser,
  useSettings,
  useSettingsStore,
  useTerminalSetupPrompt,
  useTextBuffer,
  useUIState,
  useVimMode,
  use_app_default,
  use_is_screen_reader_enabled_default,
  use_stdin_default,
  use_stdout_default,
  validateAuthMethod,
  widestLineFromStyledChars,
  wordBreakStyledChars,
  wrapStyledChars
} from "./chunk-7DZN7VCC.js";
import {
  ApiKeyUpdatedEvent,
  AsyncFzf,
  AuthType,
  CompressionStatus,
  ConversationFinishedEvent,
  CoreToolCallStatus,
  CreditPurchaseClickEvent,
  EDITOR_DISPLAY_NAMES,
  EmptyWalletMenuShownEvent,
  ExecutionLifecycleService,
  ExitCodes,
  FileDiscoveryService,
  FileSearchFactory,
  FolderTrustDiscoveryService,
  G1_UTM_CAMPAIGNS,
  GeminiCliOperation,
  GeminiEventType,
  GitService,
  IdeClient,
  LlmRole,
  Logger,
  MCPDiscoveryState,
  MCPServerStatus,
  MessageSenderType,
  ModelNotFoundError,
  ModelSlashCommandEvent,
  OverageMenuShownEvent,
  OverageOptionSelectedEvent,
  PolicyIntegrityManager,
  ProjectIdRequiredError,
  ROOT_SCHEDULER_ID,
  Scheduler,
  SessionEndReason,
  SessionStartSource,
  ShellExecutionService,
  SlashCommandStatus,
  TerminalQuotaError,
  UserAccountManager,
  UserPromptEvent,
  UserTierId,
  ValidationRequiredError,
  WarningPriority,
  addMCPStatusChangeListener,
  allowEditorTypeInSandbox,
  buildG1Url,
  buildUserSteeringHintPrompt,
  checkExhaustive,
  clearApiKey,
  clearCachedCredentialFile,
  convertSessionToClientHistory,
  createWorkingStdio,
  disableLineWrapping,
  disableMouseEvents,
  enableLineWrapping,
  enableMouseEvents,
  enterAlternateScreen,
  escapeShellArg,
  exitAlternateScreen,
  flattenMemory,
  generateSummary,
  getAdminErrorMessage,
  getCodeAssistServer,
  getEditorDisplayName,
  getG1CreditBalance,
  getMCPServerStatus,
  getPackageJson,
  getPlanModeExitMessage,
  getResponseText,
  getShellConfiguration,
  getVersion,
  hasRedirection,
  hasValidEditorCommand,
  ideContextStore,
  import_lru_cache,
  isAppleTerminal,
  isBinary,
  isCompletedAskUserTool,
  isEditorAvailable,
  isHeadlessMode,
  isOverageEligibleModel,
  isSubagentProgress,
  isUserVisibleHook,
  loadApiKey,
  logBillingEvent,
  logConversationFinishedEvent,
  logModelSlashCommand,
  logSlashCommand,
  logUserPrompt,
  makeSlashCommandEvent,
  openBrowserSecurely,
  parseAndFormatApiError,
  processRestorableToolCalls,
  processSingleFileContent,
  promptIdContext,
  recordCreditPurchaseClick,
  recordExitFail,
  recordFlickerFrame,
  recordOverageOptionSelected,
  recordSlowRender,
  recordToolCallInteractions,
  removeMCPStatusChangeListener,
  runInDevTraceSpan,
  saveApiKey,
  sessionId,
  shouldAutoUseCredits,
  shouldEnterAlternateScreen,
  shouldHideToolCall,
  shouldLaunchBrowser,
  shouldShowEmptyWalletMenu,
  shouldShowOverageMenu,
  spawnAsync,
  startMemoryService,
  startupProfiler,
  stripAnsi,
  tokenLimit,
  uiTelemetryService,
  validatePlanContent,
  validatePlanPath,
  writeToStdout
} from "./chunk-GOUPAQ35.js";
import {
  ACTIVATE_SKILL_TOOL_NAME,
  ApprovalMode,
  ChangeAuthRequestedError,
  CoreEvent,
  DEFAULT_GEMINI_FLASH_LITE_MODEL,
  DEFAULT_GEMINI_FLASH_MODEL,
  DEFAULT_GEMINI_MODEL,
  DEFAULT_GEMINI_MODEL_AUTO,
  EDIT_DISPLAY_NAME,
  EDIT_TOOL_NAMES,
  FinishReason,
  GEMINI_DIR,
  GLOB_DISPLAY_NAME,
  GREP_DISPLAY_NAME,
  Kind,
  LS_DISPLAY_NAME,
  MessageBusType,
  PREVIEW_GEMINI_3_1_CUSTOM_TOOLS_MODEL,
  PREVIEW_GEMINI_3_1_FLASH_LITE_MODEL,
  PREVIEW_GEMINI_3_1_MODEL,
  PREVIEW_GEMINI_FLASH_MODEL,
  PREVIEW_GEMINI_MODEL,
  PREVIEW_GEMINI_MODEL_AUTO,
  QuestionType,
  READ_FILE_DISPLAY_NAME,
  READ_MANY_FILES_DISPLAY_NAME,
  SHELL_TOOL_NAME,
  Storage,
  TOPIC_PARAM_STRATEGIC_INTENT,
  TOPIC_PARAM_SUMMARY,
  TOPIC_PARAM_TITLE,
  ToolConfirmationOutcome,
  ToolErrorType,
  UPDATE_TOPIC_DISPLAY_NAME,
  UPDATE_TOPIC_TOOL_NAME,
  UnauthorizedError,
  VALID_GEMINI_MODELS,
  WEB_FETCH_DISPLAY_NAME,
  WEB_SEARCH_DISPLAY_NAME,
  WRITE_FILE_DISPLAY_NAME,
  coreEvents,
  debugLogger,
  escapePath,
  getAllGeminiMdFilenames,
  getDisplayString,
  getErrorMessage,
  hasSummary,
  homedir,
  isAccountSuspendedError,
  isAutoModel,
  isBackgroundExecutionData,
  isFileDiff,
  isGrepResult,
  isListResult,
  isNodeError,
  isProModel,
  isReadManyFilesResult,
  isStructuredToolResult,
  refreshServerHierarchicalMemory,
  safeJsonToMarkdown,
  shortenPath,
  tildeifyPath
} from "./chunk-ETUADTWF.js";
import "./chunk-664ZODQF.js";
import {
  appEvents
} from "./chunk-5PS3AYFU.js";
import "./chunk-RJTRUG2J.js";
import "./chunk-IUUIT4SU.js";
import {
  __commonJS,
  __export,
  __require,
  __toESM
} from "./chunk-34MYV7JD.js";

// node_modules/highlight.js/lib/core.js
var require_core = __commonJS({
  "node_modules/highlight.js/lib/core.js"(exports, module) {
    function deepFreeze(obj) {
      if (obj instanceof Map) {
        obj.clear = obj.delete = obj.set = function() {
          throw new Error("map is read-only");
        };
      } else if (obj instanceof Set) {
        obj.add = obj.clear = obj.delete = function() {
          throw new Error("set is read-only");
        };
      }
      Object.freeze(obj);
      Object.getOwnPropertyNames(obj).forEach((name) => {
        const prop = obj[name];
        const type = typeof prop;
        if ((type === "object" || type === "function") && !Object.isFrozen(prop)) {
          deepFreeze(prop);
        }
      });
      return obj;
    }
    var Response2 = class {
      /**
       * @param {CompiledMode} mode
       */
      constructor(mode) {
        if (mode.data === void 0) mode.data = {};
        this.data = mode.data;
        this.isMatchIgnored = false;
      }
      ignoreMatch() {
        this.isMatchIgnored = true;
      }
    };
    function escapeHTML(value) {
      return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#x27;");
    }
    function inherit$1(original, ...objects) {
      const result = /* @__PURE__ */ Object.create(null);
      for (const key in original) {
        result[key] = original[key];
      }
      objects.forEach(function(obj) {
        for (const key in obj) {
          result[key] = obj[key];
        }
      });
      return (
        /** @type {T} */
        result
      );
    }
    var SPAN_CLOSE = "</span>";
    var emitsWrappingTags = (node) => {
      return !!node.scope;
    };
    var scopeToCSSClass = (name, { prefix }) => {
      if (name.startsWith("language:")) {
        return name.replace("language:", "language-");
      }
      if (name.includes(".")) {
        const pieces = name.split(".");
        return [
          `${prefix}${pieces.shift()}`,
          ...pieces.map((x, i) => `${x}${"_".repeat(i + 1)}`)
        ].join(" ");
      }
      return `${prefix}${name}`;
    };
    var HTMLRenderer = class {
      /**
       * Creates a new HTMLRenderer
       *
       * @param {Tree} parseTree - the parse tree (must support `walk` API)
       * @param {{classPrefix: string}} options
       */
      constructor(parseTree, options) {
        this.buffer = "";
        this.classPrefix = options.classPrefix;
        parseTree.walk(this);
      }
      /**
       * Adds texts to the output stream
       *
       * @param {string} text */
      addText(text) {
        this.buffer += escapeHTML(text);
      }
      /**
       * Adds a node open to the output stream (if needed)
       *
       * @param {Node} node */
      openNode(node) {
        if (!emitsWrappingTags(node)) return;
        const className = scopeToCSSClass(
          node.scope,
          { prefix: this.classPrefix }
        );
        this.span(className);
      }
      /**
       * Adds a node close to the output stream (if needed)
       *
       * @param {Node} node */
      closeNode(node) {
        if (!emitsWrappingTags(node)) return;
        this.buffer += SPAN_CLOSE;
      }
      /**
       * returns the accumulated buffer
      */
      value() {
        return this.buffer;
      }
      // helpers
      /**
       * Builds a span element
       *
       * @param {string} className */
      span(className) {
        this.buffer += `<span class="${className}">`;
      }
    };
    var newNode = (opts = {}) => {
      const result = { children: [] };
      Object.assign(result, opts);
      return result;
    };
    var TokenTree = class _TokenTree {
      constructor() {
        this.rootNode = newNode();
        this.stack = [this.rootNode];
      }
      get top() {
        return this.stack[this.stack.length - 1];
      }
      get root() {
        return this.rootNode;
      }
      /** @param {Node} node */
      add(node) {
        this.top.children.push(node);
      }
      /** @param {string} scope */
      openNode(scope) {
        const node = newNode({ scope });
        this.add(node);
        this.stack.push(node);
      }
      closeNode() {
        if (this.stack.length > 1) {
          return this.stack.pop();
        }
        return void 0;
      }
      closeAllNodes() {
        while (this.closeNode()) ;
      }
      toJSON() {
        return JSON.stringify(this.rootNode, null, 4);
      }
      /**
       * @typedef { import("./html_renderer").Renderer } Renderer
       * @param {Renderer} builder
       */
      walk(builder) {
        return this.constructor._walk(builder, this.rootNode);
      }
      /**
       * @param {Renderer} builder
       * @param {Node} node
       */
      static _walk(builder, node) {
        if (typeof node === "string") {
          builder.addText(node);
        } else if (node.children) {
          builder.openNode(node);
          node.children.forEach((child) => this._walk(builder, child));
          builder.closeNode(node);
        }
        return builder;
      }
      /**
       * @param {Node} node
       */
      static _collapse(node) {
        if (typeof node === "string") return;
        if (!node.children) return;
        if (node.children.every((el) => typeof el === "string")) {
          node.children = [node.children.join("")];
        } else {
          node.children.forEach((child) => {
            _TokenTree._collapse(child);
          });
        }
      }
    };
    var TokenTreeEmitter = class extends TokenTree {
      /**
       * @param {*} options
       */
      constructor(options) {
        super();
        this.options = options;
      }
      /**
       * @param {string} text
       */
      addText(text) {
        if (text === "") {
          return;
        }
        this.add(text);
      }
      /** @param {string} scope */
      startScope(scope) {
        this.openNode(scope);
      }
      endScope() {
        this.closeNode();
      }
      /**
       * @param {Emitter & {root: DataNode}} emitter
       * @param {string} name
       */
      __addSublanguage(emitter, name) {
        const node = emitter.root;
        if (name) node.scope = `language:${name}`;
        this.add(node);
      }
      toHTML() {
        const renderer = new HTMLRenderer(this, this.options);
        return renderer.value();
      }
      finalize() {
        this.closeAllNodes();
        return true;
      }
    };
    function source2(re) {
      if (!re) return null;
      if (typeof re === "string") return re;
      return re.source;
    }
    function lookahead2(re) {
      return concat2("(?=", re, ")");
    }
    function anyNumberOfTimes(re) {
      return concat2("(?:", re, ")*");
    }
    function optional(re) {
      return concat2("(?:", re, ")?");
    }
    function concat2(...args) {
      const joined = args.map((x) => source2(x)).join("");
      return joined;
    }
    function stripOptionsFromArgs2(args) {
      const opts = args[args.length - 1];
      if (typeof opts === "object" && opts.constructor === Object) {
        args.splice(args.length - 1, 1);
        return opts;
      } else {
        return {};
      }
    }
    function either2(...args) {
      const opts = stripOptionsFromArgs2(args);
      const joined = "(" + (opts.capture ? "" : "?:") + args.map((x) => source2(x)).join("|") + ")";
      return joined;
    }
    function countMatchGroups(re) {
      return new RegExp(re.toString() + "|").exec("").length - 1;
    }
    function startsWith(re, lexeme) {
      const match = re && re.exec(lexeme);
      return match && match.index === 0;
    }
    var BACKREF_RE = /\[(?:[^\\\]]|\\.)*\]|\(\??|\\([1-9][0-9]*)|\\./;
    function _rewriteBackreferences(regexps, { joinWith }) {
      let numCaptures = 0;
      return regexps.map((regex) => {
        numCaptures += 1;
        const offset = numCaptures;
        let re = source2(regex);
        let out = "";
        while (re.length > 0) {
          const match = BACKREF_RE.exec(re);
          if (!match) {
            out += re;
            break;
          }
          out += re.substring(0, match.index);
          re = re.substring(match.index + match[0].length);
          if (match[0][0] === "\\" && match[1]) {
            out += "\\" + String(Number(match[1]) + offset);
          } else {
            out += match[0];
            if (match[0] === "(") {
              numCaptures++;
            }
          }
        }
        return out;
      }).map((re) => `(${re})`).join(joinWith);
    }
    var MATCH_NOTHING_RE = /\b\B/;
    var IDENT_RE3 = "[a-zA-Z]\\w*";
    var UNDERSCORE_IDENT_RE = "[a-zA-Z_]\\w*";
    var NUMBER_RE = "\\b\\d+(\\.\\d+)?";
    var C_NUMBER_RE = "(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)";
    var BINARY_NUMBER_RE = "\\b(0b[01]+)";
    var RE_STARTERS_RE = "!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~";
    var SHEBANG = (opts = {}) => {
      const beginShebang = /^#![ ]*\//;
      if (opts.binary) {
        opts.begin = concat2(
          beginShebang,
          /.*\b/,
          opts.binary,
          /\b.*/
        );
      }
      return inherit$1({
        scope: "meta",
        begin: beginShebang,
        end: /$/,
        relevance: 0,
        /** @type {ModeCallback} */
        "on:begin": (m, resp) => {
          if (m.index !== 0) resp.ignoreMatch();
        }
      }, opts);
    };
    var BACKSLASH_ESCAPE = {
      begin: "\\\\[\\s\\S]",
      relevance: 0
    };
    var APOS_STRING_MODE = {
      scope: "string",
      begin: "'",
      end: "'",
      illegal: "\\n",
      contains: [BACKSLASH_ESCAPE]
    };
    var QUOTE_STRING_MODE = {
      scope: "string",
      begin: '"',
      end: '"',
      illegal: "\\n",
      contains: [BACKSLASH_ESCAPE]
    };
    var PHRASAL_WORDS_MODE = {
      begin: /\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/
    };
    var COMMENT = function(begin, end, modeOptions = {}) {
      const mode = inherit$1(
        {
          scope: "comment",
          begin,
          end,
          contains: []
        },
        modeOptions
      );
      mode.contains.push({
        scope: "doctag",
        // hack to avoid the space from being included. the space is necessary to
        // match here to prevent the plain text rule below from gobbling up doctags
        begin: "[ ]*(?=(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):)",
        end: /(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):/,
        excludeBegin: true,
        relevance: 0
      });
      const ENGLISH_WORD = either2(
        // list of common 1 and 2 letter words in English
        "I",
        "a",
        "is",
        "so",
        "us",
        "to",
        "at",
        "if",
        "in",
        "it",
        "on",
        // note: this is not an exhaustive list of contractions, just popular ones
        /[A-Za-z]+['](d|ve|re|ll|t|s|n)/,
        // contractions - can't we'd they're let's, etc
        /[A-Za-z]+[-][a-z]+/,
        // `no-way`, etc.
        /[A-Za-z][a-z]{2,}/
        // allow capitalized words at beginning of sentences
      );
      mode.contains.push(
        {
          // TODO: how to include ", (, ) without breaking grammars that use these for
          // comment delimiters?
          // begin: /[ ]+([()"]?([A-Za-z'-]{3,}|is|a|I|so|us|[tT][oO]|at|if|in|it|on)[.]?[()":]?([.][ ]|[ ]|\))){3}/
          // ---
          // this tries to find sequences of 3 english words in a row (without any
          // "programming" type syntax) this gives us a strong signal that we've
          // TRULY found a comment - vs perhaps scanning with the wrong language.
          // It's possible to find something that LOOKS like the start of the
          // comment - but then if there is no readable text - good chance it is a
          // false match and not a comment.
          //
          // for a visual example please see:
          // https://github.com/highlightjs/highlight.js/issues/2827
          begin: concat2(
            /[ ]+/,
            // necessary to prevent us gobbling up doctags like /* @author Bob Mcgill */
            "(",
            ENGLISH_WORD,
            /[.]?[:]?([.][ ]|[ ])/,
            "){3}"
          )
          // look for 3 words in a row
        }
      );
      return mode;
    };
    var C_LINE_COMMENT_MODE = COMMENT("//", "$");
    var C_BLOCK_COMMENT_MODE = COMMENT("/\\*", "\\*/");
    var HASH_COMMENT_MODE = COMMENT("#", "$");
    var NUMBER_MODE = {
      scope: "number",
      begin: NUMBER_RE,
      relevance: 0
    };
    var C_NUMBER_MODE = {
      scope: "number",
      begin: C_NUMBER_RE,
      relevance: 0
    };
    var BINARY_NUMBER_MODE = {
      scope: "number",
      begin: BINARY_NUMBER_RE,
      relevance: 0
    };
    var REGEXP_MODE = {
      scope: "regexp",
      begin: /\/(?=[^/\n]*\/)/,
      end: /\/[gimuy]*/,
      contains: [
        BACKSLASH_ESCAPE,
        {
          begin: /\[/,
          end: /\]/,
          relevance: 0,
          contains: [BACKSLASH_ESCAPE]
        }
      ]
    };
    var TITLE_MODE = {
      scope: "title",
      begin: IDENT_RE3,
      relevance: 0
    };
    var UNDERSCORE_TITLE_MODE = {
      scope: "title",
      begin: UNDERSCORE_IDENT_RE,
      relevance: 0
    };
    var METHOD_GUARD = {
      // excludes method names from keyword processing
      begin: "\\.\\s*" + UNDERSCORE_IDENT_RE,
      relevance: 0
    };
    var END_SAME_AS_BEGIN = function(mode) {
      return Object.assign(
        mode,
        {
          /** @type {ModeCallback} */
          "on:begin": (m, resp) => {
            resp.data._beginMatch = m[1];
          },
          /** @type {ModeCallback} */
          "on:end": (m, resp) => {
            if (resp.data._beginMatch !== m[1]) resp.ignoreMatch();
          }
        }
      );
    };
    var MODES4 = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      APOS_STRING_MODE,
      BACKSLASH_ESCAPE,
      BINARY_NUMBER_MODE,
      BINARY_NUMBER_RE,
      COMMENT,
      C_BLOCK_COMMENT_MODE,
      C_LINE_COMMENT_MODE,
      C_NUMBER_MODE,
      C_NUMBER_RE,
      END_SAME_AS_BEGIN,
      HASH_COMMENT_MODE,
      IDENT_RE: IDENT_RE3,
      MATCH_NOTHING_RE,
      METHOD_GUARD,
      NUMBER_MODE,
      NUMBER_RE,
      PHRASAL_WORDS_MODE,
      QUOTE_STRING_MODE,
      REGEXP_MODE,
      RE_STARTERS_RE,
      SHEBANG,
      TITLE_MODE,
      UNDERSCORE_IDENT_RE,
      UNDERSCORE_TITLE_MODE
    });
    function skipIfHasPrecedingDot(match, response) {
      const before = match.input[match.index - 1];
      if (before === ".") {
        response.ignoreMatch();
      }
    }
    function scopeClassName(mode, _parent) {
      if (mode.className !== void 0) {
        mode.scope = mode.className;
        delete mode.className;
      }
    }
    function beginKeywords(mode, parent) {
      if (!parent) return;
      if (!mode.beginKeywords) return;
      mode.begin = "\\b(" + mode.beginKeywords.split(" ").join("|") + ")(?!\\.)(?=\\b|\\s)";
      mode.__beforeBegin = skipIfHasPrecedingDot;
      mode.keywords = mode.keywords || mode.beginKeywords;
      delete mode.beginKeywords;
      if (mode.relevance === void 0) mode.relevance = 0;
    }
    function compileIllegal(mode, _parent) {
      if (!Array.isArray(mode.illegal)) return;
      mode.illegal = either2(...mode.illegal);
    }
    function compileMatch(mode, _parent) {
      if (!mode.match) return;
      if (mode.begin || mode.end) throw new Error("begin & end are not supported with match");
      mode.begin = mode.match;
      delete mode.match;
    }
    function compileRelevance(mode, _parent) {
      if (mode.relevance === void 0) mode.relevance = 1;
    }
    var beforeMatchExt = (mode, parent) => {
      if (!mode.beforeMatch) return;
      if (mode.starts) throw new Error("beforeMatch cannot be used with starts");
      const originalMode = Object.assign({}, mode);
      Object.keys(mode).forEach((key) => {
        delete mode[key];
      });
      mode.keywords = originalMode.keywords;
      mode.begin = concat2(originalMode.beforeMatch, lookahead2(originalMode.begin));
      mode.starts = {
        relevance: 0,
        contains: [
          Object.assign(originalMode, { endsParent: true })
        ]
      };
      mode.relevance = 0;
      delete originalMode.beforeMatch;
    };
    var COMMON_KEYWORDS = [
      "of",
      "and",
      "for",
      "in",
      "not",
      "or",
      "if",
      "then",
      "parent",
      // common variable name
      "list",
      // common variable name
      "value"
      // common variable name
    ];
    var DEFAULT_KEYWORD_SCOPE = "keyword";
    function compileKeywords(rawKeywords, caseInsensitive, scopeName = DEFAULT_KEYWORD_SCOPE) {
      const compiledKeywords = /* @__PURE__ */ Object.create(null);
      if (typeof rawKeywords === "string") {
        compileList(scopeName, rawKeywords.split(" "));
      } else if (Array.isArray(rawKeywords)) {
        compileList(scopeName, rawKeywords);
      } else {
        Object.keys(rawKeywords).forEach(function(scopeName2) {
          Object.assign(
            compiledKeywords,
            compileKeywords(rawKeywords[scopeName2], caseInsensitive, scopeName2)
          );
        });
      }
      return compiledKeywords;
      function compileList(scopeName2, keywordList) {
        if (caseInsensitive) {
          keywordList = keywordList.map((x) => x.toLowerCase());
        }
        keywordList.forEach(function(keyword) {
          const pair = keyword.split("|");
          compiledKeywords[pair[0]] = [scopeName2, scoreForKeyword(pair[0], pair[1])];
        });
      }
    }
    function scoreForKeyword(keyword, providedScore) {
      if (providedScore) {
        return Number(providedScore);
      }
      return commonKeyword(keyword) ? 0 : 1;
    }
    function commonKeyword(keyword) {
      return COMMON_KEYWORDS.includes(keyword.toLowerCase());
    }
    var seenDeprecations = {};
    var error = (message) => {
      console.error(message);
    };
    var warn = (message, ...args) => {
      console.log(`WARN: ${message}`, ...args);
    };
    var deprecated = (version2, message) => {
      if (seenDeprecations[`${version2}/${message}`]) return;
      console.log(`Deprecated as of ${version2}. ${message}`);
      seenDeprecations[`${version2}/${message}`] = true;
    };
    var MultiClassError = new Error();
    function remapScopeNames(mode, regexes, { key }) {
      let offset = 0;
      const scopeNames = mode[key];
      const emit = {};
      const positions = {};
      for (let i = 1; i <= regexes.length; i++) {
        positions[i + offset] = scopeNames[i];
        emit[i + offset] = true;
        offset += countMatchGroups(regexes[i - 1]);
      }
      mode[key] = positions;
      mode[key]._emit = emit;
      mode[key]._multi = true;
    }
    function beginMultiClass(mode) {
      if (!Array.isArray(mode.begin)) return;
      if (mode.skip || mode.excludeBegin || mode.returnBegin) {
        error("skip, excludeBegin, returnBegin not compatible with beginScope: {}");
        throw MultiClassError;
      }
      if (typeof mode.beginScope !== "object" || mode.beginScope === null) {
        error("beginScope must be object");
        throw MultiClassError;
      }
      remapScopeNames(mode, mode.begin, { key: "beginScope" });
      mode.begin = _rewriteBackreferences(mode.begin, { joinWith: "" });
    }
    function endMultiClass(mode) {
      if (!Array.isArray(mode.end)) return;
      if (mode.skip || mode.excludeEnd || mode.returnEnd) {
        error("skip, excludeEnd, returnEnd not compatible with endScope: {}");
        throw MultiClassError;
      }
      if (typeof mode.endScope !== "object" || mode.endScope === null) {
        error("endScope must be object");
        throw MultiClassError;
      }
      remapScopeNames(mode, mode.end, { key: "endScope" });
      mode.end = _rewriteBackreferences(mode.end, { joinWith: "" });
    }
    function scopeSugar(mode) {
      if (mode.scope && typeof mode.scope === "object" && mode.scope !== null) {
        mode.beginScope = mode.scope;
        delete mode.scope;
      }
    }
    function MultiClass(mode) {
      scopeSugar(mode);
      if (typeof mode.beginScope === "string") {
        mode.beginScope = { _wrap: mode.beginScope };
      }
      if (typeof mode.endScope === "string") {
        mode.endScope = { _wrap: mode.endScope };
      }
      beginMultiClass(mode);
      endMultiClass(mode);
    }
    function compileLanguage(language) {
      function langRe(value, global2) {
        return new RegExp(
          source2(value),
          "m" + (language.case_insensitive ? "i" : "") + (language.unicodeRegex ? "u" : "") + (global2 ? "g" : "")
        );
      }
      class MultiRegex {
        constructor() {
          this.matchIndexes = {};
          this.regexes = [];
          this.matchAt = 1;
          this.position = 0;
        }
        // @ts-ignore
        addRule(re, opts) {
          opts.position = this.position++;
          this.matchIndexes[this.matchAt] = opts;
          this.regexes.push([opts, re]);
          this.matchAt += countMatchGroups(re) + 1;
        }
        compile() {
          if (this.regexes.length === 0) {
            this.exec = () => null;
          }
          const terminators = this.regexes.map((el) => el[1]);
          this.matcherRe = langRe(_rewriteBackreferences(terminators, { joinWith: "|" }), true);
          this.lastIndex = 0;
        }
        /** @param {string} s */
        exec(s) {
          this.matcherRe.lastIndex = this.lastIndex;
          const match = this.matcherRe.exec(s);
          if (!match) {
            return null;
          }
          const i = match.findIndex((el, i2) => i2 > 0 && el !== void 0);
          const matchData = this.matchIndexes[i];
          match.splice(0, i);
          return Object.assign(match, matchData);
        }
      }
      class ResumableMultiRegex {
        constructor() {
          this.rules = [];
          this.multiRegexes = [];
          this.count = 0;
          this.lastIndex = 0;
          this.regexIndex = 0;
        }
        // @ts-ignore
        getMatcher(index) {
          if (this.multiRegexes[index]) return this.multiRegexes[index];
          const matcher = new MultiRegex();
          this.rules.slice(index).forEach(([re, opts]) => matcher.addRule(re, opts));
          matcher.compile();
          this.multiRegexes[index] = matcher;
          return matcher;
        }
        resumingScanAtSamePosition() {
          return this.regexIndex !== 0;
        }
        considerAll() {
          this.regexIndex = 0;
        }
        // @ts-ignore
        addRule(re, opts) {
          this.rules.push([re, opts]);
          if (opts.type === "begin") this.count++;
        }
        /** @param {string} s */
        exec(s) {
          const m = this.getMatcher(this.regexIndex);
          m.lastIndex = this.lastIndex;
          let result = m.exec(s);
          if (this.resumingScanAtSamePosition()) {
            if (result && result.index === this.lastIndex) ;
            else {
              const m2 = this.getMatcher(0);
              m2.lastIndex = this.lastIndex + 1;
              result = m2.exec(s);
            }
          }
          if (result) {
            this.regexIndex += result.position + 1;
            if (this.regexIndex === this.count) {
              this.considerAll();
            }
          }
          return result;
        }
      }
      function buildModeRegex(mode) {
        const mm = new ResumableMultiRegex();
        mode.contains.forEach((term) => mm.addRule(term.begin, { rule: term, type: "begin" }));
        if (mode.terminatorEnd) {
          mm.addRule(mode.terminatorEnd, { type: "end" });
        }
        if (mode.illegal) {
          mm.addRule(mode.illegal, { type: "illegal" });
        }
        return mm;
      }
      function compileMode(mode, parent) {
        const cmode = (
          /** @type CompiledMode */
          mode
        );
        if (mode.isCompiled) return cmode;
        [
          scopeClassName,
          // do this early so compiler extensions generally don't have to worry about
          // the distinction between match/begin
          compileMatch,
          MultiClass,
          beforeMatchExt
        ].forEach((ext) => ext(mode, parent));
        language.compilerExtensions.forEach((ext) => ext(mode, parent));
        mode.__beforeBegin = null;
        [
          beginKeywords,
          // do this later so compiler extensions that come earlier have access to the
          // raw array if they wanted to perhaps manipulate it, etc.
          compileIllegal,
          // default to 1 relevance if not specified
          compileRelevance
        ].forEach((ext) => ext(mode, parent));
        mode.isCompiled = true;
        let keywordPattern = null;
        if (typeof mode.keywords === "object" && mode.keywords.$pattern) {
          mode.keywords = Object.assign({}, mode.keywords);
          keywordPattern = mode.keywords.$pattern;
          delete mode.keywords.$pattern;
        }
        keywordPattern = keywordPattern || /\w+/;
        if (mode.keywords) {
          mode.keywords = compileKeywords(mode.keywords, language.case_insensitive);
        }
        cmode.keywordPatternRe = langRe(keywordPattern, true);
        if (parent) {
          if (!mode.begin) mode.begin = /\B|\b/;
          cmode.beginRe = langRe(cmode.begin);
          if (!mode.end && !mode.endsWithParent) mode.end = /\B|\b/;
          if (mode.end) cmode.endRe = langRe(cmode.end);
          cmode.terminatorEnd = source2(cmode.end) || "";
          if (mode.endsWithParent && parent.terminatorEnd) {
            cmode.terminatorEnd += (mode.end ? "|" : "") + parent.terminatorEnd;
          }
        }
        if (mode.illegal) cmode.illegalRe = langRe(
          /** @type {RegExp | string} */
          mode.illegal
        );
        if (!mode.contains) mode.contains = [];
        mode.contains = [].concat(...mode.contains.map(function(c2) {
          return expandOrCloneMode(c2 === "self" ? mode : c2);
        }));
        mode.contains.forEach(function(c2) {
          compileMode(
            /** @type Mode */
            c2,
            cmode
          );
        });
        if (mode.starts) {
          compileMode(mode.starts, parent);
        }
        cmode.matcher = buildModeRegex(cmode);
        return cmode;
      }
      if (!language.compilerExtensions) language.compilerExtensions = [];
      if (language.contains && language.contains.includes("self")) {
        throw new Error("ERR: contains `self` is not supported at the top-level of a language.  See documentation.");
      }
      language.classNameAliases = inherit$1(language.classNameAliases || {});
      return compileMode(
        /** @type Mode */
        language
      );
    }
    function dependencyOnParent(mode) {
      if (!mode) return false;
      return mode.endsWithParent || dependencyOnParent(mode.starts);
    }
    function expandOrCloneMode(mode) {
      if (mode.variants && !mode.cachedVariants) {
        mode.cachedVariants = mode.variants.map(function(variant) {
          return inherit$1(mode, { variants: null }, variant);
        });
      }
      if (mode.cachedVariants) {
        return mode.cachedVariants;
      }
      if (dependencyOnParent(mode)) {
        return inherit$1(mode, { starts: mode.starts ? inherit$1(mode.starts) : null });
      }
      if (Object.isFrozen(mode)) {
        return inherit$1(mode);
      }
      return mode;
    }
    var version = "11.11.1";
    var HTMLInjectionError = class extends Error {
      constructor(reason, html) {
        super(reason);
        this.name = "HTMLInjectionError";
        this.html = html;
      }
    };
    var escape = escapeHTML;
    var inherit = inherit$1;
    var NO_MATCH = Symbol("nomatch");
    var MAX_KEYWORD_HITS = 7;
    var HLJS = function(hljs) {
      const languages = /* @__PURE__ */ Object.create(null);
      const aliases = /* @__PURE__ */ Object.create(null);
      const plugins = [];
      let SAFE_MODE = true;
      const LANGUAGE_NOT_FOUND = "Could not find the language '{}', did you forget to load/include a language module?";
      const PLAINTEXT_LANGUAGE = { disableAutodetect: true, name: "Plain text", contains: [] };
      let options = {
        ignoreUnescapedHTML: false,
        throwUnescapedHTML: false,
        noHighlightRe: /^(no-?highlight)$/i,
        languageDetectRe: /\blang(?:uage)?-([\w-]+)\b/i,
        classPrefix: "hljs-",
        cssSelector: "pre code",
        languages: null,
        // beta configuration options, subject to change, welcome to discuss
        // https://github.com/highlightjs/highlight.js/issues/1086
        __emitter: TokenTreeEmitter
      };
      function shouldNotHighlight(languageName) {
        return options.noHighlightRe.test(languageName);
      }
      function blockLanguage(block) {
        let classes = block.className + " ";
        classes += block.parentNode ? block.parentNode.className : "";
        const match = options.languageDetectRe.exec(classes);
        if (match) {
          const language = getLanguage(match[1]);
          if (!language) {
            warn(LANGUAGE_NOT_FOUND.replace("{}", match[1]));
            warn("Falling back to no-highlight mode for this block.", block);
          }
          return language ? match[1] : "no-highlight";
        }
        return classes.split(/\s+/).find((_class) => shouldNotHighlight(_class) || getLanguage(_class));
      }
      function highlight2(codeOrLanguageName, optionsOrCode, ignoreIllegals) {
        let code = "";
        let languageName = "";
        if (typeof optionsOrCode === "object") {
          code = codeOrLanguageName;
          ignoreIllegals = optionsOrCode.ignoreIllegals;
          languageName = optionsOrCode.language;
        } else {
          deprecated("10.7.0", "highlight(lang, code, ...args) has been deprecated.");
          deprecated("10.7.0", "Please use highlight(code, options) instead.\nhttps://github.com/highlightjs/highlight.js/issues/2277");
          languageName = codeOrLanguageName;
          code = optionsOrCode;
        }
        if (ignoreIllegals === void 0) {
          ignoreIllegals = true;
        }
        const context = {
          code,
          language: languageName
        };
        fire("before:highlight", context);
        const result = context.result ? context.result : _highlight(context.language, context.code, ignoreIllegals);
        result.code = context.code;
        fire("after:highlight", result);
        return result;
      }
      function _highlight(languageName, codeToHighlight, ignoreIllegals, continuation) {
        const keywordHits = /* @__PURE__ */ Object.create(null);
        function keywordData(mode, matchText) {
          return mode.keywords[matchText];
        }
        function processKeywords() {
          if (!top.keywords) {
            emitter.addText(modeBuffer);
            return;
          }
          let lastIndex = 0;
          top.keywordPatternRe.lastIndex = 0;
          let match = top.keywordPatternRe.exec(modeBuffer);
          let buf = "";
          while (match) {
            buf += modeBuffer.substring(lastIndex, match.index);
            const word = language.case_insensitive ? match[0].toLowerCase() : match[0];
            const data = keywordData(top, word);
            if (data) {
              const [kind, keywordRelevance] = data;
              emitter.addText(buf);
              buf = "";
              keywordHits[word] = (keywordHits[word] || 0) + 1;
              if (keywordHits[word] <= MAX_KEYWORD_HITS) relevance += keywordRelevance;
              if (kind.startsWith("_")) {
                buf += match[0];
              } else {
                const cssClass = language.classNameAliases[kind] || kind;
                emitKeyword(match[0], cssClass);
              }
            } else {
              buf += match[0];
            }
            lastIndex = top.keywordPatternRe.lastIndex;
            match = top.keywordPatternRe.exec(modeBuffer);
          }
          buf += modeBuffer.substring(lastIndex);
          emitter.addText(buf);
        }
        function processSubLanguage() {
          if (modeBuffer === "") return;
          let result2 = null;
          if (typeof top.subLanguage === "string") {
            if (!languages[top.subLanguage]) {
              emitter.addText(modeBuffer);
              return;
            }
            result2 = _highlight(top.subLanguage, modeBuffer, true, continuations[top.subLanguage]);
            continuations[top.subLanguage] = /** @type {CompiledMode} */
            result2._top;
          } else {
            result2 = highlightAuto(modeBuffer, top.subLanguage.length ? top.subLanguage : null);
          }
          if (top.relevance > 0) {
            relevance += result2.relevance;
          }
          emitter.__addSublanguage(result2._emitter, result2.language);
        }
        function processBuffer() {
          if (top.subLanguage != null) {
            processSubLanguage();
          } else {
            processKeywords();
          }
          modeBuffer = "";
        }
        function emitKeyword(keyword, scope) {
          if (keyword === "") return;
          emitter.startScope(scope);
          emitter.addText(keyword);
          emitter.endScope();
        }
        function emitMultiClass(scope, match) {
          let i = 1;
          const max = match.length - 1;
          while (i <= max) {
            if (!scope._emit[i]) {
              i++;
              continue;
            }
            const klass = language.classNameAliases[scope[i]] || scope[i];
            const text = match[i];
            if (klass) {
              emitKeyword(text, klass);
            } else {
              modeBuffer = text;
              processKeywords();
              modeBuffer = "";
            }
            i++;
          }
        }
        function startNewMode(mode, match) {
          if (mode.scope && typeof mode.scope === "string") {
            emitter.openNode(language.classNameAliases[mode.scope] || mode.scope);
          }
          if (mode.beginScope) {
            if (mode.beginScope._wrap) {
              emitKeyword(modeBuffer, language.classNameAliases[mode.beginScope._wrap] || mode.beginScope._wrap);
              modeBuffer = "";
            } else if (mode.beginScope._multi) {
              emitMultiClass(mode.beginScope, match);
              modeBuffer = "";
            }
          }
          top = Object.create(mode, { parent: { value: top } });
          return top;
        }
        function endOfMode(mode, match, matchPlusRemainder) {
          let matched = startsWith(mode.endRe, matchPlusRemainder);
          if (matched) {
            if (mode["on:end"]) {
              const resp = new Response2(mode);
              mode["on:end"](match, resp);
              if (resp.isMatchIgnored) matched = false;
            }
            if (matched) {
              while (mode.endsParent && mode.parent) {
                mode = mode.parent;
              }
              return mode;
            }
          }
          if (mode.endsWithParent) {
            return endOfMode(mode.parent, match, matchPlusRemainder);
          }
        }
        function doIgnore(lexeme) {
          if (top.matcher.regexIndex === 0) {
            modeBuffer += lexeme[0];
            return 1;
          } else {
            resumeScanAtSamePosition = true;
            return 0;
          }
        }
        function doBeginMatch(match) {
          const lexeme = match[0];
          const newMode = match.rule;
          const resp = new Response2(newMode);
          const beforeCallbacks = [newMode.__beforeBegin, newMode["on:begin"]];
          for (const cb of beforeCallbacks) {
            if (!cb) continue;
            cb(match, resp);
            if (resp.isMatchIgnored) return doIgnore(lexeme);
          }
          if (newMode.skip) {
            modeBuffer += lexeme;
          } else {
            if (newMode.excludeBegin) {
              modeBuffer += lexeme;
            }
            processBuffer();
            if (!newMode.returnBegin && !newMode.excludeBegin) {
              modeBuffer = lexeme;
            }
          }
          startNewMode(newMode, match);
          return newMode.returnBegin ? 0 : lexeme.length;
        }
        function doEndMatch(match) {
          const lexeme = match[0];
          const matchPlusRemainder = codeToHighlight.substring(match.index);
          const endMode = endOfMode(top, match, matchPlusRemainder);
          if (!endMode) {
            return NO_MATCH;
          }
          const origin = top;
          if (top.endScope && top.endScope._wrap) {
            processBuffer();
            emitKeyword(lexeme, top.endScope._wrap);
          } else if (top.endScope && top.endScope._multi) {
            processBuffer();
            emitMultiClass(top.endScope, match);
          } else if (origin.skip) {
            modeBuffer += lexeme;
          } else {
            if (!(origin.returnEnd || origin.excludeEnd)) {
              modeBuffer += lexeme;
            }
            processBuffer();
            if (origin.excludeEnd) {
              modeBuffer = lexeme;
            }
          }
          do {
            if (top.scope) {
              emitter.closeNode();
            }
            if (!top.skip && !top.subLanguage) {
              relevance += top.relevance;
            }
            top = top.parent;
          } while (top !== endMode.parent);
          if (endMode.starts) {
            startNewMode(endMode.starts, match);
          }
          return origin.returnEnd ? 0 : lexeme.length;
        }
        function processContinuations() {
          const list = [];
          for (let current = top; current !== language; current = current.parent) {
            if (current.scope) {
              list.unshift(current.scope);
            }
          }
          list.forEach((item) => emitter.openNode(item));
        }
        let lastMatch = {};
        function processLexeme(textBeforeMatch, match) {
          const lexeme = match && match[0];
          modeBuffer += textBeforeMatch;
          if (lexeme == null) {
            processBuffer();
            return 0;
          }
          if (lastMatch.type === "begin" && match.type === "end" && lastMatch.index === match.index && lexeme === "") {
            modeBuffer += codeToHighlight.slice(match.index, match.index + 1);
            if (!SAFE_MODE) {
              const err = new Error(`0 width match regex (${languageName})`);
              err.languageName = languageName;
              err.badRule = lastMatch.rule;
              throw err;
            }
            return 1;
          }
          lastMatch = match;
          if (match.type === "begin") {
            return doBeginMatch(match);
          } else if (match.type === "illegal" && !ignoreIllegals) {
            const err = new Error('Illegal lexeme "' + lexeme + '" for mode "' + (top.scope || "<unnamed>") + '"');
            err.mode = top;
            throw err;
          } else if (match.type === "end") {
            const processed = doEndMatch(match);
            if (processed !== NO_MATCH) {
              return processed;
            }
          }
          if (match.type === "illegal" && lexeme === "") {
            modeBuffer += "\n";
            return 1;
          }
          if (iterations > 1e5 && iterations > match.index * 3) {
            const err = new Error("potential infinite loop, way more iterations than matches");
            throw err;
          }
          modeBuffer += lexeme;
          return lexeme.length;
        }
        const language = getLanguage(languageName);
        if (!language) {
          error(LANGUAGE_NOT_FOUND.replace("{}", languageName));
          throw new Error('Unknown language: "' + languageName + '"');
        }
        const md = compileLanguage(language);
        let result = "";
        let top = continuation || md;
        const continuations = {};
        const emitter = new options.__emitter(options);
        processContinuations();
        let modeBuffer = "";
        let relevance = 0;
        let index = 0;
        let iterations = 0;
        let resumeScanAtSamePosition = false;
        try {
          if (!language.__emitTokens) {
            top.matcher.considerAll();
            for (; ; ) {
              iterations++;
              if (resumeScanAtSamePosition) {
                resumeScanAtSamePosition = false;
              } else {
                top.matcher.considerAll();
              }
              top.matcher.lastIndex = index;
              const match = top.matcher.exec(codeToHighlight);
              if (!match) break;
              const beforeMatch = codeToHighlight.substring(index, match.index);
              const processedCount = processLexeme(beforeMatch, match);
              index = match.index + processedCount;
            }
            processLexeme(codeToHighlight.substring(index));
          } else {
            language.__emitTokens(codeToHighlight, emitter);
          }
          emitter.finalize();
          result = emitter.toHTML();
          return {
            language: languageName,
            value: result,
            relevance,
            illegal: false,
            _emitter: emitter,
            _top: top
          };
        } catch (err) {
          if (err.message && err.message.includes("Illegal")) {
            return {
              language: languageName,
              value: escape(codeToHighlight),
              illegal: true,
              relevance: 0,
              _illegalBy: {
                message: err.message,
                index,
                context: codeToHighlight.slice(index - 100, index + 100),
                mode: err.mode,
                resultSoFar: result
              },
              _emitter: emitter
            };
          } else if (SAFE_MODE) {
            return {
              language: languageName,
              value: escape(codeToHighlight),
              illegal: false,
              relevance: 0,
              errorRaised: err,
              _emitter: emitter,
              _top: top
            };
          } else {
            throw err;
          }
        }
      }
      function justTextHighlightResult(code) {
        const result = {
          value: escape(code),
          illegal: false,
          relevance: 0,
          _top: PLAINTEXT_LANGUAGE,
          _emitter: new options.__emitter(options)
        };
        result._emitter.addText(code);
        return result;
      }
      function highlightAuto(code, languageSubset) {
        languageSubset = languageSubset || options.languages || Object.keys(languages);
        const plaintext2 = justTextHighlightResult(code);
        const results = languageSubset.filter(getLanguage).filter(autoDetection).map(
          (name) => _highlight(name, code, false)
        );
        results.unshift(plaintext2);
        const sorted = results.sort((a, b) => {
          if (a.relevance !== b.relevance) return b.relevance - a.relevance;
          if (a.language && b.language) {
            if (getLanguage(a.language).supersetOf === b.language) {
              return 1;
            } else if (getLanguage(b.language).supersetOf === a.language) {
              return -1;
            }
          }
          return 0;
        });
        const [best, secondBest] = sorted;
        const result = best;
        result.secondBest = secondBest;
        return result;
      }
      function updateClassName(element, currentLang, resultLang) {
        const language = currentLang && aliases[currentLang] || resultLang;
        element.classList.add("hljs");
        element.classList.add(`language-${language}`);
      }
      function highlightElement(element) {
        let node = null;
        const language = blockLanguage(element);
        if (shouldNotHighlight(language)) return;
        fire(
          "before:highlightElement",
          { el: element, language }
        );
        if (element.dataset.highlighted) {
          console.log("Element previously highlighted. To highlight again, first unset `dataset.highlighted`.", element);
          return;
        }
        if (element.children.length > 0) {
          if (!options.ignoreUnescapedHTML) {
            console.warn("One of your code blocks includes unescaped HTML. This is a potentially serious security risk.");
            console.warn("https://github.com/highlightjs/highlight.js/wiki/security");
            console.warn("The element with unescaped HTML:");
            console.warn(element);
          }
          if (options.throwUnescapedHTML) {
            const err = new HTMLInjectionError(
              "One of your code blocks includes unescaped HTML.",
              element.innerHTML
            );
            throw err;
          }
        }
        node = element;
        const text = node.textContent;
        const result = language ? highlight2(text, { language, ignoreIllegals: true }) : highlightAuto(text);
        element.innerHTML = result.value;
        element.dataset.highlighted = "yes";
        updateClassName(element, language, result.language);
        element.result = {
          language: result.language,
          // TODO: remove with version 11.0
          re: result.relevance,
          relevance: result.relevance
        };
        if (result.secondBest) {
          element.secondBest = {
            language: result.secondBest.language,
            relevance: result.secondBest.relevance
          };
        }
        fire("after:highlightElement", { el: element, result, text });
      }
      function configure(userOptions) {
        options = inherit(options, userOptions);
      }
      const initHighlighting = () => {
        highlightAll();
        deprecated("10.6.0", "initHighlighting() deprecated.  Use highlightAll() now.");
      };
      function initHighlightingOnLoad() {
        highlightAll();
        deprecated("10.6.0", "initHighlightingOnLoad() deprecated.  Use highlightAll() now.");
      }
      let wantsHighlight = false;
      function highlightAll() {
        function boot() {
          highlightAll();
        }
        if (document.readyState === "loading") {
          if (!wantsHighlight) {
            window.addEventListener("DOMContentLoaded", boot, false);
          }
          wantsHighlight = true;
          return;
        }
        const blocks = document.querySelectorAll(options.cssSelector);
        blocks.forEach(highlightElement);
      }
      function registerLanguage(languageName, languageDefinition) {
        let lang = null;
        try {
          lang = languageDefinition(hljs);
        } catch (error$1) {
          error("Language definition for '{}' could not be registered.".replace("{}", languageName));
          if (!SAFE_MODE) {
            throw error$1;
          } else {
            error(error$1);
          }
          lang = PLAINTEXT_LANGUAGE;
        }
        if (!lang.name) lang.name = languageName;
        languages[languageName] = lang;
        lang.rawDefinition = languageDefinition.bind(null, hljs);
        if (lang.aliases) {
          registerAliases(lang.aliases, { languageName });
        }
      }
      function unregisterLanguage(languageName) {
        delete languages[languageName];
        for (const alias of Object.keys(aliases)) {
          if (aliases[alias] === languageName) {
            delete aliases[alias];
          }
        }
      }
      function listLanguages() {
        return Object.keys(languages);
      }
      function getLanguage(name) {
        name = (name || "").toLowerCase();
        return languages[name] || languages[aliases[name]];
      }
      function registerAliases(aliasList, { languageName }) {
        if (typeof aliasList === "string") {
          aliasList = [aliasList];
        }
        aliasList.forEach((alias) => {
          aliases[alias.toLowerCase()] = languageName;
        });
      }
      function autoDetection(name) {
        const lang = getLanguage(name);
        return lang && !lang.disableAutodetect;
      }
      function upgradePluginAPI(plugin) {
        if (plugin["before:highlightBlock"] && !plugin["before:highlightElement"]) {
          plugin["before:highlightElement"] = (data) => {
            plugin["before:highlightBlock"](
              Object.assign({ block: data.el }, data)
            );
          };
        }
        if (plugin["after:highlightBlock"] && !plugin["after:highlightElement"]) {
          plugin["after:highlightElement"] = (data) => {
            plugin["after:highlightBlock"](
              Object.assign({ block: data.el }, data)
            );
          };
        }
      }
      function addPlugin(plugin) {
        upgradePluginAPI(plugin);
        plugins.push(plugin);
      }
      function removePlugin(plugin) {
        const index = plugins.indexOf(plugin);
        if (index !== -1) {
          plugins.splice(index, 1);
        }
      }
      function fire(event, args) {
        const cb = event;
        plugins.forEach(function(plugin) {
          if (plugin[cb]) {
            plugin[cb](args);
          }
        });
      }
      function deprecateHighlightBlock(el) {
        deprecated("10.7.0", "highlightBlock will be removed entirely in v12.0");
        deprecated("10.7.0", "Please use highlightElement now.");
        return highlightElement(el);
      }
      Object.assign(hljs, {
        highlight: highlight2,
        highlightAuto,
        highlightAll,
        highlightElement,
        // TODO: Remove with v12 API
        highlightBlock: deprecateHighlightBlock,
        configure,
        initHighlighting,
        initHighlightingOnLoad,
        registerLanguage,
        unregisterLanguage,
        listLanguages,
        getLanguage,
        registerAliases,
        autoDetection,
        inherit,
        addPlugin,
        removePlugin
      });
      hljs.debugMode = function() {
        SAFE_MODE = false;
      };
      hljs.safeMode = function() {
        SAFE_MODE = true;
      };
      hljs.versionString = version;
      hljs.regex = {
        concat: concat2,
        lookahead: lookahead2,
        either: either2,
        optional,
        anyNumberOfTimes
      };
      for (const key in MODES4) {
        if (typeof MODES4[key] === "object") {
          deepFreeze(MODES4[key]);
        }
      }
      Object.assign(hljs, MODES4);
      return hljs;
    };
    var highlight = HLJS({});
    highlight.newInstance = () => HLJS({});
    module.exports = highlight;
    highlight.HighlightJS = highlight;
    highlight.default = highlight;
  }
});

// node_modules/prop-types/lib/ReactPropTypesSecret.js
var require_ReactPropTypesSecret = __commonJS({
  "node_modules/prop-types/lib/ReactPropTypesSecret.js"(exports, module) {
    "use strict";
    var ReactPropTypesSecret = "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED";
    module.exports = ReactPropTypesSecret;
  }
});

// node_modules/prop-types/factoryWithThrowingShims.js
var require_factoryWithThrowingShims = __commonJS({
  "node_modules/prop-types/factoryWithThrowingShims.js"(exports, module) {
    "use strict";
    var ReactPropTypesSecret = require_ReactPropTypesSecret();
    function emptyFunction() {
    }
    function emptyFunctionWithReset() {
    }
    emptyFunctionWithReset.resetWarningCache = emptyFunction;
    module.exports = function() {
      function shim(props, propName, componentName, location, propFullName, secret) {
        if (secret === ReactPropTypesSecret) {
          return;
        }
        var err = new Error(
          "Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types"
        );
        err.name = "Invariant Violation";
        throw err;
      }
      ;
      shim.isRequired = shim;
      function getShim() {
        return shim;
      }
      ;
      var ReactPropTypes = {
        array: shim,
        bigint: shim,
        bool: shim,
        func: shim,
        number: shim,
        object: shim,
        string: shim,
        symbol: shim,
        any: shim,
        arrayOf: getShim,
        element: shim,
        elementType: shim,
        instanceOf: getShim,
        node: shim,
        objectOf: getShim,
        oneOf: getShim,
        oneOfType: getShim,
        shape: getShim,
        exact: getShim,
        checkPropTypes: emptyFunctionWithReset,
        resetWarningCache: emptyFunction
      };
      ReactPropTypes.PropTypes = ReactPropTypes;
      return ReactPropTypes;
    };
  }
});

// node_modules/prop-types/index.js
var require_prop_types = __commonJS({
  "node_modules/prop-types/index.js"(exports, module) {
    if (false) {
      ReactIs = null;
      throwOnDirectAccess = true;
      module.exports = null(ReactIs.isElement, throwOnDirectAccess);
    } else {
      module.exports = require_factoryWithThrowingShims()();
    }
    var ReactIs;
    var throwOnDirectAccess;
  }
});

// node_modules/gradient-string/index.js
var require_gradient_string = __commonJS({
  "node_modules/gradient-string/index.js"(exports, module) {
    "use strict";
    var chalk4 = require_source();
    var tinygradient2 = require_tinygradient();
    var forbiddenChars = /\s/g;
    function InitGradient(...args) {
      const grad = tinygradient2.apply(this, args);
      const ret = (str, opts) => applyGradient(str ? str.toString() : "", grad, opts);
      ret.multiline = (str, opts) => multilineGradient(str ? str.toString() : "", grad, opts);
      return ret;
    }
    var getColors = (gradient, options, count) => options.interpolation.toLowerCase() === "hsv" ? gradient.hsv(count, options.hsvSpin.toLowerCase()) : gradient.rgb(count);
    function applyGradient(str, gradient, opts) {
      const options = validateOptions(opts);
      const colorsCount = Math.max(str.replace(forbiddenChars, "").length, gradient.stops.length);
      const colors = getColors(gradient, options, colorsCount);
      let result = "";
      for (const s of str) {
        result += s.match(forbiddenChars) ? s : chalk4.hex(colors.shift().toHex())(s);
      }
      return result;
    }
    function multilineGradient(str, gradient, opts) {
      const options = validateOptions(opts);
      const lines = str.split("\n");
      const maxLength = Math.max.apply(null, lines.map((l) => l.length).concat([gradient.stops.length]));
      const colors = getColors(gradient, options, maxLength);
      const results = [];
      for (const line of lines) {
        const lineColors = colors.slice(0);
        let lineResult = "";
        for (const l of line) {
          lineResult += chalk4.hex(lineColors.shift().toHex())(l);
        }
        results.push(lineResult);
      }
      return results.join("\n");
    }
    function validateOptions(opts) {
      const options = { interpolation: "rgb", hsvSpin: "short", ...opts };
      if (opts !== void 0 && typeof opts !== "object") {
        throw new TypeError(`Expected \`options\` to be an \`object\`, got \`${typeof opts}\``);
      }
      if (typeof options.interpolation !== "string") {
        throw new TypeError(`Expected \`options.interpolation\` to be a \`string\`, got \`${typeof options.interpolation}\``);
      }
      if (options.interpolation.toLowerCase() === "hsv" && typeof options.hsvSpin !== "string") {
        throw new TypeError(`Expected \`options.hsvSpin\` to be a \`string\`, got \`${typeof options.hsvSpin}\``);
      }
      return options;
    }
    var aliases = {
      atlas: { colors: ["#feac5e", "#c779d0", "#4bc0c8"], options: {} },
      cristal: { colors: ["#bdfff3", "#4ac29a"], options: {} },
      teen: { colors: ["#77a1d3", "#79cbca", "#e684ae"], options: {} },
      mind: { colors: ["#473b7b", "#3584a7", "#30d2be"], options: {} },
      morning: { colors: ["#ff5f6d", "#ffc371"], options: { interpolation: "hsv" } },
      vice: { colors: ["#5ee7df", "#b490ca"], options: { interpolation: "hsv" } },
      passion: { colors: ["#f43b47", "#453a94"], options: {} },
      fruit: { colors: ["#ff4e50", "#f9d423"], options: {} },
      instagram: { colors: ["#833ab4", "#fd1d1d", "#fcb045"], options: {} },
      retro: { colors: ["#3f51b1", "#5a55ae", "#7b5fac", "#8f6aae", "#a86aa4", "#cc6b8e", "#f18271", "#f3a469", "#f7c978"], options: {} },
      summer: { colors: ["#fdbb2d", "#22c1c3"], options: {} },
      rainbow: { colors: ["#ff0000", "#ff0100"], options: { interpolation: "hsv", hsvSpin: "long" } },
      pastel: { colors: ["#74ebd5", "#74ecd5"], options: { interpolation: "hsv", hsvSpin: "long" } }
    };
    module.exports = InitGradient;
    for (const a in aliases) {
      module.exports[a] = (str) => new InitGradient(aliases[a].colors)(str, aliases[a].options);
      module.exports[a].multiline = (str) => new InitGradient(aliases[a].colors).multiline(str, aliases[a].options);
    }
  }
});

// node_modules/ini/ini.js
var require_ini = __commonJS({
  "node_modules/ini/ini.js"(exports) {
    exports.parse = exports.decode = decode;
    exports.stringify = exports.encode = encode;
    exports.safe = safe;
    exports.unsafe = unsafe;
    var eol = typeof process !== "undefined" && process.platform === "win32" ? "\r\n" : "\n";
    function encode(obj, opt) {
      var children = [];
      var out = "";
      if (typeof opt === "string") {
        opt = {
          section: opt,
          whitespace: false
        };
      } else {
        opt = opt || {};
        opt.whitespace = opt.whitespace === true;
      }
      var separator = opt.whitespace ? " = " : "=";
      Object.keys(obj).forEach(function(k, _, __) {
        var val = obj[k];
        if (val && Array.isArray(val)) {
          val.forEach(function(item) {
            out += safe(k + "[]") + separator + safe(item) + "\n";
          });
        } else if (val && typeof val === "object")
          children.push(k);
        else
          out += safe(k) + separator + safe(val) + eol;
      });
      if (opt.section && out.length)
        out = "[" + safe(opt.section) + "]" + eol + out;
      children.forEach(function(k, _, __) {
        var nk = dotSplit(k).join("\\.");
        var section = (opt.section ? opt.section + "." : "") + nk;
        var child = encode(obj[k], {
          section,
          whitespace: opt.whitespace
        });
        if (out.length && child.length)
          out += eol;
        out += child;
      });
      return out;
    }
    function dotSplit(str) {
      return str.replace(/\1/g, "LITERAL\\1LITERAL").replace(/\\\./g, "").split(/\./).map(function(part) {
        return part.replace(/\1/g, "\\.").replace(/\2LITERAL\\1LITERAL\2/g, "");
      });
    }
    function decode(str) {
      var out = {};
      var p = out;
      var section = null;
      var re = /^\[([^\]]*)\]$|^([^=]+)(=(.*))?$/i;
      var lines = str.split(/[\r\n]+/g);
      lines.forEach(function(line, _, __) {
        if (!line || line.match(/^\s*[;#]/))
          return;
        var match = line.match(re);
        if (!match)
          return;
        if (match[1] !== void 0) {
          section = unsafe(match[1]);
          if (section === "__proto__") {
            p = {};
            return;
          }
          p = out[section] = out[section] || {};
          return;
        }
        var key = unsafe(match[2]);
        if (key === "__proto__")
          return;
        var value = match[3] ? unsafe(match[4]) : true;
        switch (value) {
          case "true":
          case "false":
          case "null":
            value = JSON.parse(value);
        }
        if (key.length > 2 && key.slice(-2) === "[]") {
          key = key.substring(0, key.length - 2);
          if (key === "__proto__")
            return;
          if (!p[key])
            p[key] = [];
          else if (!Array.isArray(p[key]))
            p[key] = [p[key]];
        }
        if (Array.isArray(p[key]))
          p[key].push(value);
        else
          p[key] = value;
      });
      Object.keys(out).filter(function(k, _, __) {
        if (!out[k] || typeof out[k] !== "object" || Array.isArray(out[k]))
          return false;
        var parts = dotSplit(k);
        var p2 = out;
        var l = parts.pop();
        var nl = l.replace(/\\\./g, ".");
        parts.forEach(function(part, _2, __2) {
          if (part === "__proto__")
            return;
          if (!p2[part] || typeof p2[part] !== "object")
            p2[part] = {};
          p2 = p2[part];
        });
        if (p2 === out && nl === l)
          return false;
        p2[nl] = out[k];
        return true;
      }).forEach(function(del, _, __) {
        delete out[del];
      });
      return out;
    }
    function isQuoted(val) {
      return val.charAt(0) === '"' && val.slice(-1) === '"' || val.charAt(0) === "'" && val.slice(-1) === "'";
    }
    function safe(val) {
      return typeof val !== "string" || val.match(/[=\r\n]/) || val.match(/^\[/) || val.length > 1 && isQuoted(val) || val !== val.trim() ? JSON.stringify(val) : val.replace(/;/g, "\\;").replace(/#/g, "\\#");
    }
    function unsafe(val, doUnesc) {
      val = (val || "").trim();
      if (isQuoted(val)) {
        if (val.charAt(0) === "'")
          val = val.substr(1, val.length - 2);
        try {
          val = JSON.parse(val);
        } catch (_) {
        }
      } else {
        var esc = false;
        var unesc = "";
        for (var i = 0, l = val.length; i < l; i++) {
          var c2 = val.charAt(i);
          if (esc) {
            if ("\\;#".indexOf(c2) !== -1)
              unesc += c2;
            else
              unesc += "\\" + c2;
            esc = false;
          } else if (";#".indexOf(c2) !== -1)
            break;
          else if (c2 === "\\")
            esc = true;
          else
            unesc += c2;
        }
        if (esc)
          unesc += "\\";
        return unesc.trim();
      }
      return val;
    }
  }
});

// node_modules/rc/node_modules/strip-json-comments/index.js
var require_strip_json_comments = __commonJS({
  "node_modules/rc/node_modules/strip-json-comments/index.js"(exports, module) {
    "use strict";
    var singleComment = 1;
    var multiComment = 2;
    function stripWithoutWhitespace() {
      return "";
    }
    function stripWithWhitespace(str, start, end) {
      return str.slice(start, end).replace(/\S/g, " ");
    }
    module.exports = function(str, opts) {
      opts = opts || {};
      var currentChar;
      var nextChar;
      var insideString = false;
      var insideComment = false;
      var offset = 0;
      var ret = "";
      var strip = opts.whitespace === false ? stripWithoutWhitespace : stripWithWhitespace;
      for (var i = 0; i < str.length; i++) {
        currentChar = str[i];
        nextChar = str[i + 1];
        if (!insideComment && currentChar === '"') {
          var escaped = str[i - 1] === "\\" && str[i - 2] !== "\\";
          if (!escaped) {
            insideString = !insideString;
          }
        }
        if (insideString) {
          continue;
        }
        if (!insideComment && currentChar + nextChar === "//") {
          ret += str.slice(offset, i);
          offset = i;
          insideComment = singleComment;
          i++;
        } else if (insideComment === singleComment && currentChar + nextChar === "\r\n") {
          i++;
          insideComment = false;
          ret += strip(str, offset, i);
          offset = i;
          continue;
        } else if (insideComment === singleComment && currentChar === "\n") {
          insideComment = false;
          ret += strip(str, offset, i);
          offset = i;
        } else if (!insideComment && currentChar + nextChar === "/*") {
          ret += str.slice(offset, i);
          offset = i;
          insideComment = multiComment;
          i++;
          continue;
        } else if (insideComment === multiComment && currentChar + nextChar === "*/") {
          i++;
          insideComment = false;
          ret += strip(str, offset, i + 1);
          offset = i + 1;
          continue;
        }
      }
      return ret + (insideComment ? strip(str.substr(offset)) : str.substr(offset));
    };
  }
});

// node_modules/rc/lib/utils.js
var require_utils = __commonJS({
  "node_modules/rc/lib/utils.js"(exports) {
    "use strict";
    var fs8 = __require("fs");
    var ini2 = require_ini();
    var path16 = __require("path");
    var stripJsonComments = require_strip_json_comments();
    var parse = exports.parse = function(content) {
      if (/^\s*{/.test(content))
        return JSON.parse(stripJsonComments(content));
      return ini2.parse(content);
    };
    var file = exports.file = function() {
      var args = [].slice.call(arguments).filter(function(arg) {
        return arg != null;
      });
      for (var i in args)
        if ("string" !== typeof args[i])
          return;
      var file2 = path16.join.apply(null, args);
      var content;
      try {
        return fs8.readFileSync(file2, "utf-8");
      } catch (err) {
        return;
      }
    };
    var json2 = exports.json = function() {
      var content = file.apply(null, arguments);
      return content ? parse(content) : null;
    };
    var env = exports.env = function(prefix, env2) {
      env2 = env2 || process.env;
      var obj = {};
      var l = prefix.length;
      for (var k in env2) {
        if (k.toLowerCase().indexOf(prefix.toLowerCase()) === 0) {
          var keypath = k.substring(l).split("__");
          var _emptyStringIndex;
          while ((_emptyStringIndex = keypath.indexOf("")) > -1) {
            keypath.splice(_emptyStringIndex, 1);
          }
          var cursor = obj;
          keypath.forEach(function _buildSubObj(_subkey, i) {
            if (!_subkey || typeof cursor !== "object")
              return;
            if (i === keypath.length - 1)
              cursor[_subkey] = env2[k];
            if (cursor[_subkey] === void 0)
              cursor[_subkey] = {};
            cursor = cursor[_subkey];
          });
        }
      }
      return obj;
    };
    var find = exports.find = function() {
      var rel = path16.join.apply(null, [].slice.call(arguments));
      function find2(start, rel2) {
        var file2 = path16.join(start, rel2);
        try {
          fs8.statSync(file2);
          return file2;
        } catch (err) {
          if (path16.dirname(start) !== start)
            return find2(path16.dirname(start), rel2);
        }
      }
      return find2(process.cwd(), rel);
    };
  }
});

// node_modules/deep-extend/lib/deep-extend.js
var require_deep_extend = __commonJS({
  "node_modules/deep-extend/lib/deep-extend.js"(exports, module) {
    "use strict";
    function isSpecificValue(val) {
      return val instanceof Buffer || val instanceof Date || val instanceof RegExp ? true : false;
    }
    function cloneSpecificValue(val) {
      if (val instanceof Buffer) {
        var x = Buffer.alloc ? Buffer.alloc(val.length) : new Buffer(val.length);
        val.copy(x);
        return x;
      } else if (val instanceof Date) {
        return new Date(val.getTime());
      } else if (val instanceof RegExp) {
        return new RegExp(val);
      } else {
        throw new Error("Unexpected situation");
      }
    }
    function deepCloneArray(arr) {
      var clone = [];
      arr.forEach(function(item, index) {
        if (typeof item === "object" && item !== null) {
          if (Array.isArray(item)) {
            clone[index] = deepCloneArray(item);
          } else if (isSpecificValue(item)) {
            clone[index] = cloneSpecificValue(item);
          } else {
            clone[index] = deepExtend({}, item);
          }
        } else {
          clone[index] = item;
        }
      });
      return clone;
    }
    function safeGetProperty(object, property) {
      return property === "__proto__" ? void 0 : object[property];
    }
    var deepExtend = module.exports = function() {
      if (arguments.length < 1 || typeof arguments[0] !== "object") {
        return false;
      }
      if (arguments.length < 2) {
        return arguments[0];
      }
      var target = arguments[0];
      var args = Array.prototype.slice.call(arguments, 1);
      var val, src, clone;
      args.forEach(function(obj) {
        if (typeof obj !== "object" || obj === null || Array.isArray(obj)) {
          return;
        }
        Object.keys(obj).forEach(function(key) {
          src = safeGetProperty(target, key);
          val = safeGetProperty(obj, key);
          if (val === target) {
            return;
          } else if (typeof val !== "object" || val === null) {
            target[key] = val;
            return;
          } else if (Array.isArray(val)) {
            target[key] = deepCloneArray(val);
            return;
          } else if (isSpecificValue(val)) {
            target[key] = cloneSpecificValue(val);
            return;
          } else if (typeof src !== "object" || src === null || Array.isArray(src)) {
            target[key] = deepExtend({}, val);
            return;
          } else {
            target[key] = deepExtend(src, val);
            return;
          }
        });
      });
      return target;
    };
  }
});

// node_modules/minimist/index.js
var require_minimist = __commonJS({
  "node_modules/minimist/index.js"(exports, module) {
    "use strict";
    function hasKey(obj, keys) {
      var o = obj;
      keys.slice(0, -1).forEach(function(key2) {
        o = o[key2] || {};
      });
      var key = keys[keys.length - 1];
      return key in o;
    }
    function isNumber(x) {
      if (typeof x === "number") {
        return true;
      }
      if (/^0x[0-9a-f]+$/i.test(x)) {
        return true;
      }
      return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x);
    }
    function isConstructorOrProto(obj, key) {
      return key === "constructor" && typeof obj[key] === "function" || key === "__proto__";
    }
    module.exports = function(args, opts) {
      if (!opts) {
        opts = {};
      }
      var flags = {
        bools: {},
        strings: {},
        unknownFn: null
      };
      if (typeof opts.unknown === "function") {
        flags.unknownFn = opts.unknown;
      }
      if (typeof opts.boolean === "boolean" && opts.boolean) {
        flags.allBools = true;
      } else {
        [].concat(opts.boolean).filter(Boolean).forEach(function(key2) {
          flags.bools[key2] = true;
        });
      }
      var aliases = {};
      function aliasIsBoolean(key2) {
        return aliases[key2].some(function(x) {
          return flags.bools[x];
        });
      }
      Object.keys(opts.alias || {}).forEach(function(key2) {
        aliases[key2] = [].concat(opts.alias[key2]);
        aliases[key2].forEach(function(x) {
          aliases[x] = [key2].concat(aliases[key2].filter(function(y) {
            return x !== y;
          }));
        });
      });
      [].concat(opts.string).filter(Boolean).forEach(function(key2) {
        flags.strings[key2] = true;
        if (aliases[key2]) {
          [].concat(aliases[key2]).forEach(function(k) {
            flags.strings[k] = true;
          });
        }
      });
      var defaults = opts.default || {};
      var argv = { _: [] };
      function argDefined(key2, arg2) {
        return flags.allBools && /^--[^=]+$/.test(arg2) || flags.strings[key2] || flags.bools[key2] || aliases[key2];
      }
      function setKey(obj, keys, value2) {
        var o = obj;
        for (var i2 = 0; i2 < keys.length - 1; i2++) {
          var key2 = keys[i2];
          if (isConstructorOrProto(o, key2)) {
            return;
          }
          if (o[key2] === void 0) {
            o[key2] = {};
          }
          if (o[key2] === Object.prototype || o[key2] === Number.prototype || o[key2] === String.prototype) {
            o[key2] = {};
          }
          if (o[key2] === Array.prototype) {
            o[key2] = [];
          }
          o = o[key2];
        }
        var lastKey = keys[keys.length - 1];
        if (isConstructorOrProto(o, lastKey)) {
          return;
        }
        if (o === Object.prototype || o === Number.prototype || o === String.prototype) {
          o = {};
        }
        if (o === Array.prototype) {
          o = [];
        }
        if (o[lastKey] === void 0 || flags.bools[lastKey] || typeof o[lastKey] === "boolean") {
          o[lastKey] = value2;
        } else if (Array.isArray(o[lastKey])) {
          o[lastKey].push(value2);
        } else {
          o[lastKey] = [o[lastKey], value2];
        }
      }
      function setArg(key2, val, arg2) {
        if (arg2 && flags.unknownFn && !argDefined(key2, arg2)) {
          if (flags.unknownFn(arg2) === false) {
            return;
          }
        }
        var value2 = !flags.strings[key2] && isNumber(val) ? Number(val) : val;
        setKey(argv, key2.split("."), value2);
        (aliases[key2] || []).forEach(function(x) {
          setKey(argv, x.split("."), value2);
        });
      }
      Object.keys(flags.bools).forEach(function(key2) {
        setArg(key2, defaults[key2] === void 0 ? false : defaults[key2]);
      });
      var notFlags = [];
      if (args.indexOf("--") !== -1) {
        notFlags = args.slice(args.indexOf("--") + 1);
        args = args.slice(0, args.indexOf("--"));
      }
      for (var i = 0; i < args.length; i++) {
        var arg = args[i];
        var key;
        var next;
        if (/^--.+=/.test(arg)) {
          var m = arg.match(/^--([^=]+)=([\s\S]*)$/);
          key = m[1];
          var value = m[2];
          if (flags.bools[key]) {
            value = value !== "false";
          }
          setArg(key, value, arg);
        } else if (/^--no-.+/.test(arg)) {
          key = arg.match(/^--no-(.+)/)[1];
          setArg(key, false, arg);
        } else if (/^--.+/.test(arg)) {
          key = arg.match(/^--(.+)/)[1];
          next = args[i + 1];
          if (next !== void 0 && !/^(-|--)[^-]/.test(next) && !flags.bools[key] && !flags.allBools && (aliases[key] ? !aliasIsBoolean(key) : true)) {
            setArg(key, next, arg);
            i += 1;
          } else if (/^(true|false)$/.test(next)) {
            setArg(key, next === "true", arg);
            i += 1;
          } else {
            setArg(key, flags.strings[key] ? "" : true, arg);
          }
        } else if (/^-[^-]+/.test(arg)) {
          var letters = arg.slice(1, -1).split("");
          var broken = false;
          for (var j = 0; j < letters.length; j++) {
            next = arg.slice(j + 2);
            if (next === "-") {
              setArg(letters[j], next, arg);
              continue;
            }
            if (/[A-Za-z]/.test(letters[j]) && next[0] === "=") {
              setArg(letters[j], next.slice(1), arg);
              broken = true;
              break;
            }
            if (/[A-Za-z]/.test(letters[j]) && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) {
              setArg(letters[j], next, arg);
              broken = true;
              break;
            }
            if (letters[j + 1] && letters[j + 1].match(/\W/)) {
              setArg(letters[j], arg.slice(j + 2), arg);
              broken = true;
              break;
            } else {
              setArg(letters[j], flags.strings[letters[j]] ? "" : true, arg);
            }
          }
          key = arg.slice(-1)[0];
          if (!broken && key !== "-") {
            if (args[i + 1] && !/^(-|--)[^-]/.test(args[i + 1]) && !flags.bools[key] && (aliases[key] ? !aliasIsBoolean(key) : true)) {
              setArg(key, args[i + 1], arg);
              i += 1;
            } else if (args[i + 1] && /^(true|false)$/.test(args[i + 1])) {
              setArg(key, args[i + 1] === "true", arg);
              i += 1;
            } else {
              setArg(key, flags.strings[key] ? "" : true, arg);
            }
          }
        } else {
          if (!flags.unknownFn || flags.unknownFn(arg) !== false) {
            argv._.push(flags.strings._ || !isNumber(arg) ? arg : Number(arg));
          }
          if (opts.stopEarly) {
            argv._.push.apply(argv._, args.slice(i + 1));
            break;
          }
        }
      }
      Object.keys(defaults).forEach(function(k) {
        if (!hasKey(argv, k.split("."))) {
          setKey(argv, k.split("."), defaults[k]);
          (aliases[k] || []).forEach(function(x) {
            setKey(argv, x.split("."), defaults[k]);
          });
        }
      });
      if (opts["--"]) {
        argv["--"] = notFlags.slice();
      } else {
        notFlags.forEach(function(k) {
          argv._.push(k);
        });
      }
      return argv;
    };
  }
});

// node_modules/rc/index.js
var require_rc = __commonJS({
  "node_modules/rc/index.js"(exports, module) {
    var cc = require_utils();
    var join4 = __require("path").join;
    var deepExtend = require_deep_extend();
    var etc = "/etc";
    var win = process.platform === "win32";
    var home = win ? process.env.USERPROFILE : process.env.HOME;
    module.exports = function(name, defaults, argv, parse) {
      if ("string" !== typeof name)
        throw new Error("rc(name): name *must* be string");
      if (!argv)
        argv = require_minimist()(process.argv.slice(2));
      defaults = ("string" === typeof defaults ? cc.json(defaults) : defaults) || {};
      parse = parse || cc.parse;
      var env = cc.env(name + "_");
      var configs = [defaults];
      var configFiles = [];
      function addConfigFile(file) {
        if (configFiles.indexOf(file) >= 0) return;
        var fileConfig = cc.file(file);
        if (fileConfig) {
          configs.push(parse(fileConfig));
          configFiles.push(file);
        }
      }
      if (!win)
        [
          join4(etc, name, "config"),
          join4(etc, name + "rc")
        ].forEach(addConfigFile);
      if (home)
        [
          join4(home, ".config", name, "config"),
          join4(home, ".config", name),
          join4(home, "." + name, "config"),
          join4(home, "." + name + "rc")
        ].forEach(addConfigFile);
      addConfigFile(cc.find("." + name + "rc"));
      if (env.config) addConfigFile(env.config);
      if (argv.config) addConfigFile(argv.config);
      return deepExtend.apply(null, configs.concat([
        env,
        argv,
        configFiles.length ? { configs: configFiles, config: configFiles[configFiles.length - 1] } : void 0
      ]));
    };
  }
});

// node_modules/@pnpm/network.ca-file/node_modules/graceful-fs/polyfills.js
var require_polyfills = __commonJS({
  "node_modules/@pnpm/network.ca-file/node_modules/graceful-fs/polyfills.js"(exports, module) {
    var constants2 = __require("constants");
    var origCwd = process.cwd;
    var cwd5 = null;
    var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform;
    process.cwd = function() {
      if (!cwd5)
        cwd5 = origCwd.call(process);
      return cwd5;
    };
    try {
      process.cwd();
    } catch (er) {
    }
    if (typeof process.chdir === "function") {
      chdir = process.chdir;
      process.chdir = function(d) {
        cwd5 = null;
        chdir.call(process, d);
      };
      if (Object.setPrototypeOf) Object.setPrototypeOf(process.chdir, chdir);
    }
    var chdir;
    module.exports = patch;
    function patch(fs8) {
      if (constants2.hasOwnProperty("O_SYMLINK") && process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) {
        patchLchmod(fs8);
      }
      if (!fs8.lutimes) {
        patchLutimes(fs8);
      }
      fs8.chown = chownFix(fs8.chown);
      fs8.fchown = chownFix(fs8.fchown);
      fs8.lchown = chownFix(fs8.lchown);
      fs8.chmod = chmodFix(fs8.chmod);
      fs8.fchmod = chmodFix(fs8.fchmod);
      fs8.lchmod = chmodFix(fs8.lchmod);
      fs8.chownSync = chownFixSync(fs8.chownSync);
      fs8.fchownSync = chownFixSync(fs8.fchownSync);
      fs8.lchownSync = chownFixSync(fs8.lchownSync);
      fs8.chmodSync = chmodFixSync(fs8.chmodSync);
      fs8.fchmodSync = chmodFixSync(fs8.fchmodSync);
      fs8.lchmodSync = chmodFixSync(fs8.lchmodSync);
      fs8.stat = statFix(fs8.stat);
      fs8.fstat = statFix(fs8.fstat);
      fs8.lstat = statFix(fs8.lstat);
      fs8.statSync = statFixSync(fs8.statSync);
      fs8.fstatSync = statFixSync(fs8.fstatSync);
      fs8.lstatSync = statFixSync(fs8.lstatSync);
      if (fs8.chmod && !fs8.lchmod) {
        fs8.lchmod = function(path16, mode, cb) {
          if (cb) process.nextTick(cb);
        };
        fs8.lchmodSync = function() {
        };
      }
      if (fs8.chown && !fs8.lchown) {
        fs8.lchown = function(path16, uid, gid, cb) {
          if (cb) process.nextTick(cb);
        };
        fs8.lchownSync = function() {
        };
      }
      if (platform === "win32") {
        fs8.rename = typeof fs8.rename !== "function" ? fs8.rename : function(fs$rename) {
          function rename(from, to, cb) {
            var start = Date.now();
            var backoff = 0;
            fs$rename(from, to, function CB(er) {
              if (er && (er.code === "EACCES" || er.code === "EPERM") && Date.now() - start < 6e4) {
                setTimeout(function() {
                  fs8.stat(to, function(stater, st) {
                    if (stater && stater.code === "ENOENT")
                      fs$rename(from, to, CB);
                    else
                      cb(er);
                  });
                }, backoff);
                if (backoff < 100)
                  backoff += 10;
                return;
              }
              if (cb) cb(er);
            });
          }
          if (Object.setPrototypeOf) Object.setPrototypeOf(rename, fs$rename);
          return rename;
        }(fs8.rename);
      }
      fs8.read = typeof fs8.read !== "function" ? fs8.read : function(fs$read) {
        function read(fd, buffer, offset, length, position, callback_) {
          var callback;
          if (callback_ && typeof callback_ === "function") {
            var eagCounter = 0;
            callback = function(er, _, __) {
              if (er && er.code === "EAGAIN" && eagCounter < 10) {
                eagCounter++;
                return fs$read.call(fs8, fd, buffer, offset, length, position, callback);
              }
              callback_.apply(this, arguments);
            };
          }
          return fs$read.call(fs8, fd, buffer, offset, length, position, callback);
        }
        if (Object.setPrototypeOf) Object.setPrototypeOf(read, fs$read);
        return read;
      }(fs8.read);
      fs8.readSync = typeof fs8.readSync !== "function" ? fs8.readSync : /* @__PURE__ */ function(fs$readSync) {
        return function(fd, buffer, offset, length, position) {
          var eagCounter = 0;
          while (true) {
            try {
              return fs$readSync.call(fs8, fd, buffer, offset, length, position);
            } catch (er) {
              if (er.code === "EAGAIN" && eagCounter < 10) {
                eagCounter++;
                continue;
              }
              throw er;
            }
          }
        };
      }(fs8.readSync);
      function patchLchmod(fs9) {
        fs9.lchmod = function(path16, mode, callback) {
          fs9.open(
            path16,
            constants2.O_WRONLY | constants2.O_SYMLINK,
            mode,
            function(err, fd) {
              if (err) {
                if (callback) callback(err);
                return;
              }
              fs9.fchmod(fd, mode, function(err2) {
                fs9.close(fd, function(err22) {
                  if (callback) callback(err2 || err22);
                });
              });
            }
          );
        };
        fs9.lchmodSync = function(path16, mode) {
          var fd = fs9.openSync(path16, constants2.O_WRONLY | constants2.O_SYMLINK, mode);
          var threw = true;
          var ret;
          try {
            ret = fs9.fchmodSync(fd, mode);
            threw = false;
          } finally {
            if (threw) {
              try {
                fs9.closeSync(fd);
              } catch (er) {
              }
            } else {
              fs9.closeSync(fd);
            }
          }
          return ret;
        };
      }
      function patchLutimes(fs9) {
        if (constants2.hasOwnProperty("O_SYMLINK") && fs9.futimes) {
          fs9.lutimes = function(path16, at, mt, cb) {
            fs9.open(path16, constants2.O_SYMLINK, function(er, fd) {
              if (er) {
                if (cb) cb(er);
                return;
              }
              fs9.futimes(fd, at, mt, function(er2) {
                fs9.close(fd, function(er22) {
                  if (cb) cb(er2 || er22);
                });
              });
            });
          };
          fs9.lutimesSync = function(path16, at, mt) {
            var fd = fs9.openSync(path16, constants2.O_SYMLINK);
            var ret;
            var threw = true;
            try {
              ret = fs9.futimesSync(fd, at, mt);
              threw = false;
            } finally {
              if (threw) {
                try {
                  fs9.closeSync(fd);
                } catch (er) {
                }
              } else {
                fs9.closeSync(fd);
              }
            }
            return ret;
          };
        } else if (fs9.futimes) {
          fs9.lutimes = function(_a, _b, _c, cb) {
            if (cb) process.nextTick(cb);
          };
          fs9.lutimesSync = function() {
          };
        }
      }
      function chmodFix(orig) {
        if (!orig) return orig;
        return function(target, mode, cb) {
          return orig.call(fs8, target, mode, function(er) {
            if (chownErOk(er)) er = null;
            if (cb) cb.apply(this, arguments);
          });
        };
      }
      function chmodFixSync(orig) {
        if (!orig) return orig;
        return function(target, mode) {
          try {
            return orig.call(fs8, target, mode);
          } catch (er) {
            if (!chownErOk(er)) throw er;
          }
        };
      }
      function chownFix(orig) {
        if (!orig) return orig;
        return function(target, uid, gid, cb) {
          return orig.call(fs8, target, uid, gid, function(er) {
            if (chownErOk(er)) er = null;
            if (cb) cb.apply(this, arguments);
          });
        };
      }
      function chownFixSync(orig) {
        if (!orig) return orig;
        return function(target, uid, gid) {
          try {
            return orig.call(fs8, target, uid, gid);
          } catch (er) {
            if (!chownErOk(er)) throw er;
          }
        };
      }
      function statFix(orig) {
        if (!orig) return orig;
        return function(target, options, cb) {
          if (typeof options === "function") {
            cb = options;
            options = null;
          }
          function callback(er, stats) {
            if (stats) {
              if (stats.uid < 0) stats.uid += 4294967296;
              if (stats.gid < 0) stats.gid += 4294967296;
            }
            if (cb) cb.apply(this, arguments);
          }
          return options ? orig.call(fs8, target, options, callback) : orig.call(fs8, target, callback);
        };
      }
      function statFixSync(orig) {
        if (!orig) return orig;
        return function(target, options) {
          var stats = options ? orig.call(fs8, target, options) : orig.call(fs8, target);
          if (stats) {
            if (stats.uid < 0) stats.uid += 4294967296;
            if (stats.gid < 0) stats.gid += 4294967296;
          }
          return stats;
        };
      }
      function chownErOk(er) {
        if (!er)
          return true;
        if (er.code === "ENOSYS")
          return true;
        var nonroot = !process.getuid || process.getuid() !== 0;
        if (nonroot) {
          if (er.code === "EINVAL" || er.code === "EPERM")
            return true;
        }
        return false;
      }
    }
  }
});

// node_modules/@pnpm/network.ca-file/node_modules/graceful-fs/legacy-streams.js
var require_legacy_streams = __commonJS({
  "node_modules/@pnpm/network.ca-file/node_modules/graceful-fs/legacy-streams.js"(exports, module) {
    var Stream = __require("stream").Stream;
    module.exports = legacy;
    function legacy(fs8) {
      return {
        ReadStream,
        WriteStream
      };
      function ReadStream(path16, options) {
        if (!(this instanceof ReadStream)) return new ReadStream(path16, options);
        Stream.call(this);
        var self = this;
        this.path = path16;
        this.fd = null;
        this.readable = true;
        this.paused = false;
        this.flags = "r";
        this.mode = 438;
        this.bufferSize = 64 * 1024;
        options = options || {};
        var keys = Object.keys(options);
        for (var index = 0, length = keys.length; index < length; index++) {
          var key = keys[index];
          this[key] = options[key];
        }
        if (this.encoding) this.setEncoding(this.encoding);
        if (this.start !== void 0) {
          if ("number" !== typeof this.start) {
            throw TypeError("start must be a Number");
          }
          if (this.end === void 0) {
            this.end = Infinity;
          } else if ("number" !== typeof this.end) {
            throw TypeError("end must be a Number");
          }
          if (this.start > this.end) {
            throw new Error("start must be <= end");
          }
          this.pos = this.start;
        }
        if (this.fd !== null) {
          process.nextTick(function() {
            self._read();
          });
          return;
        }
        fs8.open(this.path, this.flags, this.mode, function(err, fd) {
          if (err) {
            self.emit("error", err);
            self.readable = false;
            return;
          }
          self.fd = fd;
          self.emit("open", fd);
          self._read();
        });
      }
      function WriteStream(path16, options) {
        if (!(this instanceof WriteStream)) return new WriteStream(path16, options);
        Stream.call(this);
        this.path = path16;
        this.fd = null;
        this.writable = true;
        this.flags = "w";
        this.encoding = "binary";
        this.mode = 438;
        this.bytesWritten = 0;
        options = options || {};
        var keys = Object.keys(options);
        for (var index = 0, length = keys.length; index < length; index++) {
          var key = keys[index];
          this[key] = options[key];
        }
        if (this.start !== void 0) {
          if ("number" !== typeof this.start) {
            throw TypeError("start must be a Number");
          }
          if (this.start < 0) {
            throw new Error("start must be >= zero");
          }
          this.pos = this.start;
        }
        this.busy = false;
        this._queue = [];
        if (this.fd === null) {
          this._open = fs8.open;
          this._queue.push([this._open, this.path, this.flags, this.mode, void 0]);
          this.flush();
        }
      }
    }
  }
});

// node_modules/@pnpm/network.ca-file/node_modules/graceful-fs/clone.js
var require_clone = __commonJS({
  "node_modules/@pnpm/network.ca-file/node_modules/graceful-fs/clone.js"(exports, module) {
    "use strict";
    module.exports = clone;
    var getPrototypeOf = Object.getPrototypeOf || function(obj) {
      return obj.__proto__;
    };
    function clone(obj) {
      if (obj === null || typeof obj !== "object")
        return obj;
      if (obj instanceof Object)
        var copy = { __proto__: getPrototypeOf(obj) };
      else
        var copy = /* @__PURE__ */ Object.create(null);
      Object.getOwnPropertyNames(obj).forEach(function(key) {
        Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key));
      });
      return copy;
    }
  }
});

// node_modules/@pnpm/network.ca-file/node_modules/graceful-fs/graceful-fs.js
var require_graceful_fs = __commonJS({
  "node_modules/@pnpm/network.ca-file/node_modules/graceful-fs/graceful-fs.js"(exports, module) {
    var fs8 = __require("fs");
    var polyfills = require_polyfills();
    var legacy = require_legacy_streams();
    var clone = require_clone();
    var util = __require("util");
    var gracefulQueue;
    var previousSymbol;
    if (typeof Symbol === "function" && typeof Symbol.for === "function") {
      gracefulQueue = Symbol.for("graceful-fs.queue");
      previousSymbol = Symbol.for("graceful-fs.previous");
    } else {
      gracefulQueue = "___graceful-fs.queue";
      previousSymbol = "___graceful-fs.previous";
    }
    function noop() {
    }
    function publishQueue(context, queue2) {
      Object.defineProperty(context, gracefulQueue, {
        get: function() {
          return queue2;
        }
      });
    }
    var debug = noop;
    if (util.debuglog)
      debug = util.debuglog("gfs4");
    else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || ""))
      debug = function() {
        var m = util.format.apply(util, arguments);
        m = "GFS4: " + m.split(/\n/).join("\nGFS4: ");
        console.error(m);
      };
    if (!fs8[gracefulQueue]) {
      queue = global[gracefulQueue] || [];
      publishQueue(fs8, queue);
      fs8.close = function(fs$close) {
        function close(fd, cb) {
          return fs$close.call(fs8, fd, function(err) {
            if (!err) {
              resetQueue();
            }
            if (typeof cb === "function")
              cb.apply(this, arguments);
          });
        }
        Object.defineProperty(close, previousSymbol, {
          value: fs$close
        });
        return close;
      }(fs8.close);
      fs8.closeSync = function(fs$closeSync) {
        function closeSync(fd) {
          fs$closeSync.apply(fs8, arguments);
          resetQueue();
        }
        Object.defineProperty(closeSync, previousSymbol, {
          value: fs$closeSync
        });
        return closeSync;
      }(fs8.closeSync);
      if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || "")) {
        process.on("exit", function() {
          debug(fs8[gracefulQueue]);
          __require("assert").equal(fs8[gracefulQueue].length, 0);
        });
      }
    }
    var queue;
    if (!global[gracefulQueue]) {
      publishQueue(global, fs8[gracefulQueue]);
    }
    module.exports = patch(clone(fs8));
    if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs8.__patched) {
      module.exports = patch(fs8);
      fs8.__patched = true;
    }
    function patch(fs9) {
      polyfills(fs9);
      fs9.gracefulify = patch;
      fs9.createReadStream = createReadStream;
      fs9.createWriteStream = createWriteStream;
      var fs$readFile = fs9.readFile;
      fs9.readFile = readFile3;
      function readFile3(path16, options, cb) {
        if (typeof options === "function")
          cb = options, options = null;
        return go$readFile(path16, options, cb);
        function go$readFile(path17, options2, cb2, startTime) {
          return fs$readFile(path17, options2, function(err) {
            if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
              enqueue([go$readFile, [path17, options2, cb2], err, startTime || Date.now(), Date.now()]);
            else {
              if (typeof cb2 === "function")
                cb2.apply(this, arguments);
            }
          });
        }
      }
      var fs$writeFile = fs9.writeFile;
      fs9.writeFile = writeFile2;
      function writeFile2(path16, data, options, cb) {
        if (typeof options === "function")
          cb = options, options = null;
        return go$writeFile(path16, data, options, cb);
        function go$writeFile(path17, data2, options2, cb2, startTime) {
          return fs$writeFile(path17, data2, options2, function(err) {
            if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
              enqueue([go$writeFile, [path17, data2, options2, cb2], err, startTime || Date.now(), Date.now()]);
            else {
              if (typeof cb2 === "function")
                cb2.apply(this, arguments);
            }
          });
        }
      }
      var fs$appendFile = fs9.appendFile;
      if (fs$appendFile)
        fs9.appendFile = appendFile;
      function appendFile(path16, data, options, cb) {
        if (typeof options === "function")
          cb = options, options = null;
        return go$appendFile(path16, data, options, cb);
        function go$appendFile(path17, data2, options2, cb2, startTime) {
          return fs$appendFile(path17, data2, options2, function(err) {
            if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
              enqueue([go$appendFile, [path17, data2, options2, cb2], err, startTime || Date.now(), Date.now()]);
            else {
              if (typeof cb2 === "function")
                cb2.apply(this, arguments);
            }
          });
        }
      }
      var fs$copyFile = fs9.copyFile;
      if (fs$copyFile)
        fs9.copyFile = copyFile;
      function copyFile(src, dest, flags, cb) {
        if (typeof flags === "function") {
          cb = flags;
          flags = 0;
        }
        return go$copyFile(src, dest, flags, cb);
        function go$copyFile(src2, dest2, flags2, cb2, startTime) {
          return fs$copyFile(src2, dest2, flags2, function(err) {
            if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
              enqueue([go$copyFile, [src2, dest2, flags2, cb2], err, startTime || Date.now(), Date.now()]);
            else {
              if (typeof cb2 === "function")
                cb2.apply(this, arguments);
            }
          });
        }
      }
      var fs$readdir = fs9.readdir;
      fs9.readdir = readdir2;
      var noReaddirOptionVersions = /^v[0-5]\./;
      function readdir2(path16, options, cb) {
        if (typeof options === "function")
          cb = options, options = null;
        var go$readdir = noReaddirOptionVersions.test(process.version) ? function go$readdir2(path17, options2, cb2, startTime) {
          return fs$readdir(path17, fs$readdirCallback(
            path17,
            options2,
            cb2,
            startTime
          ));
        } : function go$readdir2(path17, options2, cb2, startTime) {
          return fs$readdir(path17, options2, fs$readdirCallback(
            path17,
            options2,
            cb2,
            startTime
          ));
        };
        return go$readdir(path16, options, cb);
        function fs$readdirCallback(path17, options2, cb2, startTime) {
          return function(err, files) {
            if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
              enqueue([
                go$readdir,
                [path17, options2, cb2],
                err,
                startTime || Date.now(),
                Date.now()
              ]);
            else {
              if (files && files.sort)
                files.sort();
              if (typeof cb2 === "function")
                cb2.call(this, err, files);
            }
          };
        }
      }
      if (process.version.substr(0, 4) === "v0.8") {
        var legStreams = legacy(fs9);
        ReadStream = legStreams.ReadStream;
        WriteStream = legStreams.WriteStream;
      }
      var fs$ReadStream = fs9.ReadStream;
      if (fs$ReadStream) {
        ReadStream.prototype = Object.create(fs$ReadStream.prototype);
        ReadStream.prototype.open = ReadStream$open;
      }
      var fs$WriteStream = fs9.WriteStream;
      if (fs$WriteStream) {
        WriteStream.prototype = Object.create(fs$WriteStream.prototype);
        WriteStream.prototype.open = WriteStream$open;
      }
      Object.defineProperty(fs9, "ReadStream", {
        get: function() {
          return ReadStream;
        },
        set: function(val) {
          ReadStream = val;
        },
        enumerable: true,
        configurable: true
      });
      Object.defineProperty(fs9, "WriteStream", {
        get: function() {
          return WriteStream;
        },
        set: function(val) {
          WriteStream = val;
        },
        enumerable: true,
        configurable: true
      });
      var FileReadStream = ReadStream;
      Object.defineProperty(fs9, "FileReadStream", {
        get: function() {
          return FileReadStream;
        },
        set: function(val) {
          FileReadStream = val;
        },
        enumerable: true,
        configurable: true
      });
      var FileWriteStream = WriteStream;
      Object.defineProperty(fs9, "FileWriteStream", {
        get: function() {
          return FileWriteStream;
        },
        set: function(val) {
          FileWriteStream = val;
        },
        enumerable: true,
        configurable: true
      });
      function ReadStream(path16, options) {
        if (this instanceof ReadStream)
          return fs$ReadStream.apply(this, arguments), this;
        else
          return ReadStream.apply(Object.create(ReadStream.prototype), arguments);
      }
      function ReadStream$open() {
        var that = this;
        open(that.path, that.flags, that.mode, function(err, fd) {
          if (err) {
            if (that.autoClose)
              that.destroy();
            that.emit("error", err);
          } else {
            that.fd = fd;
            that.emit("open", fd);
            that.read();
          }
        });
      }
      function WriteStream(path16, options) {
        if (this instanceof WriteStream)
          return fs$WriteStream.apply(this, arguments), this;
        else
          return WriteStream.apply(Object.create(WriteStream.prototype), arguments);
      }
      function WriteStream$open() {
        var that = this;
        open(that.path, that.flags, that.mode, function(err, fd) {
          if (err) {
            that.destroy();
            that.emit("error", err);
          } else {
            that.fd = fd;
            that.emit("open", fd);
          }
        });
      }
      function createReadStream(path16, options) {
        return new fs9.ReadStream(path16, options);
      }
      function createWriteStream(path16, options) {
        return new fs9.WriteStream(path16, options);
      }
      var fs$open = fs9.open;
      fs9.open = open;
      function open(path16, flags, mode, cb) {
        if (typeof mode === "function")
          cb = mode, mode = null;
        return go$open(path16, flags, mode, cb);
        function go$open(path17, flags2, mode2, cb2, startTime) {
          return fs$open(path17, flags2, mode2, function(err, fd) {
            if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
              enqueue([go$open, [path17, flags2, mode2, cb2], err, startTime || Date.now(), Date.now()]);
            else {
              if (typeof cb2 === "function")
                cb2.apply(this, arguments);
            }
          });
        }
      }
      return fs9;
    }
    function enqueue(elem) {
      debug("ENQUEUE", elem[0].name, elem[1]);
      fs8[gracefulQueue].push(elem);
      retry();
    }
    var retryTimer;
    function resetQueue() {
      var now = Date.now();
      for (var i = 0; i < fs8[gracefulQueue].length; ++i) {
        if (fs8[gracefulQueue][i].length > 2) {
          fs8[gracefulQueue][i][3] = now;
          fs8[gracefulQueue][i][4] = now;
        }
      }
      retry();
    }
    function retry() {
      clearTimeout(retryTimer);
      retryTimer = void 0;
      if (fs8[gracefulQueue].length === 0)
        return;
      var elem = fs8[gracefulQueue].shift();
      var fn = elem[0];
      var args = elem[1];
      var err = elem[2];
      var startTime = elem[3];
      var lastTime = elem[4];
      if (startTime === void 0) {
        debug("RETRY", fn.name, args);
        fn.apply(null, args);
      } else if (Date.now() - startTime >= 6e4) {
        debug("TIMEOUT", fn.name, args);
        var cb = args.pop();
        if (typeof cb === "function")
          cb.call(null, err);
      } else {
        var sinceAttempt = Date.now() - lastTime;
        var sinceStart = Math.max(lastTime - startTime, 1);
        var desiredDelay = Math.min(sinceStart * 1.2, 100);
        if (sinceAttempt >= desiredDelay) {
          debug("RETRY", fn.name, args);
          fn.apply(null, args.concat([startTime]));
        } else {
          fs8[gracefulQueue].push(elem);
        }
      }
      if (retryTimer === void 0) {
        retryTimer = setTimeout(retry, 0);
      }
    }
  }
});

// node_modules/@pnpm/network.ca-file/dist/ca-file.js
var require_ca_file = __commonJS({
  "node_modules/@pnpm/network.ca-file/dist/ca-file.js"(exports) {
    "use strict";
    var __importDefault = exports && exports.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.readCAFileSync = void 0;
    var graceful_fs_1 = __importDefault(require_graceful_fs());
    function readCAFileSync(filePath) {
      try {
        const contents = graceful_fs_1.default.readFileSync(filePath, "utf8");
        const delim = "-----END CERTIFICATE-----";
        const output = contents.split(delim).filter((ca) => Boolean(ca.trim())).map((ca) => `${ca.trimLeft()}${delim}`);
        return output;
      } catch (err) {
        if (err.code === "ENOENT")
          return void 0;
        throw err;
      }
    }
    exports.readCAFileSync = readCAFileSync;
  }
});

// node_modules/@pnpm/network.ca-file/dist/index.js
var require_dist = __commonJS({
  "node_modules/@pnpm/network.ca-file/dist/index.js"(exports) {
    "use strict";
    var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    } : function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    });
    var __exportStar = exports && exports.__exportStar || function(m, exports2) {
      for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p)) __createBinding(exports2, m, p);
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    __exportStar(require_ca_file(), exports);
  }
});

// node_modules/proto-list/proto-list.js
var require_proto_list = __commonJS({
  "node_modules/proto-list/proto-list.js"(exports, module) {
    module.exports = ProtoList;
    function setProto(obj, proto) {
      if (typeof Object.setPrototypeOf === "function")
        return Object.setPrototypeOf(obj, proto);
      else
        obj.__proto__ = proto;
    }
    function ProtoList() {
      this.list = [];
      var root = null;
      Object.defineProperty(this, "root", {
        get: function() {
          return root;
        },
        set: function(r2) {
          root = r2;
          if (this.list.length) {
            setProto(this.list[this.list.length - 1], r2);
          }
        },
        enumerable: true,
        configurable: true
      });
    }
    ProtoList.prototype = {
      get length() {
        return this.list.length;
      },
      get keys() {
        var k = [];
        for (var i in this.list[0]) k.push(i);
        return k;
      },
      get snapshot() {
        var o = {};
        this.keys.forEach(function(k) {
          o[k] = this.get(k);
        }, this);
        return o;
      },
      get store() {
        return this.list[0];
      },
      push: function(obj) {
        if (typeof obj !== "object") obj = { valueOf: obj };
        if (this.list.length >= 1) {
          setProto(this.list[this.list.length - 1], obj);
        }
        setProto(obj, this.root);
        return this.list.push(obj);
      },
      pop: function() {
        if (this.list.length >= 2) {
          setProto(this.list[this.list.length - 2], this.root);
        }
        return this.list.pop();
      },
      unshift: function(obj) {
        setProto(obj, this.list[0] || this.root);
        return this.list.unshift(obj);
      },
      shift: function() {
        if (this.list.length === 1) {
          setProto(this.list[0], this.root);
        }
        return this.list.shift();
      },
      get: function(key) {
        return this.list[0][key];
      },
      set: function(key, val, save) {
        if (!this.length) this.push({});
        if (save && this.list[0].hasOwnProperty(key)) this.push({});
        return this.list[0][key] = val;
      },
      forEach: function(fn, thisp) {
        for (var key in this.list[0]) fn.call(thisp, key, this.list[0][key]);
      },
      slice: function() {
        return this.list.slice.apply(this.list, arguments);
      },
      splice: function() {
        var ret = this.list.splice.apply(this.list, arguments);
        for (var i = 0, l = this.list.length; i < l; i++) {
          setProto(this.list[i], this.list[i + 1] || this.root);
        }
        return ret;
      }
    };
  }
});

// node_modules/config-chain/index.js
var require_config_chain = __commonJS({
  "node_modules/config-chain/index.js"(exports, module) {
    var ProtoList = require_proto_list();
    var path16 = __require("path");
    var fs8 = __require("fs");
    var ini2 = require_ini();
    var EE = __require("events").EventEmitter;
    var url2 = __require("url");
    var http = __require("http");
    var exports = module.exports = function() {
      var args = [].slice.call(arguments), conf = new ConfigChain();
      while (args.length) {
        var a = args.shift();
        if (a) conf.push("string" === typeof a ? json2(a) : a);
      }
      return conf;
    };
    var find = exports.find = function() {
      var rel = path16.join.apply(null, [].slice.call(arguments));
      function find2(start, rel2) {
        var file = path16.join(start, rel2);
        try {
          fs8.statSync(file);
          return file;
        } catch (err) {
          if (path16.dirname(start) !== start)
            return find2(path16.dirname(start), rel2);
        }
      }
      return find2(__chunk_dirname, rel);
    };
    var parse = exports.parse = function(content, file, type) {
      content = "" + content;
      if (!type) {
        try {
          return JSON.parse(content);
        } catch (er) {
          return ini2.parse(content);
        }
      } else if (type === "json") {
        if (this.emit) {
          try {
            return JSON.parse(content);
          } catch (er) {
            this.emit("error", er);
          }
        } else {
          return JSON.parse(content);
        }
      } else {
        return ini2.parse(content);
      }
    };
    var json2 = exports.json = function() {
      var args = [].slice.call(arguments).filter(function(arg) {
        return arg != null;
      });
      var file = path16.join.apply(null, args);
      var content;
      try {
        content = fs8.readFileSync(file, "utf-8");
      } catch (err) {
        return;
      }
      return parse(content, file, "json");
    };
    var env = exports.env = function(prefix, env2) {
      env2 = env2 || process.env;
      var obj = {};
      var l = prefix.length;
      for (var k in env2) {
        if (k.indexOf(prefix) === 0)
          obj[k.substring(l)] = env2[k];
      }
      return obj;
    };
    exports.ConfigChain = ConfigChain;
    function ConfigChain() {
      EE.apply(this);
      ProtoList.apply(this, arguments);
      this._awaiting = 0;
      this._saving = 0;
      this.sources = {};
    }
    var extras = {
      constructor: { value: ConfigChain }
    };
    Object.keys(EE.prototype).forEach(function(k) {
      extras[k] = Object.getOwnPropertyDescriptor(EE.prototype, k);
    });
    ConfigChain.prototype = Object.create(ProtoList.prototype, extras);
    ConfigChain.prototype.del = function(key, where) {
      if (where) {
        var target = this.sources[where];
        target = target && target.data;
        if (!target) {
          return this.emit("error", new Error("not found " + where));
        }
        delete target[key];
      } else {
        for (var i = 0, l = this.list.length; i < l; i++) {
          delete this.list[i][key];
        }
      }
      return this;
    };
    ConfigChain.prototype.set = function(key, value, where) {
      var target;
      if (where) {
        target = this.sources[where];
        target = target && target.data;
        if (!target) {
          return this.emit("error", new Error("not found " + where));
        }
      } else {
        target = this.list[0];
        if (!target) {
          return this.emit("error", new Error("cannot set, no confs!"));
        }
      }
      target[key] = value;
      return this;
    };
    ConfigChain.prototype.get = function(key, where) {
      if (where) {
        where = this.sources[where];
        if (where) where = where.data;
        if (where && Object.hasOwnProperty.call(where, key)) return where[key];
        return void 0;
      }
      return this.list[0][key];
    };
    ConfigChain.prototype.save = function(where, type, cb) {
      if (typeof type === "function") cb = type, type = null;
      var target = this.sources[where];
      if (!target || !(target.path || target.source) || !target.data) {
        return this.emit("error", new Error("bad save target: " + where));
      }
      if (target.source) {
        var pref = target.prefix || "";
        Object.keys(target.data).forEach(function(k) {
          target.source[pref + k] = target.data[k];
        });
        return this;
      }
      var type = type || target.type;
      var data = target.data;
      if (target.type === "json") {
        data = JSON.stringify(data);
      } else {
        data = ini2.stringify(data);
      }
      this._saving++;
      fs8.writeFile(target.path, data, "utf8", function(er) {
        this._saving--;
        if (er) {
          if (cb) return cb(er);
          else return this.emit("error", er);
        }
        if (this._saving === 0) {
          if (cb) cb();
          this.emit("save");
        }
      }.bind(this));
      return this;
    };
    ConfigChain.prototype.addFile = function(file, type, name) {
      name = name || file;
      var marker = { __source__: name };
      this.sources[name] = { path: file, type };
      this.push(marker);
      this._await();
      fs8.readFile(file, "utf8", function(er, data) {
        if (er) this.emit("error", er);
        this.addString(data, file, type, marker);
      }.bind(this));
      return this;
    };
    ConfigChain.prototype.addEnv = function(prefix, env2, name) {
      name = name || "env";
      var data = exports.env(prefix, env2);
      this.sources[name] = { data, source: env2, prefix };
      return this.add(data, name);
    };
    ConfigChain.prototype.addUrl = function(req, type, name) {
      this._await();
      var href = url2.format(req);
      name = name || href;
      var marker = { __source__: name };
      this.sources[name] = { href, type };
      this.push(marker);
      http.request(req, function(res) {
        var c2 = [];
        var ct = res.headers["content-type"];
        if (!type) {
          type = ct.indexOf("json") !== -1 ? "json" : ct.indexOf("ini") !== -1 ? "ini" : href.match(/\.json$/) ? "json" : href.match(/\.ini$/) ? "ini" : null;
          marker.type = type;
        }
        res.on("data", c2.push.bind(c2)).on("end", function() {
          this.addString(Buffer.concat(c2), href, type, marker);
        }.bind(this)).on("error", this.emit.bind(this, "error"));
      }.bind(this)).on("error", this.emit.bind(this, "error")).end();
      return this;
    };
    ConfigChain.prototype.addString = function(data, file, type, marker) {
      data = this.parse(data, file, type);
      this.add(data, marker);
      return this;
    };
    ConfigChain.prototype.add = function(data, marker) {
      if (marker && typeof marker === "object") {
        var i = this.list.indexOf(marker);
        if (i === -1) {
          return this.emit("error", new Error("bad marker"));
        }
        this.splice(i, 1, data);
        marker = marker.__source__;
        this.sources[marker] = this.sources[marker] || {};
        this.sources[marker].data = data;
        this._resolve();
      } else {
        if (typeof marker === "string") {
          this.sources[marker] = this.sources[marker] || {};
          this.sources[marker].data = data;
        }
        this._await();
        this.push(data);
        process.nextTick(this._resolve.bind(this));
      }
      return this;
    };
    ConfigChain.prototype.parse = exports.parse;
    ConfigChain.prototype._await = function() {
      this._awaiting++;
    };
    ConfigChain.prototype._resolve = function() {
      this._awaiting--;
      if (this._awaiting === 0) this.emit("load", this);
    };
  }
});

// node_modules/@pnpm/npm-conf/lib/envKeyToSetting.js
var require_envKeyToSetting = __commonJS({
  "node_modules/@pnpm/npm-conf/lib/envKeyToSetting.js"(exports, module) {
    module.exports = function(x) {
      const colonIndex = x.indexOf(":");
      if (colonIndex === -1) {
        return normalize(x);
      }
      const firstPart = x.substr(0, colonIndex);
      const secondPart = x.substr(colonIndex + 1);
      return `${normalize(firstPart)}:${normalize(secondPart)}`;
    };
    function normalize(s) {
      s = s.toLowerCase();
      if (s === "_authtoken") return "_authToken";
      let r2 = s[0];
      for (let i = 1; i < s.length; i++) {
        r2 += s[i] === "_" ? "-" : s[i];
      }
      return r2;
    }
  }
});

// node_modules/@pnpm/config.env-replace/dist/env-replace.js
var require_env_replace = __commonJS({
  "node_modules/@pnpm/config.env-replace/dist/env-replace.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.envReplace = void 0;
    var ENV_EXPR = /(?<!\\)(\\*)\$\{([^${}]+)\}/g;
    function envReplace(settingValue, env) {
      return settingValue.replace(ENV_EXPR, replaceEnvMatch.bind(null, env));
    }
    exports.envReplace = envReplace;
    function replaceEnvMatch(env, orig, escape, name) {
      if (escape.length % 2) {
        return orig.slice((escape.length + 1) / 2);
      }
      const envValue = getEnvValue(env, name);
      if (envValue === void 0) {
        throw new Error(`Failed to replace env in config: ${orig}`);
      }
      return `${escape.slice(escape.length / 2)}${envValue}`;
    }
    var ENV_VALUE = /([^:-]+)(:?)-(.+)/;
    function getEnvValue(env, name) {
      const matched = name.match(ENV_VALUE);
      if (!matched)
        return env[name];
      const [, variableName, colon, fallback] = matched;
      if (Object.prototype.hasOwnProperty.call(env, variableName)) {
        return !env[variableName] && colon ? fallback : env[variableName];
      }
      return fallback;
    }
  }
});

// node_modules/@pnpm/config.env-replace/dist/index.js
var require_dist2 = __commonJS({
  "node_modules/@pnpm/config.env-replace/dist/index.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.envReplace = void 0;
    var env_replace_1 = require_env_replace();
    Object.defineProperty(exports, "envReplace", { enumerable: true, get: function() {
      return env_replace_1.envReplace;
    } });
  }
});

// node_modules/@pnpm/npm-conf/lib/util.js
var require_util = __commonJS({
  "node_modules/@pnpm/npm-conf/lib/util.js"(exports) {
    "use strict";
    var fs8 = __require("fs");
    var path16 = __require("path");
    var { envReplace } = require_dist2();
    var parseKey = (key) => {
      if (typeof key !== "string") {
        return key;
      }
      return envReplace(key, process.env);
    };
    var parseField = (types, field, key) => {
      if (typeof field !== "string") {
        return field;
      }
      const typeList = [].concat(types[key]);
      const isPath = typeList.indexOf(path16) !== -1;
      const isBool = typeList.indexOf(Boolean) !== -1;
      const isString = typeList.indexOf(String) !== -1;
      const isNumber = typeList.indexOf(Number) !== -1;
      field = `${field}`.trim();
      if (/^".*"$/.test(field)) {
        try {
          field = JSON.parse(field);
        } catch (error) {
          throw new Error(`Failed parsing JSON config key ${key}: ${field}`);
        }
      }
      if (isBool && !isString && field === "") {
        return true;
      }
      switch (field) {
        // eslint-disable-line default-case
        case "true": {
          return true;
        }
        case "false": {
          return false;
        }
        case "null": {
          return null;
        }
        case "undefined": {
          return void 0;
        }
      }
      field = envReplace(field, process.env);
      if (isPath) {
        const regex = process.platform === "win32" ? /^~(\/|\\)/ : /^~\//;
        if (regex.test(field) && process.env.HOME) {
          field = path16.resolve(process.env.HOME, field.substr(2));
        }
        field = path16.resolve(field);
      }
      if (isNumber && !isNaN(field)) {
        field = Number(field);
      }
      return field;
    };
    var findPrefix = (name) => {
      name = path16.resolve(name);
      let walkedUp = false;
      while (path16.basename(name) === "node_modules") {
        name = path16.dirname(name);
        walkedUp = true;
      }
      if (walkedUp) {
        return name;
      }
      const find = (name2, original) => {
        const regex = /^[a-zA-Z]:(\\|\/)?$/;
        if (name2 === "/" || process.platform === "win32" && regex.test(name2)) {
          return original;
        }
        try {
          const files = fs8.readdirSync(name2);
          if (files.includes("node_modules") || files.includes("package.json") || files.includes("package.json5") || files.includes("package.yaml") || files.includes("pnpm-workspace.yaml")) {
            return name2;
          }
          const dirname5 = path16.dirname(name2);
          if (dirname5 === name2) {
            return original;
          }
          return find(dirname5, original);
        } catch (error) {
          if (name2 === original) {
            if (error.code === "ENOENT") {
              return original;
            }
            throw error;
          }
          return original;
        }
      };
      return find(name, name);
    };
    exports.envReplace = envReplace;
    exports.findPrefix = findPrefix;
    exports.parseField = parseField;
    exports.parseKey = parseKey;
  }
});

// node_modules/@pnpm/npm-conf/lib/types.js
var require_types = __commonJS({
  "node_modules/@pnpm/npm-conf/lib/types.js"(exports) {
    "use strict";
    var path16 = __require("path");
    var Stream = __require("stream").Stream;
    var url2 = __require("url");
    var Umask = () => {
    };
    var getLocalAddresses = () => [];
    var semver3 = () => {
    };
    exports.types = {
      access: [null, "restricted", "public"],
      "allow-same-version": Boolean,
      "always-auth": Boolean,
      also: [null, "dev", "development"],
      audit: Boolean,
      "auth-type": ["legacy", "sso", "saml", "oauth"],
      "bin-links": Boolean,
      browser: [null, String],
      ca: [null, String, Array],
      cafile: path16,
      cache: path16,
      "cache-lock-stale": Number,
      "cache-lock-retries": Number,
      "cache-lock-wait": Number,
      "cache-max": Number,
      "cache-min": Number,
      cert: [null, String],
      cidr: [null, String, Array],
      color: ["always", Boolean],
      depth: Number,
      description: Boolean,
      dev: Boolean,
      "dry-run": Boolean,
      editor: String,
      "engine-strict": Boolean,
      force: Boolean,
      "fetch-retries": Number,
      "fetch-retry-factor": Number,
      "fetch-retry-mintimeout": Number,
      "fetch-retry-maxtimeout": Number,
      git: String,
      "git-tag-version": Boolean,
      "commit-hooks": Boolean,
      global: Boolean,
      globalconfig: path16,
      "global-style": Boolean,
      group: [Number, String],
      "https-proxy": [null, url2],
      "user-agent": String,
      "ham-it-up": Boolean,
      "heading": String,
      "if-present": Boolean,
      "ignore-prepublish": Boolean,
      "ignore-scripts": Boolean,
      "init-module": path16,
      "init-author-name": String,
      "init-author-email": String,
      "init-author-url": ["", url2],
      "init-license": String,
      "init-version": semver3,
      json: Boolean,
      key: [null, String],
      "legacy-bundling": Boolean,
      link: Boolean,
      // local-address must be listed as an IP for a local network interface
      // must be IPv4 due to node bug
      "local-address": getLocalAddresses(),
      loglevel: ["silent", "error", "warn", "notice", "http", "timing", "info", "verbose", "silly"],
      logstream: Stream,
      "logs-max": Number,
      long: Boolean,
      maxsockets: Number,
      message: String,
      "metrics-registry": [null, String],
      "node-options": [null, String],
      "node-version": [null, semver3],
      "no-proxy": [null, String, Array],
      offline: Boolean,
      "onload-script": [null, String],
      only: [null, "dev", "development", "prod", "production"],
      optional: Boolean,
      "package-lock": Boolean,
      otp: [null, String],
      "package-lock-only": Boolean,
      parseable: Boolean,
      "prefer-offline": Boolean,
      "prefer-online": Boolean,
      prefix: path16,
      production: Boolean,
      progress: Boolean,
      proxy: [null, false, url2],
      provenance: Boolean,
      // allow proxy to be disabled explicitly
      "read-only": Boolean,
      "rebuild-bundle": Boolean,
      registry: [null, url2],
      rollback: Boolean,
      save: Boolean,
      "save-bundle": Boolean,
      "save-dev": Boolean,
      "save-exact": Boolean,
      "save-optional": Boolean,
      "save-prefix": String,
      "save-prod": Boolean,
      scope: String,
      "script-shell": [null, String],
      "scripts-prepend-node-path": [false, true, "auto", "warn-only"],
      searchopts: String,
      searchexclude: [null, String],
      searchlimit: Number,
      searchstaleness: Number,
      "send-metrics": Boolean,
      shell: String,
      shrinkwrap: Boolean,
      "sign-git-tag": Boolean,
      "sso-poll-frequency": Number,
      "sso-type": [null, "oauth", "saml"],
      "strict-ssl": Boolean,
      tag: String,
      timing: Boolean,
      tmp: path16,
      unicode: Boolean,
      "unsafe-perm": Boolean,
      usage: Boolean,
      user: [Number, String],
      userconfig: path16,
      umask: Umask,
      version: Boolean,
      "tag-version-prefix": String,
      versions: Boolean,
      viewer: String,
      _exit: Boolean
    };
  }
});

// node_modules/@pnpm/npm-conf/lib/conf.js
var require_conf = __commonJS({
  "node_modules/@pnpm/npm-conf/lib/conf.js"(exports, module) {
    "use strict";
    var { readCAFileSync } = require_dist();
    var fs8 = __require("fs");
    var path16 = __require("path");
    var { ConfigChain } = require_config_chain();
    var envKeyToSetting = require_envKeyToSetting();
    var util = require_util();
    var Conf = class extends ConfigChain {
      // https://github.com/npm/cli/blob/latest/lib/config/core.js#L203-L217
      constructor(base, types) {
        super(base);
        this.root = base;
        this._parseField = util.parseField.bind(null, types || require_types());
      }
      // https://github.com/npm/cli/blob/latest/lib/config/core.js#L326-L338
      add(data, marker) {
        try {
          for (const [key, value] of Object.entries(data)) {
            const substKey = util.parseKey(key);
            if (substKey !== key) {
              delete data[key];
            }
            data[substKey] = this._parseField(value, substKey);
          }
        } catch (error) {
          throw error;
        }
        return super.add(data, marker);
      }
      // https://github.com/npm/cli/blob/latest/lib/config/core.js#L306-L319
      addFile(file, name) {
        name = name || file;
        const marker = { __source__: name };
        this.sources[name] = { path: file, type: "ini" };
        this.push(marker);
        this._await();
        try {
          const contents = fs8.readFileSync(file, "utf8");
          this.addString(contents, file, "ini", marker);
        } catch (error) {
          if (error.code === "ENOENT") {
            this.add({}, marker);
          } else if (error.code !== "EISDIR") {
            return `Issue while reading "${file}". ${error.message}`;
          }
        }
      }
      // https://github.com/npm/cli/blob/latest/lib/config/core.js#L341-L357
      addEnv(env) {
        env = env || process.env;
        const conf = {};
        Object.keys(env).filter((x) => /^npm_config_/i.test(x)).forEach((x) => {
          if (!env[x]) {
            return;
          }
          const key = envKeyToSetting(x.substr(11));
          const rawVal = env[x];
          conf[key] = deserializeEnvVal(key, rawVal);
        });
        return super.addEnv("", conf, "env");
      }
      // https://github.com/npm/cli/blob/latest/lib/config/load-prefix.js
      loadPrefix() {
        const cli = this.list[0];
        Object.defineProperty(this, "prefix", {
          enumerable: true,
          set: (prefix) => {
            const g = this.get("global");
            this[g ? "globalPrefix" : "localPrefix"] = prefix;
          },
          get: () => {
            const g = this.get("global");
            return g ? this.globalPrefix : this.localPrefix;
          }
        });
        Object.defineProperty(this, "globalPrefix", {
          enumerable: true,
          set: (prefix) => {
            this.set("prefix", prefix);
          },
          get: () => {
            return path16.resolve(this.get("prefix"));
          }
        });
        let p;
        Object.defineProperty(this, "localPrefix", {
          enumerable: true,
          set: (prefix) => {
            p = prefix;
          },
          get: () => {
            return p;
          }
        });
        if (Object.prototype.hasOwnProperty.call(cli, "prefix")) {
          p = path16.resolve(cli.prefix);
        } else {
          try {
            const prefix = util.findPrefix(process.cwd());
            p = prefix;
          } catch (error) {
            throw error;
          }
        }
        return p;
      }
      // https://github.com/npm/cli/blob/latest/lib/config/load-cafile.js
      loadCAFile(file) {
        if (!file) {
          return;
        }
        const ca = readCAFileSync(file);
        if (ca) {
          this.set("ca", ca);
        }
      }
      // https://github.com/npm/cli/blob/latest/lib/config/set-user.js
      loadUser() {
        const defConf = this.root;
        if (this.get("global")) {
          return;
        }
        if (process.env.SUDO_UID) {
          defConf.user = Number(process.env.SUDO_UID);
          return;
        }
        const prefix = path16.resolve(this.get("prefix"));
        try {
          const stats = fs8.statSync(prefix);
          defConf.user = stats.uid;
        } catch (error) {
          if (error.code === "ENOENT") {
            return;
          }
          throw error;
        }
      }
    };
    function deserializeEnvVal(envKey, envValue) {
      function deserializeList(envValue2) {
        const npmConfigSep = "\n\n";
        if (envValue2.indexOf(npmConfigSep)) {
          return envValue2.split(npmConfigSep);
        }
        return envValue2.split(",");
      }
      switch (envKey) {
        case "hoist-pattern":
        case "public-hoist-pattern":
          return deserializeList(envValue);
      }
      return envValue;
    }
    module.exports = Conf;
  }
});

// node_modules/@pnpm/npm-conf/lib/defaults.js
var require_defaults = __commonJS({
  "node_modules/@pnpm/npm-conf/lib/defaults.js"(exports) {
    "use strict";
    var os4 = __require("os");
    var path16 = __require("path");
    var temp = os4.tmpdir();
    var uidOrPid = process.getuid ? process.getuid() : process.pid;
    var hasUnicode = () => true;
    var isWindows2 = process.platform === "win32";
    var osenv = {
      editor: () => process.env.EDITOR || process.env.VISUAL || (isWindows2 ? "notepad.exe" : "vi"),
      shell: () => isWindows2 ? process.env.COMSPEC || "cmd.exe" : process.env.SHELL || "/bin/bash"
    };
    var umask = {
      fromString: () => process.umask()
    };
    var home = os4.homedir();
    if (home) {
      process.env.HOME = home;
    } else {
      home = path16.resolve(temp, "npm-" + uidOrPid);
    }
    var cacheExtra = process.platform === "win32" ? "npm-cache" : ".npm";
    var cacheRoot = process.platform === "win32" && process.env.APPDATA || home;
    var cache = path16.resolve(cacheRoot, cacheExtra);
    var defaults;
    var globalPrefix;
    Object.defineProperty(exports, "defaults", {
      get: function() {
        if (defaults) return defaults;
        if (process.env.PREFIX) {
          globalPrefix = process.env.PREFIX;
        } else if (process.platform === "win32") {
          globalPrefix = path16.dirname(process.execPath);
        } else {
          globalPrefix = path16.dirname(path16.dirname(process.execPath));
          if (process.env.DESTDIR) {
            globalPrefix = path16.join(process.env.DESTDIR, globalPrefix);
          }
        }
        defaults = {
          access: null,
          "allow-same-version": false,
          "always-auth": false,
          also: null,
          audit: true,
          "auth-type": "legacy",
          "bin-links": true,
          browser: null,
          ca: null,
          cafile: null,
          cache,
          "cache-lock-stale": 6e4,
          "cache-lock-retries": 10,
          "cache-lock-wait": 1e4,
          "cache-max": Infinity,
          "cache-min": 10,
          cert: null,
          cidr: null,
          color: process.env.NO_COLOR == null,
          depth: Infinity,
          description: true,
          dev: false,
          "dry-run": false,
          editor: osenv.editor(),
          "engine-strict": false,
          force: false,
          "fetch-retries": 2,
          "fetch-retry-factor": 10,
          "fetch-retry-mintimeout": 1e4,
          "fetch-retry-maxtimeout": 6e4,
          git: "git",
          "git-tag-version": true,
          "commit-hooks": true,
          global: false,
          globalconfig: path16.resolve(globalPrefix, "etc", "npmrc"),
          "global-style": false,
          group: process.platform === "win32" ? 0 : process.env.SUDO_GID || process.getgid && process.getgid(),
          "ham-it-up": false,
          heading: "npm",
          "if-present": false,
          "ignore-prepublish": false,
          "ignore-scripts": false,
          "init-module": path16.resolve(home, ".npm-init.js"),
          "init-author-name": "",
          "init-author-email": "",
          "init-author-url": "",
          "init-version": "1.0.0",
          "init-license": "ISC",
          json: false,
          key: null,
          "legacy-bundling": false,
          link: false,
          "local-address": void 0,
          loglevel: "notice",
          logstream: process.stderr,
          "logs-max": 10,
          long: false,
          maxsockets: 50,
          message: "%s",
          "metrics-registry": null,
          "node-options": null,
          // We remove node-version to fix the issue described here: https://github.com/pnpm/pnpm/issues/4203#issuecomment-1133872769
          "offline": false,
          "onload-script": false,
          only: null,
          optional: true,
          otp: null,
          "package-lock": true,
          "package-lock-only": false,
          parseable: false,
          "prefer-offline": false,
          "prefer-online": false,
          prefix: globalPrefix,
          production: true,
          "progress": !process.env.TRAVIS && !process.env.CI,
          provenance: false,
          proxy: null,
          "https-proxy": null,
          "no-proxy": null,
          "user-agent": "npm/{npm-version} node/{node-version} {platform} {arch}",
          "read-only": false,
          "rebuild-bundle": true,
          registry: "https://registry.npmjs.org/",
          rollback: true,
          save: true,
          "save-bundle": false,
          "save-dev": false,
          "save-exact": false,
          "save-optional": false,
          "save-prefix": "^",
          "save-prod": false,
          scope: "",
          "script-shell": null,
          "scripts-prepend-node-path": "warn-only",
          searchopts: "",
          searchexclude: null,
          searchlimit: 20,
          searchstaleness: 15 * 60,
          "send-metrics": false,
          shell: osenv.shell(),
          shrinkwrap: true,
          "sign-git-tag": false,
          "sso-poll-frequency": 500,
          "sso-type": "oauth",
          "strict-ssl": true,
          tag: "latest",
          "tag-version-prefix": "v",
          timing: false,
          tmp: temp,
          unicode: hasUnicode(),
          "unsafe-perm": process.platform === "win32" || process.platform === "cygwin" || !(process.getuid && process.setuid && process.getgid && process.setgid) || process.getuid() !== 0,
          usage: false,
          user: process.platform === "win32" ? 0 : "nobody",
          userconfig: path16.resolve(home, ".npmrc"),
          umask: process.umask ? process.umask() : umask.fromString("022"),
          version: false,
          versions: false,
          viewer: process.platform === "win32" ? "browser" : "man",
          _exit: true
        };
        return defaults;
      }
    });
  }
});

// node_modules/@pnpm/npm-conf/index.js
var require_npm_conf = __commonJS({
  "node_modules/@pnpm/npm-conf/index.js"(exports, module) {
    "use strict";
    var path16 = __require("path");
    var Conf = require_conf();
    var _defaults = require_defaults();
    module.exports = (opts, types, defaults) => {
      const conf = new Conf(Object.assign({}, _defaults.defaults, defaults), types);
      conf.add(Object.assign({}, opts), "cli");
      const warnings = [];
      let failedToLoadBuiltInConfig = false;
      if (__require.resolve.paths) {
        const paths = __require.resolve.paths("npm");
        let npmPath;
        try {
          npmPath = __require.resolve("npm", { paths: paths.slice(-1) });
        } catch (error) {
          failedToLoadBuiltInConfig = true;
        }
        if (npmPath) {
          warnings.push(conf.addFile(path16.resolve(path16.dirname(npmPath), "..", "npmrc"), "builtin"));
        }
      }
      conf.addEnv();
      conf.loadPrefix();
      const projectConf = path16.resolve(conf.localPrefix, ".npmrc");
      const userConf = conf.get("userconfig");
      if (!conf.get("global") && projectConf !== userConf) {
        warnings.push(conf.addFile(projectConf, "project"));
      } else {
        conf.add({}, "project");
      }
      if (conf.get("workspace-prefix") && conf.get("workspace-prefix") !== projectConf) {
        const workspaceConf = path16.resolve(conf.get("workspace-prefix"), ".npmrc");
        warnings.push(conf.addFile(workspaceConf, "workspace"));
      }
      warnings.push(conf.addFile(conf.get("userconfig"), "user"));
      if (conf.get("prefix")) {
        const etc = path16.resolve(conf.get("prefix"), "etc");
        conf.root.globalconfig = path16.resolve(etc, "npmrc");
        conf.root.globalignorefile = path16.resolve(etc, "npmignore");
      }
      warnings.push(conf.addFile(conf.get("globalconfig"), "global"));
      conf.loadUser();
      const caFile = conf.get("cafile");
      if (caFile) {
        conf.loadCAFile(caFile);
      }
      return {
        config: conf,
        warnings: warnings.filter(Boolean),
        failedToLoadBuiltInConfig
      };
    };
    Object.defineProperty(module.exports, "defaults", {
      get() {
        return _defaults.defaults;
      },
      enumerable: true
    });
  }
});

// node_modules/registry-auth-token/index.js
var require_registry_auth_token = __commonJS({
  "node_modules/registry-auth-token/index.js"(exports, module) {
    var npmConf = require_npm_conf();
    var tokenKey = ":_authToken";
    var legacyTokenKey = ":_auth";
    var userKey = ":username";
    var passwordKey = ":_password";
    module.exports = function getRegistryAuthToken() {
      let checkUrl;
      let options;
      if (arguments.length >= 2) {
        checkUrl = arguments[0];
        options = Object.assign({}, arguments[1]);
      } else if (typeof arguments[0] === "string") {
        checkUrl = arguments[0];
      } else {
        options = Object.assign({}, arguments[0]);
      }
      options = options || {};
      const providedNpmrc = options.npmrc;
      options.npmrc = (options.npmrc ? {
        config: {
          get: (key) => providedNpmrc[key]
        }
      } : npmConf()).config;
      checkUrl = checkUrl || options.npmrc.get("registry") || npmConf.defaults.registry;
      return getRegistryAuthInfo(checkUrl, options) || getLegacyAuthInfo(options.npmrc);
    };
    function urlResolve(from, to) {
      const resolvedUrl = new URL(to, new URL(from.startsWith("//") ? `./${from}` : from, "resolve://"));
      if (resolvedUrl.protocol === "resolve:") {
        const { pathname, search, hash } = resolvedUrl;
        return pathname + search + hash;
      }
      return resolvedUrl.toString();
    }
    function getRegistryAuthInfo(checkUrl, options) {
      let parsed = checkUrl instanceof URL ? checkUrl : new URL(checkUrl.startsWith("//") ? `http:${checkUrl}` : checkUrl);
      let pathname;
      while (pathname !== "/" && parsed.pathname !== pathname) {
        pathname = parsed.pathname || "/";
        const regUrl = "//" + parsed.host + pathname.replace(/\/$/, "");
        const authInfo = getAuthInfoForUrl(regUrl, options.npmrc);
        if (authInfo) {
          return authInfo;
        }
        if (!options.recursive) {
          return /\/$/.test(checkUrl) ? void 0 : getRegistryAuthInfo(new URL("./", parsed), options);
        }
        parsed.pathname = urlResolve(normalizePath(pathname), "..") || "/";
      }
      return void 0;
    }
    function getLegacyAuthInfo(npmrc) {
      if (!npmrc.get("_auth")) {
        return void 0;
      }
      const token = replaceEnvironmentVariable(npmrc.get("_auth"));
      return { token, type: "Basic" };
    }
    function normalizePath(path16) {
      return path16[path16.length - 1] === "/" ? path16 : path16 + "/";
    }
    function getAuthInfoForUrl(regUrl, npmrc) {
      const bearerAuth = getBearerToken(npmrc.get(regUrl + tokenKey) || npmrc.get(regUrl + "/" + tokenKey));
      if (bearerAuth) {
        return bearerAuth;
      }
      const username = npmrc.get(regUrl + userKey) || npmrc.get(regUrl + "/" + userKey);
      const password = npmrc.get(regUrl + passwordKey) || npmrc.get(regUrl + "/" + passwordKey);
      const basicAuth = getTokenForUsernameAndPassword(username, password);
      if (basicAuth) {
        return basicAuth;
      }
      const basicAuthWithToken = getLegacyAuthToken(npmrc.get(regUrl + legacyTokenKey) || npmrc.get(regUrl + "/" + legacyTokenKey));
      if (basicAuthWithToken) {
        return basicAuthWithToken;
      }
      return void 0;
    }
    function replaceEnvironmentVariable(token) {
      return token.replace(/^\$\{?([^}]*)\}?$/, function(fullMatch, envVar) {
        return process.env[envVar];
      });
    }
    function getBearerToken(tok) {
      if (!tok) {
        return void 0;
      }
      const token = replaceEnvironmentVariable(tok);
      return { token, type: "Bearer" };
    }
    function getTokenForUsernameAndPassword(username, password) {
      if (!username || !password) {
        return void 0;
      }
      const pass = Buffer.from(replaceEnvironmentVariable(password), "base64").toString("utf8");
      const token = Buffer.from(username + ":" + pass, "utf8").toString("base64");
      return {
        token,
        type: "Basic",
        password: pass,
        username
      };
    }
    function getLegacyAuthToken(tok) {
      if (!tok) {
        return void 0;
      }
      const token = replaceEnvironmentVariable(tok);
      return { token, type: "Basic" };
    }
  }
});

// packages/cli/src/interactiveCli.tsx
var import_react130 = __toESM(require_react(), 1);
import { basename as basename5 } from "node:path";

// packages/cli/src/ui/AppContainer.tsx
var import_react129 = __toESM(require_react(), 1);

// packages/cli/src/ui/contexts/StreamingContext.tsx
var import_react = __toESM(require_react(), 1);
var StreamingContext = (0, import_react.createContext)(
  void 0
);
var useStreamingContext = () => {
  const context = import_react.default.useContext(StreamingContext);
  if (context === void 0) {
    throw new Error(
      "useStreamingContext must be used within a StreamingContextProvider"
    );
  }
  return context;
};

// packages/cli/src/ui/components/HistoryItemDisplay.tsx
var import_react38 = __toESM(require_react(), 1);

// packages/cli/src/ui/components/messages/UserMessage.tsx
var import_react3 = __toESM(require_react(), 1);

// packages/cli/src/ui/textConstants.ts
var SCREEN_READER_USER_PREFIX = "User: ";
var SCREEN_READER_MODEL_PREFIX = "Model: ";
var SCREEN_READER_LOADING = "loading";
var SCREEN_READER_RESPONDING = "responding";
var GENERIC_WORKING_LABEL = "Working...";

// packages/cli/src/ui/components/shared/HalfLinePaddedBox.tsx
var import_react2 = __toESM(require_react(), 1);

// packages/cli/src/ui/utils/terminalUtils.ts
import process2 from "node:process";
function getColorDepth() {
  return process2.stdout.getColorDepth ? process2.stdout.getColorDepth() : 24;
}
function isLowColorDepth() {
  return getColorDepth() < 24;
}
var cachedIsITerm2;
function isITerm2() {
  if (cachedIsITerm2 !== void 0) {
    return cachedIsITerm2;
  }
  cachedIsITerm2 = process2.env["TERM_PROGRAM"] === "iTerm.app";
  return cachedIsITerm2;
}

// packages/cli/src/ui/components/shared/HalfLinePaddedBox.tsx
var import_jsx_runtime = __toESM(require_jsx_runtime(), 1);
var HalfLinePaddedBox = (props) => {
  const isScreenReaderEnabled = use_is_screen_reader_enabled_default();
  if (props.useBackgroundColor === false || isScreenReaderEnabled) {
    return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_jsx_runtime.Fragment, { children: props.children });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(HalfLinePaddedBoxInternal, { ...props });
};
var HalfLinePaddedBoxInternal = ({
  backgroundBaseColor,
  backgroundOpacity,
  children
}) => {
  const { terminalWidth } = useUIState();
  const terminalBg = theme.background.primary || "black";
  const isLowColor = isLowColorDepth();
  const backgroundColor = (0, import_react2.useMemo)(() => {
    if (isLowColor) {
      return getSafeLowColorBackground(terminalBg);
    }
    const resolvedBase = resolveColor(backgroundBaseColor) || backgroundBaseColor;
    const resolvedTerminalBg = resolveColor(terminalBg) || terminalBg;
    return interpolateColor(
      resolvedTerminalBg,
      resolvedBase,
      backgroundOpacity
    );
  }, [backgroundBaseColor, backgroundOpacity, terminalBg, isLowColor]);
  if (!backgroundColor) {
    return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_jsx_runtime.Fragment, { children });
  }
  const isITerm = isITerm2();
  if (isITerm) {
    return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
      Box_default,
      {
        width: terminalWidth,
        flexDirection: "column",
        alignItems: "stretch",
        minHeight: 1,
        flexShrink: 0,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Box_default, { width: terminalWidth, flexDirection: "row", children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Text, { color: backgroundColor, children: "\u2584".repeat(terminalWidth) }) }),
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
            Box_default,
            {
              width: terminalWidth,
              flexDirection: "column",
              alignItems: "stretch",
              backgroundColor,
              children
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Box_default, { width: terminalWidth, flexDirection: "row", children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Text, { color: backgroundColor, children: "\u2580".repeat(terminalWidth) }) })
        ]
      }
    );
  }
  return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
    Box_default,
    {
      width: terminalWidth,
      flexDirection: "column",
      alignItems: "stretch",
      minHeight: 1,
      flexShrink: 0,
      backgroundColor,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Box_default, { width: terminalWidth, flexDirection: "row", children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Text, { backgroundColor, color: terminalBg, children: "\u2580".repeat(terminalWidth) }) }),
        children,
        /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Box_default, { width: terminalWidth, flexDirection: "row", children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Text, { color: terminalBg, backgroundColor, children: "\u2584".repeat(terminalWidth) }) })
      ]
    }
  );
};

// packages/cli/src/ui/components/messages/UserMessage.tsx
var import_jsx_runtime2 = __toESM(require_jsx_runtime(), 1);
var UserMessage = ({ text, width }) => {
  const prefix = "> ";
  const prefixWidth = prefix.length;
  const isSlashCommand2 = isSlashCommand(text);
  const config = useConfig();
  const useBackgroundColor = config.getUseBackgroundColor();
  const textColor = isSlashCommand2 ? theme.text.accent : theme.text.primary;
  const displayText = (0, import_react3.useMemo)(() => {
    if (!text) return text;
    return text.split("\n").map((line) => {
      const transformations = calculateTransformationsForLine(line);
      const { transformedLine } = calculateTransformedLine(
        line,
        0,
        // line index doesn't matter since cursor is [-1, -1]
        [-1, -1],
        transformations
      );
      return transformedLine;
    }).join("\n");
  }, [text]);
  return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
    HalfLinePaddedBox,
    {
      backgroundBaseColor: theme.background.message,
      backgroundOpacity: 1,
      useBackgroundColor,
      children: /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
        Box_default,
        {
          flexDirection: "row",
          paddingY: 0,
          marginY: useBackgroundColor ? 0 : 1,
          paddingX: useBackgroundColor ? 1 : 0,
          alignSelf: "flex-start",
          width,
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(Box_default, { width: prefixWidth, flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
              Text,
              {
                color: theme.text.accent,
                "aria-label": SCREEN_READER_USER_PREFIX,
                children: prefix
              }
            ) }),
            /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(Box_default, { flexGrow: 1, children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(Text, { wrap: "wrap", color: textColor, children: displayText }) })
          ]
        }
      )
    }
  );
};

// packages/cli/src/ui/components/messages/UserShellMessage.tsx
var import_jsx_runtime3 = __toESM(require_jsx_runtime(), 1);
var UserShellMessage = ({
  text,
  width
}) => {
  const config = useConfig();
  const useBackgroundColor = config.getUseBackgroundColor();
  const commandToDisplay = text.startsWith("!") ? text.substring(1) : text;
  return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
    HalfLinePaddedBox,
    {
      backgroundBaseColor: theme.background.message,
      backgroundOpacity: 1,
      useBackgroundColor,
      children: /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(
        Box_default,
        {
          paddingY: 0,
          marginY: useBackgroundColor ? 0 : 1,
          paddingX: useBackgroundColor ? 1 : 0,
          width,
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(Text, { color: theme.ui.symbol, children: "$ " }),
            /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(Text, { color: theme.text.primary, children: commandToDisplay })
          ]
        }
      )
    }
  );
};

// packages/cli/src/ui/utils/MarkdownDisplay.tsx
var import_react9 = __toESM(require_react(), 1);

// packages/cli/src/ui/utils/CodeColorizer.tsx
var import_react6 = __toESM(require_react(), 1);

// node_modules/highlight.js/es/languages/arduino.js
function cPlusPlus(hljs) {
  const regex = hljs.regex;
  const C_LINE_COMMENT_MODE = hljs.COMMENT("//", "$", { contains: [{ begin: /\\\n/ }] });
  const DECLTYPE_AUTO_RE = "decltype\\(auto\\)";
  const NAMESPACE_RE = "[a-zA-Z_]\\w*::";
  const TEMPLATE_ARGUMENT_RE = "<[^<>]+>";
  const FUNCTION_TYPE_RE = "(?!struct)(" + DECLTYPE_AUTO_RE + "|" + regex.optional(NAMESPACE_RE) + "[a-zA-Z_]\\w*" + regex.optional(TEMPLATE_ARGUMENT_RE) + ")";
  const CPP_PRIMITIVE_TYPES = {
    className: "type",
    begin: "\\b[a-z\\d_]*_t\\b"
  };
  const CHARACTER_ESCAPES = "\\\\(x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4,8}|[0-7]{3}|\\S)";
  const STRINGS = {
    className: "string",
    variants: [
      {
        begin: '(u8?|U|L)?"',
        end: '"',
        illegal: "\\n",
        contains: [hljs.BACKSLASH_ESCAPE]
      },
      {
        begin: "(u8?|U|L)?'(" + CHARACTER_ESCAPES + "|.)",
        end: "'",
        illegal: "."
      },
      hljs.END_SAME_AS_BEGIN({
        begin: /(?:u8?|U|L)?R"([^()\\ ]{0,16})\(/,
        end: /\)([^()\\ ]{0,16})"/
      })
    ]
  };
  const NUMBERS = {
    className: "number",
    variants: [
      // Floating-point literal.
      {
        begin: "[+-]?(?:(?:[0-9](?:'?[0-9])*\\.(?:[0-9](?:'?[0-9])*)?|\\.[0-9](?:'?[0-9])*)(?:[Ee][+-]?[0-9](?:'?[0-9])*)?|[0-9](?:'?[0-9])*[Ee][+-]?[0-9](?:'?[0-9])*|0[Xx](?:[0-9A-Fa-f](?:'?[0-9A-Fa-f])*(?:\\.(?:[0-9A-Fa-f](?:'?[0-9A-Fa-f])*)?)?|\\.[0-9A-Fa-f](?:'?[0-9A-Fa-f])*)[Pp][+-]?[0-9](?:'?[0-9])*)(?:[Ff](?:16|32|64|128)?|(BF|bf)16|[Ll]|)"
      },
      // Integer literal.
      {
        begin: "[+-]?\\b(?:0[Bb][01](?:'?[01])*|0[Xx][0-9A-Fa-f](?:'?[0-9A-Fa-f])*|0(?:'?[0-7])*|[1-9](?:'?[0-9])*)(?:[Uu](?:LL?|ll?)|[Uu][Zz]?|(?:LL?|ll?)[Uu]?|[Zz][Uu]|)"
        // Note: there are user-defined literal suffixes too, but perhaps having the custom suffix not part of the
        // literal highlight actually makes it stand out more.
      }
    ],
    relevance: 0
  };
  const PREPROCESSOR = {
    className: "meta",
    begin: /#\s*[a-z]+\b/,
    end: /$/,
    keywords: { keyword: "if else elif endif define undef warning error line pragma _Pragma ifdef ifndef include" },
    contains: [
      {
        begin: /\\\n/,
        relevance: 0
      },
      hljs.inherit(STRINGS, { className: "string" }),
      {
        className: "string",
        begin: /<.*?>/
      },
      C_LINE_COMMENT_MODE,
      hljs.C_BLOCK_COMMENT_MODE
    ]
  };
  const TITLE_MODE = {
    className: "title",
    begin: regex.optional(NAMESPACE_RE) + hljs.IDENT_RE,
    relevance: 0
  };
  const FUNCTION_TITLE = regex.optional(NAMESPACE_RE) + hljs.IDENT_RE + "\\s*\\(";
  const RESERVED_KEYWORDS = [
    "alignas",
    "alignof",
    "and",
    "and_eq",
    "asm",
    "atomic_cancel",
    "atomic_commit",
    "atomic_noexcept",
    "auto",
    "bitand",
    "bitor",
    "break",
    "case",
    "catch",
    "class",
    "co_await",
    "co_return",
    "co_yield",
    "compl",
    "concept",
    "const_cast|10",
    "consteval",
    "constexpr",
    "constinit",
    "continue",
    "decltype",
    "default",
    "delete",
    "do",
    "dynamic_cast|10",
    "else",
    "enum",
    "explicit",
    "export",
    "extern",
    "false",
    "final",
    "for",
    "friend",
    "goto",
    "if",
    "import",
    "inline",
    "module",
    "mutable",
    "namespace",
    "new",
    "noexcept",
    "not",
    "not_eq",
    "nullptr",
    "operator",
    "or",
    "or_eq",
    "override",
    "private",
    "protected",
    "public",
    "reflexpr",
    "register",
    "reinterpret_cast|10",
    "requires",
    "return",
    "sizeof",
    "static_assert",
    "static_cast|10",
    "struct",
    "switch",
    "synchronized",
    "template",
    "this",
    "thread_local",
    "throw",
    "transaction_safe",
    "transaction_safe_dynamic",
    "true",
    "try",
    "typedef",
    "typeid",
    "typename",
    "union",
    "using",
    "virtual",
    "volatile",
    "while",
    "xor",
    "xor_eq"
  ];
  const RESERVED_TYPES = [
    "bool",
    "char",
    "char16_t",
    "char32_t",
    "char8_t",
    "double",
    "float",
    "int",
    "long",
    "short",
    "void",
    "wchar_t",
    "unsigned",
    "signed",
    "const",
    "static"
  ];
  const TYPE_HINTS = [
    "any",
    "auto_ptr",
    "barrier",
    "binary_semaphore",
    "bitset",
    "complex",
    "condition_variable",
    "condition_variable_any",
    "counting_semaphore",
    "deque",
    "false_type",
    "flat_map",
    "flat_set",
    "future",
    "imaginary",
    "initializer_list",
    "istringstream",
    "jthread",
    "latch",
    "lock_guard",
    "multimap",
    "multiset",
    "mutex",
    "optional",
    "ostringstream",
    "packaged_task",
    "pair",
    "promise",
    "priority_queue",
    "queue",
    "recursive_mutex",
    "recursive_timed_mutex",
    "scoped_lock",
    "set",
    "shared_future",
    "shared_lock",
    "shared_mutex",
    "shared_timed_mutex",
    "shared_ptr",
    "stack",
    "string_view",
    "stringstream",
    "timed_mutex",
    "thread",
    "true_type",
    "tuple",
    "unique_lock",
    "unique_ptr",
    "unordered_map",
    "unordered_multimap",
    "unordered_multiset",
    "unordered_set",
    "variant",
    "vector",
    "weak_ptr",
    "wstring",
    "wstring_view"
  ];
  const FUNCTION_HINTS = [
    "abort",
    "abs",
    "acos",
    "apply",
    "as_const",
    "asin",
    "atan",
    "atan2",
    "calloc",
    "ceil",
    "cerr",
    "cin",
    "clog",
    "cos",
    "cosh",
    "cout",
    "declval",
    "endl",
    "exchange",
    "exit",
    "exp",
    "fabs",
    "floor",
    "fmod",
    "forward",
    "fprintf",
    "fputs",
    "free",
    "frexp",
    "fscanf",
    "future",
    "invoke",
    "isalnum",
    "isalpha",
    "iscntrl",
    "isdigit",
    "isgraph",
    "islower",
    "isprint",
    "ispunct",
    "isspace",
    "isupper",
    "isxdigit",
    "labs",
    "launder",
    "ldexp",
    "log",
    "log10",
    "make_pair",
    "make_shared",
    "make_shared_for_overwrite",
    "make_tuple",
    "make_unique",
    "malloc",
    "memchr",
    "memcmp",
    "memcpy",
    "memset",
    "modf",
    "move",
    "pow",
    "printf",
    "putchar",
    "puts",
    "realloc",
    "scanf",
    "sin",
    "sinh",
    "snprintf",
    "sprintf",
    "sqrt",
    "sscanf",
    "std",
    "stderr",
    "stdin",
    "stdout",
    "strcat",
    "strchr",
    "strcmp",
    "strcpy",
    "strcspn",
    "strlen",
    "strncat",
    "strncmp",
    "strncpy",
    "strpbrk",
    "strrchr",
    "strspn",
    "strstr",
    "swap",
    "tan",
    "tanh",
    "terminate",
    "to_underlying",
    "tolower",
    "toupper",
    "vfprintf",
    "visit",
    "vprintf",
    "vsprintf"
  ];
  const LITERALS3 = [
    "NULL",
    "false",
    "nullopt",
    "nullptr",
    "true"
  ];
  const BUILT_IN = ["_Pragma"];
  const CPP_KEYWORDS = {
    type: RESERVED_TYPES,
    keyword: RESERVED_KEYWORDS,
    literal: LITERALS3,
    built_in: BUILT_IN,
    _type_hints: TYPE_HINTS
  };
  const FUNCTION_DISPATCH = {
    className: "function.dispatch",
    relevance: 0,
    keywords: {
      // Only for relevance, not highlighting.
      _hint: FUNCTION_HINTS
    },
    begin: regex.concat(
      /\b/,
      /(?!decltype)/,
      /(?!if)/,
      /(?!for)/,
      /(?!switch)/,
      /(?!while)/,
      hljs.IDENT_RE,
      regex.lookahead(/(<[^<>]+>|)\s*\(/)
    )
  };
  const EXPRESSION_CONTAINS = [
    FUNCTION_DISPATCH,
    PREPROCESSOR,
    CPP_PRIMITIVE_TYPES,
    C_LINE_COMMENT_MODE,
    hljs.C_BLOCK_COMMENT_MODE,
    NUMBERS,
    STRINGS
  ];
  const EXPRESSION_CONTEXT = {
    // This mode covers expression context where we can't expect a function
    // definition and shouldn't highlight anything that looks like one:
    // `return some()`, `else if()`, `(x*sum(1, 2))`
    variants: [
      {
        begin: /=/,
        end: /;/
      },
      {
        begin: /\(/,
        end: /\)/
      },
      {
        beginKeywords: "new throw return else",
        end: /;/
      }
    ],
    keywords: CPP_KEYWORDS,
    contains: EXPRESSION_CONTAINS.concat([
      {
        begin: /\(/,
        end: /\)/,
        keywords: CPP_KEYWORDS,
        contains: EXPRESSION_CONTAINS.concat(["self"]),
        relevance: 0
      }
    ]),
    relevance: 0
  };
  const FUNCTION_DECLARATION = {
    className: "function",
    begin: "(" + FUNCTION_TYPE_RE + "[\\*&\\s]+)+" + FUNCTION_TITLE,
    returnBegin: true,
    end: /[{;=]/,
    excludeEnd: true,
    keywords: CPP_KEYWORDS,
    illegal: /[^\w\s\*&:<>.]/,
    contains: [
      {
        // to prevent it from being confused as the function title
        begin: DECLTYPE_AUTO_RE,
        keywords: CPP_KEYWORDS,
        relevance: 0
      },
      {
        begin: FUNCTION_TITLE,
        returnBegin: true,
        contains: [TITLE_MODE],
        relevance: 0
      },
      // needed because we do not have look-behind on the below rule
      // to prevent it from grabbing the final : in a :: pair
      {
        begin: /::/,
        relevance: 0
      },
      // initializers
      {
        begin: /:/,
        endsWithParent: true,
        contains: [
          STRINGS,
          NUMBERS
        ]
      },
      // allow for multiple declarations, e.g.:
      // extern void f(int), g(char);
      {
        relevance: 0,
        match: /,/
      },
      {
        className: "params",
        begin: /\(/,
        end: /\)/,
        keywords: CPP_KEYWORDS,
        relevance: 0,
        contains: [
          C_LINE_COMMENT_MODE,
          hljs.C_BLOCK_COMMENT_MODE,
          STRINGS,
          NUMBERS,
          CPP_PRIMITIVE_TYPES,
          // Count matching parentheses.
          {
            begin: /\(/,
            end: /\)/,
            keywords: CPP_KEYWORDS,
            relevance: 0,
            contains: [
              "self",
              C_LINE_COMMENT_MODE,
              hljs.C_BLOCK_COMMENT_MODE,
              STRINGS,
              NUMBERS,
              CPP_PRIMITIVE_TYPES
            ]
          }
        ]
      },
      CPP_PRIMITIVE_TYPES,
      C_LINE_COMMENT_MODE,
      hljs.C_BLOCK_COMMENT_MODE,
      PREPROCESSOR
    ]
  };
  return {
    name: "C++",
    aliases: [
      "cc",
      "c++",
      "h++",
      "hpp",
      "hh",
      "hxx",
      "cxx"
    ],
    keywords: CPP_KEYWORDS,
    illegal: "</",
    classNameAliases: { "function.dispatch": "built_in" },
    contains: [].concat(
      EXPRESSION_CONTEXT,
      FUNCTION_DECLARATION,
      FUNCTION_DISPATCH,
      EXPRESSION_CONTAINS,
      [
        PREPROCESSOR,
        {
          // containers: ie, `vector <int> rooms (9);`
          begin: "\\b(deque|list|queue|priority_queue|pair|stack|vector|map|set|bitset|multiset|multimap|unordered_map|unordered_set|unordered_multiset|unordered_multimap|array|tuple|optional|variant|function|flat_map|flat_set)\\s*<(?!<)",
          end: ">",
          keywords: CPP_KEYWORDS,
          contains: [
            "self",
            CPP_PRIMITIVE_TYPES
          ]
        },
        {
          begin: hljs.IDENT_RE + "::",
          keywords: CPP_KEYWORDS
        },
        {
          match: [
            // extra complexity to deal with `enum class` and `enum struct`
            /\b(?:enum(?:\s+(?:class|struct))?|class|struct|union)/,
            /\s+/,
            /\w+/
          ],
          className: {
            1: "keyword",
            3: "title.class"
          }
        }
      ]
    )
  };
}
function arduino(hljs) {
  const ARDUINO_KW = {
    type: [
      "boolean",
      "byte",
      "word",
      "String"
    ],
    built_in: [
      "KeyboardController",
      "MouseController",
      "SoftwareSerial",
      "EthernetServer",
      "EthernetClient",
      "LiquidCrystal",
      "RobotControl",
      "GSMVoiceCall",
      "EthernetUDP",
      "EsploraTFT",
      "HttpClient",
      "RobotMotor",
      "WiFiClient",
      "GSMScanner",
      "FileSystem",
      "Scheduler",
      "GSMServer",
      "YunClient",
      "YunServer",
      "IPAddress",
      "GSMClient",
      "GSMModem",
      "Keyboard",
      "Ethernet",
      "Console",
      "GSMBand",
      "Esplora",
      "Stepper",
      "Process",
      "WiFiUDP",
      "GSM_SMS",
      "Mailbox",
      "USBHost",
      "Firmata",
      "PImage",
      "Client",
      "Server",
      "GSMPIN",
      "FileIO",
      "Bridge",
      "Serial",
      "EEPROM",
      "Stream",
      "Mouse",
      "Audio",
      "Servo",
      "File",
      "Task",
      "GPRS",
      "WiFi",
      "Wire",
      "TFT",
      "GSM",
      "SPI",
      "SD"
    ],
    _hints: [
      "setup",
      "loop",
      "runShellCommandAsynchronously",
      "analogWriteResolution",
      "retrieveCallingNumber",
      "printFirmwareVersion",
      "analogReadResolution",
      "sendDigitalPortPair",
      "noListenOnLocalhost",
      "readJoystickButton",
      "setFirmwareVersion",
      "readJoystickSwitch",
      "scrollDisplayRight",
      "getVoiceCallStatus",
      "scrollDisplayLeft",
      "writeMicroseconds",
      "delayMicroseconds",
      "beginTransmission",
      "getSignalStrength",
      "runAsynchronously",
      "getAsynchronously",
      "listenOnLocalhost",
      "getCurrentCarrier",
      "readAccelerometer",
      "messageAvailable",
      "sendDigitalPorts",
      "lineFollowConfig",
      "countryNameWrite",
      "runShellCommand",
      "readStringUntil",
      "rewindDirectory",
      "readTemperature",
      "setClockDivider",
      "readLightSensor",
      "endTransmission",
      "analogReference",
      "detachInterrupt",
      "countryNameRead",
      "attachInterrupt",
      "encryptionType",
      "readBytesUntil",
      "robotNameWrite",
      "readMicrophone",
      "robotNameRead",
      "cityNameWrite",
      "userNameWrite",
      "readJoystickY",
      "readJoystickX",
      "mouseReleased",
      "openNextFile",
      "scanNetworks",
      "noInterrupts",
      "digitalWrite",
      "beginSpeaker",
      "mousePressed",
      "isActionDone",
      "mouseDragged",
      "displayLogos",
      "noAutoscroll",
      "addParameter",
      "remoteNumber",
      "getModifiers",
      "keyboardRead",
      "userNameRead",
      "waitContinue",
      "processInput",
      "parseCommand",
      "printVersion",
      "readNetworks",
      "writeMessage",
      "blinkVersion",
      "cityNameRead",
      "readMessage",
      "setDataMode",
      "parsePacket",
      "isListening",
      "setBitOrder",
      "beginPacket",
      "isDirectory",
      "motorsWrite",
      "drawCompass",
      "digitalRead",
      "clearScreen",
      "serialEvent",
      "rightToLeft",
      "setTextSize",
      "leftToRight",
      "requestFrom",
      "keyReleased",
      "compassRead",
      "analogWrite",
      "interrupts",
      "WiFiServer",
      "disconnect",
      "playMelody",
      "parseFloat",
      "autoscroll",
      "getPINUsed",
      "setPINUsed",
      "setTimeout",
      "sendAnalog",
      "readSlider",
      "analogRead",
      "beginWrite",
      "createChar",
      "motorsStop",
      "keyPressed",
      "tempoWrite",
      "readButton",
      "subnetMask",
      "debugPrint",
      "macAddress",
      "writeGreen",
      "randomSeed",
      "attachGPRS",
      "readString",
      "sendString",
      "remotePort",
      "releaseAll",
      "mouseMoved",
      "background",
      "getXChange",
      "getYChange",
      "answerCall",
      "getResult",
      "voiceCall",
      "endPacket",
      "constrain",
      "getSocket",
      "writeJSON",
      "getButton",
      "available",
      "connected",
      "findUntil",
      "readBytes",
      "exitValue",
      "readGreen",
      "writeBlue",
      "startLoop",
      "IPAddress",
      "isPressed",
      "sendSysex",
      "pauseMode",
      "gatewayIP",
      "setCursor",
      "getOemKey",
      "tuneWrite",
      "noDisplay",
      "loadImage",
      "switchPIN",
      "onRequest",
      "onReceive",
      "changePIN",
      "playFile",
      "noBuffer",
      "parseInt",
      "overflow",
      "checkPIN",
      "knobRead",
      "beginTFT",
      "bitClear",
      "updateIR",
      "bitWrite",
      "position",
      "writeRGB",
      "highByte",
      "writeRed",
      "setSpeed",
      "readBlue",
      "noStroke",
      "remoteIP",
      "transfer",
      "shutdown",
      "hangCall",
      "beginSMS",
      "endWrite",
      "attached",
      "maintain",
      "noCursor",
      "checkReg",
      "checkPUK",
      "shiftOut",
      "isValid",
      "shiftIn",
      "pulseIn",
      "connect",
      "println",
      "localIP",
      "pinMode",
      "getIMEI",
      "display",
      "noBlink",
      "process",
      "getBand",
      "running",
      "beginSD",
      "drawBMP",
      "lowByte",
      "setBand",
      "release",
      "bitRead",
      "prepare",
      "pointTo",
      "readRed",
      "setMode",
      "noFill",
      "remove",
      "listen",
      "stroke",
      "detach",
      "attach",
      "noTone",
      "exists",
      "buffer",
      "height",
      "bitSet",
      "circle",
      "config",
      "cursor",
      "random",
      "IRread",
      "setDNS",
      "endSMS",
      "getKey",
      "micros",
      "millis",
      "begin",
      "print",
      "write",
      "ready",
      "flush",
      "width",
      "isPIN",
      "blink",
      "clear",
      "press",
      "mkdir",
      "rmdir",
      "close",
      "point",
      "yield",
      "image",
      "BSSID",
      "click",
      "delay",
      "read",
      "text",
      "move",
      "peek",
      "beep",
      "rect",
      "line",
      "open",
      "seek",
      "fill",
      "size",
      "turn",
      "stop",
      "home",
      "find",
      "step",
      "tone",
      "sqrt",
      "RSSI",
      "SSID",
      "end",
      "bit",
      "tan",
      "cos",
      "sin",
      "pow",
      "map",
      "abs",
      "max",
      "min",
      "get",
      "run",
      "put"
    ],
    literal: [
      "DIGITAL_MESSAGE",
      "FIRMATA_STRING",
      "ANALOG_MESSAGE",
      "REPORT_DIGITAL",
      "REPORT_ANALOG",
      "INPUT_PULLUP",
      "SET_PIN_MODE",
      "INTERNAL2V56",
      "SYSTEM_RESET",
      "LED_BUILTIN",
      "INTERNAL1V1",
      "SYSEX_START",
      "INTERNAL",
      "EXTERNAL",
      "DEFAULT",
      "OUTPUT",
      "INPUT",
      "HIGH",
      "LOW"
    ]
  };
  const ARDUINO = cPlusPlus(hljs);
  const kws = (
    /** @type {Record<string,any>} */
    ARDUINO.keywords
  );
  kws.type = [
    ...kws.type,
    ...ARDUINO_KW.type
  ];
  kws.literal = [
    ...kws.literal,
    ...ARDUINO_KW.literal
  ];
  kws.built_in = [
    ...kws.built_in,
    ...ARDUINO_KW.built_in
  ];
  kws._hints = ARDUINO_KW._hints;
  ARDUINO.name = "Arduino";
  ARDUINO.aliases = ["ino"];
  ARDUINO.supersetOf = "cpp";
  return ARDUINO;
}

// node_modules/highlight.js/es/languages/bash.js
function bash(hljs) {
  const regex = hljs.regex;
  const VAR = {};
  const BRACED_VAR = {
    begin: /\$\{/,
    end: /\}/,
    contains: [
      "self",
      {
        begin: /:-/,
        contains: [VAR]
      }
      // default values
    ]
  };
  Object.assign(VAR, {
    className: "variable",
    variants: [
      { begin: regex.concat(
        /\$[\w\d#@][\w\d_]*/,
        // negative look-ahead tries to avoid matching patterns that are not
        // Perl at all like $ident$, @ident@, etc.
        `(?![\\w\\d])(?![$])`
      ) },
      BRACED_VAR
    ]
  });
  const SUBST = {
    className: "subst",
    begin: /\$\(/,
    end: /\)/,
    contains: [hljs.BACKSLASH_ESCAPE]
  };
  const COMMENT = hljs.inherit(
    hljs.COMMENT(),
    {
      match: [
        /(^|\s)/,
        /#.*$/
      ],
      scope: {
        2: "comment"
      }
    }
  );
  const HERE_DOC = {
    begin: /<<-?\s*(?=\w+)/,
    starts: { contains: [
      hljs.END_SAME_AS_BEGIN({
        begin: /(\w+)/,
        end: /(\w+)/,
        className: "string"
      })
    ] }
  };
  const QUOTE_STRING = {
    className: "string",
    begin: /"/,
    end: /"/,
    contains: [
      hljs.BACKSLASH_ESCAPE,
      VAR,
      SUBST
    ]
  };
  SUBST.contains.push(QUOTE_STRING);
  const ESCAPED_QUOTE = {
    match: /\\"/
  };
  const APOS_STRING = {
    className: "string",
    begin: /'/,
    end: /'/
  };
  const ESCAPED_APOS = {
    match: /\\'/
  };
  const ARITHMETIC = {
    begin: /\$?\(\(/,
    end: /\)\)/,
    contains: [
      {
        begin: /\d+#[0-9a-f]+/,
        className: "number"
      },
      hljs.NUMBER_MODE,
      VAR
    ]
  };
  const SH_LIKE_SHELLS = [
    "fish",
    "bash",
    "zsh",
    "sh",
    "csh",
    "ksh",
    "tcsh",
    "dash",
    "scsh"
  ];
  const KNOWN_SHEBANG = hljs.SHEBANG({
    binary: `(${SH_LIKE_SHELLS.join("|")})`,
    relevance: 10
  });
  const FUNCTION = {
    className: "function",
    begin: /\w[\w\d_]*\s*\(\s*\)\s*\{/,
    returnBegin: true,
    contains: [hljs.inherit(hljs.TITLE_MODE, { begin: /\w[\w\d_]*/ })],
    relevance: 0
  };
  const KEYWORDS3 = [
    "if",
    "then",
    "else",
    "elif",
    "fi",
    "time",
    "for",
    "while",
    "until",
    "in",
    "do",
    "done",
    "case",
    "esac",
    "coproc",
    "function",
    "select"
  ];
  const LITERALS3 = [
    "true",
    "false"
  ];
  const PATH_MODE = { match: /(\/[a-z._-]+)+/ };
  const SHELL_BUILT_INS = [
    "break",
    "cd",
    "continue",
    "eval",
    "exec",
    "exit",
    "export",
    "getopts",
    "hash",
    "pwd",
    "readonly",
    "return",
    "shift",
    "test",
    "times",
    "trap",
    "umask",
    "unset"
  ];
  const BASH_BUILT_INS = [
    "alias",
    "bind",
    "builtin",
    "caller",
    "command",
    "declare",
    "echo",
    "enable",
    "help",
    "let",
    "local",
    "logout",
    "mapfile",
    "printf",
    "read",
    "readarray",
    "source",
    "sudo",
    "type",
    "typeset",
    "ulimit",
    "unalias"
  ];
  const ZSH_BUILT_INS = [
    "autoload",
    "bg",
    "bindkey",
    "bye",
    "cap",
    "chdir",
    "clone",
    "comparguments",
    "compcall",
    "compctl",
    "compdescribe",
    "compfiles",
    "compgroups",
    "compquote",
    "comptags",
    "comptry",
    "compvalues",
    "dirs",
    "disable",
    "disown",
    "echotc",
    "echoti",
    "emulate",
    "fc",
    "fg",
    "float",
    "functions",
    "getcap",
    "getln",
    "history",
    "integer",
    "jobs",
    "kill",
    "limit",
    "log",
    "noglob",
    "popd",
    "print",
    "pushd",
    "pushln",
    "rehash",
    "sched",
    "setcap",
    "setopt",
    "stat",
    "suspend",
    "ttyctl",
    "unfunction",
    "unhash",
    "unlimit",
    "unsetopt",
    "vared",
    "wait",
    "whence",
    "where",
    "which",
    "zcompile",
    "zformat",
    "zftp",
    "zle",
    "zmodload",
    "zparseopts",
    "zprof",
    "zpty",
    "zregexparse",
    "zsocket",
    "zstyle",
    "ztcp"
  ];
  const GNU_CORE_UTILS = [
    "chcon",
    "chgrp",
    "chown",
    "chmod",
    "cp",
    "dd",
    "df",
    "dir",
    "dircolors",
    "ln",
    "ls",
    "mkdir",
    "mkfifo",
    "mknod",
    "mktemp",
    "mv",
    "realpath",
    "rm",
    "rmdir",
    "shred",
    "sync",
    "touch",
    "truncate",
    "vdir",
    "b2sum",
    "base32",
    "base64",
    "cat",
    "cksum",
    "comm",
    "csplit",
    "cut",
    "expand",
    "fmt",
    "fold",
    "head",
    "join",
    "md5sum",
    "nl",
    "numfmt",
    "od",
    "paste",
    "ptx",
    "pr",
    "sha1sum",
    "sha224sum",
    "sha256sum",
    "sha384sum",
    "sha512sum",
    "shuf",
    "sort",
    "split",
    "sum",
    "tac",
    "tail",
    "tr",
    "tsort",
    "unexpand",
    "uniq",
    "wc",
    "arch",
    "basename",
    "chroot",
    "date",
    "dirname",
    "du",
    "echo",
    "env",
    "expr",
    "factor",
    // "false", // keyword literal already
    "groups",
    "hostid",
    "id",
    "link",
    "logname",
    "nice",
    "nohup",
    "nproc",
    "pathchk",
    "pinky",
    "printenv",
    "printf",
    "pwd",
    "readlink",
    "runcon",
    "seq",
    "sleep",
    "stat",
    "stdbuf",
    "stty",
    "tee",
    "test",
    "timeout",
    // "true", // keyword literal already
    "tty",
    "uname",
    "unlink",
    "uptime",
    "users",
    "who",
    "whoami",
    "yes"
  ];
  return {
    name: "Bash",
    aliases: [
      "sh",
      "zsh"
    ],
    keywords: {
      $pattern: /\b[a-z][a-z0-9._-]+\b/,
      keyword: KEYWORDS3,
      literal: LITERALS3,
      built_in: [
        ...SHELL_BUILT_INS,
        ...BASH_BUILT_INS,
        // Shell modifiers
        "set",
        "shopt",
        ...ZSH_BUILT_INS,
        ...GNU_CORE_UTILS
      ]
    },
    contains: [
      KNOWN_SHEBANG,
      // to catch known shells and boost relevancy
      hljs.SHEBANG(),
      // to catch unknown shells but still highlight the shebang
      FUNCTION,
      ARITHMETIC,
      COMMENT,
      HERE_DOC,
      PATH_MODE,
      QUOTE_STRING,
      ESCAPED_QUOTE,
      APOS_STRING,
      ESCAPED_APOS,
      VAR
    ]
  };
}

// node_modules/highlight.js/es/languages/c.js
function c(hljs) {
  const regex = hljs.regex;
  const C_LINE_COMMENT_MODE = hljs.COMMENT("//", "$", { contains: [{ begin: /\\\n/ }] });
  const DECLTYPE_AUTO_RE = "decltype\\(auto\\)";
  const NAMESPACE_RE = "[a-zA-Z_]\\w*::";
  const TEMPLATE_ARGUMENT_RE = "<[^<>]+>";
  const FUNCTION_TYPE_RE = "(" + DECLTYPE_AUTO_RE + "|" + regex.optional(NAMESPACE_RE) + "[a-zA-Z_]\\w*" + regex.optional(TEMPLATE_ARGUMENT_RE) + ")";
  const TYPES3 = {
    className: "type",
    variants: [
      { begin: "\\b[a-z\\d_]*_t\\b" },
      { match: /\batomic_[a-z]{3,6}\b/ }
    ]
  };
  const CHARACTER_ESCAPES = "\\\\(x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4,8}|[0-7]{3}|\\S)";
  const STRINGS = {
    className: "string",
    variants: [
      {
        begin: '(u8?|U|L)?"',
        end: '"',
        illegal: "\\n",
        contains: [hljs.BACKSLASH_ESCAPE]
      },
      {
        begin: "(u8?|U|L)?'(" + CHARACTER_ESCAPES + "|.)",
        end: "'",
        illegal: "."
      },
      hljs.END_SAME_AS_BEGIN({
        begin: /(?:u8?|U|L)?R"([^()\\ ]{0,16})\(/,
        end: /\)([^()\\ ]{0,16})"/
      })
    ]
  };
  const NUMBERS = {
    className: "number",
    variants: [
      { match: /\b(0b[01']+)/ },
      { match: /(-?)\b([\d']+(\.[\d']*)?|\.[\d']+)((ll|LL|l|L)(u|U)?|(u|U)(ll|LL|l|L)?|f|F|b|B)/ },
      { match: /(-?)\b(0[xX][a-fA-F0-9]+(?:'[a-fA-F0-9]+)*(?:\.[a-fA-F0-9]*(?:'[a-fA-F0-9]*)*)?(?:[pP][-+]?[0-9]+)?(l|L)?(u|U)?)/ },
      { match: /(-?)\b\d+(?:'\d+)*(?:\.\d*(?:'\d*)*)?(?:[eE][-+]?\d+)?/ }
    ],
    relevance: 0
  };
  const PREPROCESSOR = {
    className: "meta",
    begin: /#\s*[a-z]+\b/,
    end: /$/,
    keywords: { keyword: "if else elif endif define undef warning error line pragma _Pragma ifdef ifndef elifdef elifndef include" },
    contains: [
      {
        begin: /\\\n/,
        relevance: 0
      },
      hljs.inherit(STRINGS, { className: "string" }),
      {
        className: "string",
        begin: /<.*?>/
      },
      C_LINE_COMMENT_MODE,
      hljs.C_BLOCK_COMMENT_MODE
    ]
  };
  const TITLE_MODE = {
    className: "title",
    begin: regex.optional(NAMESPACE_RE) + hljs.IDENT_RE,
    relevance: 0
  };
  const FUNCTION_TITLE = regex.optional(NAMESPACE_RE) + hljs.IDENT_RE + "\\s*\\(";
  const C_KEYWORDS = [
    "asm",
    "auto",
    "break",
    "case",
    "continue",
    "default",
    "do",
    "else",
    "enum",
    "extern",
    "for",
    "fortran",
    "goto",
    "if",
    "inline",
    "register",
    "restrict",
    "return",
    "sizeof",
    "typeof",
    "typeof_unqual",
    "struct",
    "switch",
    "typedef",
    "union",
    "volatile",
    "while",
    "_Alignas",
    "_Alignof",
    "_Atomic",
    "_Generic",
    "_Noreturn",
    "_Static_assert",
    "_Thread_local",
    // aliases
    "alignas",
    "alignof",
    "noreturn",
    "static_assert",
    "thread_local",
    // not a C keyword but is, for all intents and purposes, treated exactly like one.
    "_Pragma"
  ];
  const C_TYPES = [
    "float",
    "double",
    "signed",
    "unsigned",
    "int",
    "short",
    "long",
    "char",
    "void",
    "_Bool",
    "_BitInt",
    "_Complex",
    "_Imaginary",
    "_Decimal32",
    "_Decimal64",
    "_Decimal96",
    "_Decimal128",
    "_Decimal64x",
    "_Decimal128x",
    "_Float16",
    "_Float32",
    "_Float64",
    "_Float128",
    "_Float32x",
    "_Float64x",
    "_Float128x",
    // modifiers
    "const",
    "static",
    "constexpr",
    // aliases
    "complex",
    "bool",
    "imaginary"
  ];
  const KEYWORDS3 = {
    keyword: C_KEYWORDS,
    type: C_TYPES,
    literal: "true false NULL",
    // TODO: apply hinting work similar to what was done in cpp.js
    built_in: "std string wstring cin cout cerr clog stdin stdout stderr stringstream istringstream ostringstream auto_ptr deque list queue stack vector map set pair bitset multiset multimap unordered_set unordered_map unordered_multiset unordered_multimap priority_queue make_pair array shared_ptr abort terminate abs acos asin atan2 atan calloc ceil cosh cos exit exp fabs floor fmod fprintf fputs free frexp fscanf future isalnum isalpha iscntrl isdigit isgraph islower isprint ispunct isspace isupper isxdigit tolower toupper labs ldexp log10 log malloc realloc memchr memcmp memcpy memset modf pow printf putchar puts scanf sinh sin snprintf sprintf sqrt sscanf strcat strchr strcmp strcpy strcspn strlen strncat strncmp strncpy strpbrk strrchr strspn strstr tanh tan vfprintf vprintf vsprintf endl initializer_list unique_ptr"
  };
  const EXPRESSION_CONTAINS = [
    PREPROCESSOR,
    TYPES3,
    C_LINE_COMMENT_MODE,
    hljs.C_BLOCK_COMMENT_MODE,
    NUMBERS,
    STRINGS
  ];
  const EXPRESSION_CONTEXT = {
    // This mode covers expression context where we can't expect a function
    // definition and shouldn't highlight anything that looks like one:
    // `return some()`, `else if()`, `(x*sum(1, 2))`
    variants: [
      {
        begin: /=/,
        end: /;/
      },
      {
        begin: /\(/,
        end: /\)/
      },
      {
        beginKeywords: "new throw return else",
        end: /;/
      }
    ],
    keywords: KEYWORDS3,
    contains: EXPRESSION_CONTAINS.concat([
      {
        begin: /\(/,
        end: /\)/,
        keywords: KEYWORDS3,
        contains: EXPRESSION_CONTAINS.concat(["self"]),
        relevance: 0
      }
    ]),
    relevance: 0
  };
  const FUNCTION_DECLARATION = {
    begin: "(" + FUNCTION_TYPE_RE + "[\\*&\\s]+)+" + FUNCTION_TITLE,
    returnBegin: true,
    end: /[{;=]/,
    excludeEnd: true,
    keywords: KEYWORDS3,
    illegal: /[^\w\s\*&:<>.]/,
    contains: [
      {
        // to prevent it from being confused as the function title
        begin: DECLTYPE_AUTO_RE,
        keywords: KEYWORDS3,
        relevance: 0
      },
      {
        begin: FUNCTION_TITLE,
        returnBegin: true,
        contains: [hljs.inherit(TITLE_MODE, { className: "title.function" })],
        relevance: 0
      },
      // allow for multiple declarations, e.g.:
      // extern void f(int), g(char);
      {
        relevance: 0,
        match: /,/
      },
      {
        className: "params",
        begin: /\(/,
        end: /\)/,
        keywords: KEYWORDS3,
        relevance: 0,
        contains: [
          C_LINE_COMMENT_MODE,
          hljs.C_BLOCK_COMMENT_MODE,
          STRINGS,
          NUMBERS,
          TYPES3,
          // Count matching parentheses.
          {
            begin: /\(/,
            end: /\)/,
            keywords: KEYWORDS3,
            relevance: 0,
            contains: [
              "self",
              C_LINE_COMMENT_MODE,
              hljs.C_BLOCK_COMMENT_MODE,
              STRINGS,
              NUMBERS,
              TYPES3
            ]
          }
        ]
      },
      TYPES3,
      C_LINE_COMMENT_MODE,
      hljs.C_BLOCK_COMMENT_MODE,
      PREPROCESSOR
    ]
  };
  return {
    name: "C",
    aliases: ["h"],
    keywords: KEYWORDS3,
    // Until differentiations are added between `c` and `cpp`, `c` will
    // not be auto-detected to avoid auto-detect conflicts between C and C++
    disableAutodetect: true,
    illegal: "</",
    contains: [].concat(
      EXPRESSION_CONTEXT,
      FUNCTION_DECLARATION,
      EXPRESSION_CONTAINS,
      [
        PREPROCESSOR,
        {
          begin: hljs.IDENT_RE + "::",
          keywords: KEYWORDS3
        },
        {
          className: "class",
          beginKeywords: "enum class struct union",
          end: /[{;:<>=]/,
          contains: [
            { beginKeywords: "final class struct" },
            hljs.TITLE_MODE
          ]
        }
      ]
    ),
    exports: {
      preprocessor: PREPROCESSOR,
      strings: STRINGS,
      keywords: KEYWORDS3
    }
  };
}

// node_modules/highlight.js/es/languages/cpp.js
function cpp(hljs) {
  const regex = hljs.regex;
  const C_LINE_COMMENT_MODE = hljs.COMMENT("//", "$", { contains: [{ begin: /\\\n/ }] });
  const DECLTYPE_AUTO_RE = "decltype\\(auto\\)";
  const NAMESPACE_RE = "[a-zA-Z_]\\w*::";
  const TEMPLATE_ARGUMENT_RE = "<[^<>]+>";
  const FUNCTION_TYPE_RE = "(?!struct)(" + DECLTYPE_AUTO_RE + "|" + regex.optional(NAMESPACE_RE) + "[a-zA-Z_]\\w*" + regex.optional(TEMPLATE_ARGUMENT_RE) + ")";
  const CPP_PRIMITIVE_TYPES = {
    className: "type",
    begin: "\\b[a-z\\d_]*_t\\b"
  };
  const CHARACTER_ESCAPES = "\\\\(x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4,8}|[0-7]{3}|\\S)";
  const STRINGS = {
    className: "string",
    variants: [
      {
        begin: '(u8?|U|L)?"',
        end: '"',
        illegal: "\\n",
        contains: [hljs.BACKSLASH_ESCAPE]
      },
      {
        begin: "(u8?|U|L)?'(" + CHARACTER_ESCAPES + "|.)",
        end: "'",
        illegal: "."
      },
      hljs.END_SAME_AS_BEGIN({
        begin: /(?:u8?|U|L)?R"([^()\\ ]{0,16})\(/,
        end: /\)([^()\\ ]{0,16})"/
      })
    ]
  };
  const NUMBERS = {
    className: "number",
    variants: [
      // Floating-point literal.
      {
        begin: "[+-]?(?:(?:[0-9](?:'?[0-9])*\\.(?:[0-9](?:'?[0-9])*)?|\\.[0-9](?:'?[0-9])*)(?:[Ee][+-]?[0-9](?:'?[0-9])*)?|[0-9](?:'?[0-9])*[Ee][+-]?[0-9](?:'?[0-9])*|0[Xx](?:[0-9A-Fa-f](?:'?[0-9A-Fa-f])*(?:\\.(?:[0-9A-Fa-f](?:'?[0-9A-Fa-f])*)?)?|\\.[0-9A-Fa-f](?:'?[0-9A-Fa-f])*)[Pp][+-]?[0-9](?:'?[0-9])*)(?:[Ff](?:16|32|64|128)?|(BF|bf)16|[Ll]|)"
      },
      // Integer literal.
      {
        begin: "[+-]?\\b(?:0[Bb][01](?:'?[01])*|0[Xx][0-9A-Fa-f](?:'?[0-9A-Fa-f])*|0(?:'?[0-7])*|[1-9](?:'?[0-9])*)(?:[Uu](?:LL?|ll?)|[Uu][Zz]?|(?:LL?|ll?)[Uu]?|[Zz][Uu]|)"
        // Note: there are user-defined literal suffixes too, but perhaps having the custom suffix not part of the
        // literal highlight actually makes it stand out more.
      }
    ],
    relevance: 0
  };
  const PREPROCESSOR = {
    className: "meta",
    begin: /#\s*[a-z]+\b/,
    end: /$/,
    keywords: { keyword: "if else elif endif define undef warning error line pragma _Pragma ifdef ifndef include" },
    contains: [
      {
        begin: /\\\n/,
        relevance: 0
      },
      hljs.inherit(STRINGS, { className: "string" }),
      {
        className: "string",
        begin: /<.*?>/
      },
      C_LINE_COMMENT_MODE,
      hljs.C_BLOCK_COMMENT_MODE
    ]
  };
  const TITLE_MODE = {
    className: "title",
    begin: regex.optional(NAMESPACE_RE) + hljs.IDENT_RE,
    relevance: 0
  };
  const FUNCTION_TITLE = regex.optional(NAMESPACE_RE) + hljs.IDENT_RE + "\\s*\\(";
  const RESERVED_KEYWORDS = [
    "alignas",
    "alignof",
    "and",
    "and_eq",
    "asm",
    "atomic_cancel",
    "atomic_commit",
    "atomic_noexcept",
    "auto",
    "bitand",
    "bitor",
    "break",
    "case",
    "catch",
    "class",
    "co_await",
    "co_return",
    "co_yield",
    "compl",
    "concept",
    "const_cast|10",
    "consteval",
    "constexpr",
    "constinit",
    "continue",
    "decltype",
    "default",
    "delete",
    "do",
    "dynamic_cast|10",
    "else",
    "enum",
    "explicit",
    "export",
    "extern",
    "false",
    "final",
    "for",
    "friend",
    "goto",
    "if",
    "import",
    "inline",
    "module",
    "mutable",
    "namespace",
    "new",
    "noexcept",
    "not",
    "not_eq",
    "nullptr",
    "operator",
    "or",
    "or_eq",
    "override",
    "private",
    "protected",
    "public",
    "reflexpr",
    "register",
    "reinterpret_cast|10",
    "requires",
    "return",
    "sizeof",
    "static_assert",
    "static_cast|10",
    "struct",
    "switch",
    "synchronized",
    "template",
    "this",
    "thread_local",
    "throw",
    "transaction_safe",
    "transaction_safe_dynamic",
    "true",
    "try",
    "typedef",
    "typeid",
    "typename",
    "union",
    "using",
    "virtual",
    "volatile",
    "while",
    "xor",
    "xor_eq"
  ];
  const RESERVED_TYPES = [
    "bool",
    "char",
    "char16_t",
    "char32_t",
    "char8_t",
    "double",
    "float",
    "int",
    "long",
    "short",
    "void",
    "wchar_t",
    "unsigned",
    "signed",
    "const",
    "static"
  ];
  const TYPE_HINTS = [
    "any",
    "auto_ptr",
    "barrier",
    "binary_semaphore",
    "bitset",
    "complex",
    "condition_variable",
    "condition_variable_any",
    "counting_semaphore",
    "deque",
    "false_type",
    "flat_map",
    "flat_set",
    "future",
    "imaginary",
    "initializer_list",
    "istringstream",
    "jthread",
    "latch",
    "lock_guard",
    "multimap",
    "multiset",
    "mutex",
    "optional",
    "ostringstream",
    "packaged_task",
    "pair",
    "promise",
    "priority_queue",
    "queue",
    "recursive_mutex",
    "recursive_timed_mutex",
    "scoped_lock",
    "set",
    "shared_future",
    "shared_lock",
    "shared_mutex",
    "shared_timed_mutex",
    "shared_ptr",
    "stack",
    "string_view",
    "stringstream",
    "timed_mutex",
    "thread",
    "true_type",
    "tuple",
    "unique_lock",
    "unique_ptr",
    "unordered_map",
    "unordered_multimap",
    "unordered_multiset",
    "unordered_set",
    "variant",
    "vector",
    "weak_ptr",
    "wstring",
    "wstring_view"
  ];
  const FUNCTION_HINTS = [
    "abort",
    "abs",
    "acos",
    "apply",
    "as_const",
    "asin",
    "atan",
    "atan2",
    "calloc",
    "ceil",
    "cerr",
    "cin",
    "clog",
    "cos",
    "cosh",
    "cout",
    "declval",
    "endl",
    "exchange",
    "exit",
    "exp",
    "fabs",
    "floor",
    "fmod",
    "forward",
    "fprintf",
    "fputs",
    "free",
    "frexp",
    "fscanf",
    "future",
    "invoke",
    "isalnum",
    "isalpha",
    "iscntrl",
    "isdigit",
    "isgraph",
    "islower",
    "isprint",
    "ispunct",
    "isspace",
    "isupper",
    "isxdigit",
    "labs",
    "launder",
    "ldexp",
    "log",
    "log10",
    "make_pair",
    "make_shared",
    "make_shared_for_overwrite",
    "make_tuple",
    "make_unique",
    "malloc",
    "memchr",
    "memcmp",
    "memcpy",
    "memset",
    "modf",
    "move",
    "pow",
    "printf",
    "putchar",
    "puts",
    "realloc",
    "scanf",
    "sin",
    "sinh",
    "snprintf",
    "sprintf",
    "sqrt",
    "sscanf",
    "std",
    "stderr",
    "stdin",
    "stdout",
    "strcat",
    "strchr",
    "strcmp",
    "strcpy",
    "strcspn",
    "strlen",
    "strncat",
    "strncmp",
    "strncpy",
    "strpbrk",
    "strrchr",
    "strspn",
    "strstr",
    "swap",
    "tan",
    "tanh",
    "terminate",
    "to_underlying",
    "tolower",
    "toupper",
    "vfprintf",
    "visit",
    "vprintf",
    "vsprintf"
  ];
  const LITERALS3 = [
    "NULL",
    "false",
    "nullopt",
    "nullptr",
    "true"
  ];
  const BUILT_IN = ["_Pragma"];
  const CPP_KEYWORDS = {
    type: RESERVED_TYPES,
    keyword: RESERVED_KEYWORDS,
    literal: LITERALS3,
    built_in: BUILT_IN,
    _type_hints: TYPE_HINTS
  };
  const FUNCTION_DISPATCH = {
    className: "function.dispatch",
    relevance: 0,
    keywords: {
      // Only for relevance, not highlighting.
      _hint: FUNCTION_HINTS
    },
    begin: regex.concat(
      /\b/,
      /(?!decltype)/,
      /(?!if)/,
      /(?!for)/,
      /(?!switch)/,
      /(?!while)/,
      hljs.IDENT_RE,
      regex.lookahead(/(<[^<>]+>|)\s*\(/)
    )
  };
  const EXPRESSION_CONTAINS = [
    FUNCTION_DISPATCH,
    PREPROCESSOR,
    CPP_PRIMITIVE_TYPES,
    C_LINE_COMMENT_MODE,
    hljs.C_BLOCK_COMMENT_MODE,
    NUMBERS,
    STRINGS
  ];
  const EXPRESSION_CONTEXT = {
    // This mode covers expression context where we can't expect a function
    // definition and shouldn't highlight anything that looks like one:
    // `return some()`, `else if()`, `(x*sum(1, 2))`
    variants: [
      {
        begin: /=/,
        end: /;/
      },
      {
        begin: /\(/,
        end: /\)/
      },
      {
        beginKeywords: "new throw return else",
        end: /;/
      }
    ],
    keywords: CPP_KEYWORDS,
    contains: EXPRESSION_CONTAINS.concat([
      {
        begin: /\(/,
        end: /\)/,
        keywords: CPP_KEYWORDS,
        contains: EXPRESSION_CONTAINS.concat(["self"]),
        relevance: 0
      }
    ]),
    relevance: 0
  };
  const FUNCTION_DECLARATION = {
    className: "function",
    begin: "(" + FUNCTION_TYPE_RE + "[\\*&\\s]+)+" + FUNCTION_TITLE,
    returnBegin: true,
    end: /[{;=]/,
    excludeEnd: true,
    keywords: CPP_KEYWORDS,
    illegal: /[^\w\s\*&:<>.]/,
    contains: [
      {
        // to prevent it from being confused as the function title
        begin: DECLTYPE_AUTO_RE,
        keywords: CPP_KEYWORDS,
        relevance: 0
      },
      {
        begin: FUNCTION_TITLE,
        returnBegin: true,
        contains: [TITLE_MODE],
        relevance: 0
      },
      // needed because we do not have look-behind on the below rule
      // to prevent it from grabbing the final : in a :: pair
      {
        begin: /::/,
        relevance: 0
      },
      // initializers
      {
        begin: /:/,
        endsWithParent: true,
        contains: [
          STRINGS,
          NUMBERS
        ]
      },
      // allow for multiple declarations, e.g.:
      // extern void f(int), g(char);
      {
        relevance: 0,
        match: /,/
      },
      {
        className: "params",
        begin: /\(/,
        end: /\)/,
        keywords: CPP_KEYWORDS,
        relevance: 0,
        contains: [
          C_LINE_COMMENT_MODE,
          hljs.C_BLOCK_COMMENT_MODE,
          STRINGS,
          NUMBERS,
          CPP_PRIMITIVE_TYPES,
          // Count matching parentheses.
          {
            begin: /\(/,
            end: /\)/,
            keywords: CPP_KEYWORDS,
            relevance: 0,
            contains: [
              "self",
              C_LINE_COMMENT_MODE,
              hljs.C_BLOCK_COMMENT_MODE,
              STRINGS,
              NUMBERS,
              CPP_PRIMITIVE_TYPES
            ]
          }
        ]
      },
      CPP_PRIMITIVE_TYPES,
      C_LINE_COMMENT_MODE,
      hljs.C_BLOCK_COMMENT_MODE,
      PREPROCESSOR
    ]
  };
  return {
    name: "C++",
    aliases: [
      "cc",
      "c++",
      "h++",
      "hpp",
      "hh",
      "hxx",
      "cxx"
    ],
    keywords: CPP_KEYWORDS,
    illegal: "</",
    classNameAliases: { "function.dispatch": "built_in" },
    contains: [].concat(
      EXPRESSION_CONTEXT,
      FUNCTION_DECLARATION,
      FUNCTION_DISPATCH,
      EXPRESSION_CONTAINS,
      [
        PREPROCESSOR,
        {
          // containers: ie, `vector <int> rooms (9);`
          begin: "\\b(deque|list|queue|priority_queue|pair|stack|vector|map|set|bitset|multiset|multimap|unordered_map|unordered_set|unordered_multiset|unordered_multimap|array|tuple|optional|variant|function|flat_map|flat_set)\\s*<(?!<)",
          end: ">",
          keywords: CPP_KEYWORDS,
          contains: [
            "self",
            CPP_PRIMITIVE_TYPES
          ]
        },
        {
          begin: hljs.IDENT_RE + "::",
          keywords: CPP_KEYWORDS
        },
        {
          match: [
            // extra complexity to deal with `enum class` and `enum struct`
            /\b(?:enum(?:\s+(?:class|struct))?|class|struct|union)/,
            /\s+/,
            /\w+/
          ],
          className: {
            1: "keyword",
            3: "title.class"
          }
        }
      ]
    )
  };
}

// node_modules/highlight.js/es/languages/csharp.js
function csharp(hljs) {
  const BUILT_IN_KEYWORDS = [
    "bool",
    "byte",
    "char",
    "decimal",
    "delegate",
    "double",
    "dynamic",
    "enum",
    "float",
    "int",
    "long",
    "nint",
    "nuint",
    "object",
    "sbyte",
    "short",
    "string",
    "ulong",
    "uint",
    "ushort"
  ];
  const FUNCTION_MODIFIERS = [
    "public",
    "private",
    "protected",
    "static",
    "internal",
    "protected",
    "abstract",
    "async",
    "extern",
    "override",
    "unsafe",
    "virtual",
    "new",
    "sealed",
    "partial"
  ];
  const LITERAL_KEYWORDS = [
    "default",
    "false",
    "null",
    "true"
  ];
  const NORMAL_KEYWORDS = [
    "abstract",
    "as",
    "base",
    "break",
    "case",
    "catch",
    "class",
    "const",
    "continue",
    "do",
    "else",
    "event",
    "explicit",
    "extern",
    "finally",
    "fixed",
    "for",
    "foreach",
    "goto",
    "if",
    "implicit",
    "in",
    "interface",
    "internal",
    "is",
    "lock",
    "namespace",
    "new",
    "operator",
    "out",
    "override",
    "params",
    "private",
    "protected",
    "public",
    "readonly",
    "record",
    "ref",
    "return",
    "scoped",
    "sealed",
    "sizeof",
    "stackalloc",
    "static",
    "struct",
    "switch",
    "this",
    "throw",
    "try",
    "typeof",
    "unchecked",
    "unsafe",
    "using",
    "virtual",
    "void",
    "volatile",
    "while"
  ];
  const CONTEXTUAL_KEYWORDS = [
    "add",
    "alias",
    "and",
    "ascending",
    "args",
    "async",
    "await",
    "by",
    "descending",
    "dynamic",
    "equals",
    "file",
    "from",
    "get",
    "global",
    "group",
    "init",
    "into",
    "join",
    "let",
    "nameof",
    "not",
    "notnull",
    "on",
    "or",
    "orderby",
    "partial",
    "record",
    "remove",
    "required",
    "scoped",
    "select",
    "set",
    "unmanaged",
    "value|0",
    "var",
    "when",
    "where",
    "with",
    "yield"
  ];
  const KEYWORDS3 = {
    keyword: NORMAL_KEYWORDS.concat(CONTEXTUAL_KEYWORDS),
    built_in: BUILT_IN_KEYWORDS,
    literal: LITERAL_KEYWORDS
  };
  const TITLE_MODE = hljs.inherit(hljs.TITLE_MODE, { begin: "[a-zA-Z](\\.?\\w)*" });
  const NUMBERS = {
    className: "number",
    variants: [
      { begin: "\\b(0b[01']+)" },
      { begin: "(-?)\\b([\\d']+(\\.[\\d']*)?|\\.[\\d']+)(u|U|l|L|ul|UL|f|F|b|B)" },
      { begin: "(-?)(\\b0[xX][a-fA-F0-9']+|(\\b[\\d']+(\\.[\\d']*)?|\\.[\\d']+)([eE][-+]?[\\d']+)?)" }
    ],
    relevance: 0
  };
  const RAW_STRING = {
    className: "string",
    begin: /"""("*)(?!")(.|\n)*?"""\1/,
    relevance: 1
  };
  const VERBATIM_STRING = {
    className: "string",
    begin: '@"',
    end: '"',
    contains: [{ begin: '""' }]
  };
  const VERBATIM_STRING_NO_LF = hljs.inherit(VERBATIM_STRING, { illegal: /\n/ });
  const SUBST = {
    className: "subst",
    begin: /\{/,
    end: /\}/,
    keywords: KEYWORDS3
  };
  const SUBST_NO_LF = hljs.inherit(SUBST, { illegal: /\n/ });
  const INTERPOLATED_STRING = {
    className: "string",
    begin: /\$"/,
    end: '"',
    illegal: /\n/,
    contains: [
      { begin: /\{\{/ },
      { begin: /\}\}/ },
      hljs.BACKSLASH_ESCAPE,
      SUBST_NO_LF
    ]
  };
  const INTERPOLATED_VERBATIM_STRING = {
    className: "string",
    begin: /\$@"/,
    end: '"',
    contains: [
      { begin: /\{\{/ },
      { begin: /\}\}/ },
      { begin: '""' },
      SUBST
    ]
  };
  const INTERPOLATED_VERBATIM_STRING_NO_LF = hljs.inherit(INTERPOLATED_VERBATIM_STRING, {
    illegal: /\n/,
    contains: [
      { begin: /\{\{/ },
      { begin: /\}\}/ },
      { begin: '""' },
      SUBST_NO_LF
    ]
  });
  SUBST.contains = [
    INTERPOLATED_VERBATIM_STRING,
    INTERPOLATED_STRING,
    VERBATIM_STRING,
    hljs.APOS_STRING_MODE,
    hljs.QUOTE_STRING_MODE,
    NUMBERS,
    hljs.C_BLOCK_COMMENT_MODE
  ];
  SUBST_NO_LF.contains = [
    INTERPOLATED_VERBATIM_STRING_NO_LF,
    INTERPOLATED_STRING,
    VERBATIM_STRING_NO_LF,
    hljs.APOS_STRING_MODE,
    hljs.QUOTE_STRING_MODE,
    NUMBERS,
    hljs.inherit(hljs.C_BLOCK_COMMENT_MODE, { illegal: /\n/ })
  ];
  const STRING = { variants: [
    RAW_STRING,
    INTERPOLATED_VERBATIM_STRING,
    INTERPOLATED_STRING,
    VERBATIM_STRING,
    hljs.APOS_STRING_MODE,
    hljs.QUOTE_STRING_MODE
  ] };
  const GENERIC_MODIFIER = {
    begin: "<",
    end: ">",
    contains: [
      { beginKeywords: "in out" },
      TITLE_MODE
    ]
  };
  const TYPE_IDENT_RE = hljs.IDENT_RE + "(<" + hljs.IDENT_RE + "(\\s*,\\s*" + hljs.IDENT_RE + ")*>)?(\\[\\])?";
  const AT_IDENTIFIER = {
    // prevents expressions like `@class` from incorrect flagging
    // `class` as a keyword
    begin: "@" + hljs.IDENT_RE,
    relevance: 0
  };
  return {
    name: "C#",
    aliases: [
      "cs",
      "c#"
    ],
    keywords: KEYWORDS3,
    illegal: /::/,
    contains: [
      hljs.COMMENT(
        "///",
        "$",
        {
          returnBegin: true,
          contains: [
            {
              className: "doctag",
              variants: [
                {
                  begin: "///",
                  relevance: 0
                },
                { begin: "<!--|-->" },
                {
                  begin: "</?",
                  end: ">"
                }
              ]
            }
          ]
        }
      ),
      hljs.C_LINE_COMMENT_MODE,
      hljs.C_BLOCK_COMMENT_MODE,
      {
        className: "meta",
        begin: "#",
        end: "$",
        keywords: { keyword: "if else elif endif define undef warning error line region endregion pragma checksum" }
      },
      STRING,
      NUMBERS,
      {
        beginKeywords: "class interface",
        relevance: 0,
        end: /[{;=]/,
        illegal: /[^\s:,]/,
        contains: [
          { beginKeywords: "where class" },
          TITLE_MODE,
          GENERIC_MODIFIER,
          hljs.C_LINE_COMMENT_MODE,
          hljs.C_BLOCK_COMMENT_MODE
        ]
      },
      {
        beginKeywords: "namespace",
        relevance: 0,
        end: /[{;=]/,
        illegal: /[^\s:]/,
        contains: [
          TITLE_MODE,
          hljs.C_LINE_COMMENT_MODE,
          hljs.C_BLOCK_COMMENT_MODE
        ]
      },
      {
        beginKeywords: "record",
        relevance: 0,
        end: /[{;=]/,
        illegal: /[^\s:]/,
        contains: [
          TITLE_MODE,
          GENERIC_MODIFIER,
          hljs.C_LINE_COMMENT_MODE,
          hljs.C_BLOCK_COMMENT_MODE
        ]
      },
      {
        // [Attributes("")]
        className: "meta",
        begin: "^\\s*\\[(?=[\\w])",
        excludeBegin: true,
        end: "\\]",
        excludeEnd: true,
        contains: [
          {
            className: "string",
            begin: /"/,
            end: /"/
          }
        ]
      },
      {
        // Expression keywords prevent 'keyword Name(...)' from being
        // recognized as a function definition
        beginKeywords: "new return throw await else",
        relevance: 0
      },
      {
        className: "function",
        begin: "(" + TYPE_IDENT_RE + "\\s+)+" + hljs.IDENT_RE + "\\s*(<[^=]+>\\s*)?\\(",
        returnBegin: true,
        end: /\s*[{;=]/,
        excludeEnd: true,
        keywords: KEYWORDS3,
        contains: [
          // prevents these from being highlighted `title`
          {
            beginKeywords: FUNCTION_MODIFIERS.join(" "),
            relevance: 0
          },
          {
            begin: hljs.IDENT_RE + "\\s*(<[^=]+>\\s*)?\\(",
            returnBegin: true,
            contains: [
              hljs.TITLE_MODE,
              GENERIC_MODIFIER
            ],
            relevance: 0
          },
          { match: /\(\)/ },
          {
            className: "params",
            begin: /\(/,
            end: /\)/,
            excludeBegin: true,
            excludeEnd: true,
            keywords: KEYWORDS3,
            relevance: 0,
            contains: [
              STRING,
              NUMBERS,
              hljs.C_BLOCK_COMMENT_MODE
            ]
          },
          hljs.C_LINE_COMMENT_MODE,
          hljs.C_BLOCK_COMMENT_MODE
        ]
      },
      AT_IDENTIFIER
    ]
  };
}

// node_modules/highlight.js/es/languages/css.js
var MODES = (hljs) => {
  return {
    IMPORTANT: {
      scope: "meta",
      begin: "!important"
    },
    BLOCK_COMMENT: hljs.C_BLOCK_COMMENT_MODE,
    HEXCOLOR: {
      scope: "number",
      begin: /#(([0-9a-fA-F]{3,4})|(([0-9a-fA-F]{2}){3,4}))\b/
    },
    FUNCTION_DISPATCH: {
      className: "built_in",
      begin: /[\w-]+(?=\()/
    },
    ATTRIBUTE_SELECTOR_MODE: {
      scope: "selector-attr",
      begin: /\[/,
      end: /\]/,
      illegal: "$",
      contains: [
        hljs.APOS_STRING_MODE,
        hljs.QUOTE_STRING_MODE
      ]
    },
    CSS_NUMBER_MODE: {
      scope: "number",
      begin: hljs.NUMBER_RE + "(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",
      relevance: 0
    },
    CSS_VARIABLE: {
      className: "attr",
      begin: /--[A-Za-z_][A-Za-z0-9_-]*/
    }
  };
};
var HTML_TAGS = [
  "a",
  "abbr",
  "address",
  "article",
  "aside",
  "audio",
  "b",
  "blockquote",
  "body",
  "button",
  "canvas",
  "caption",
  "cite",
  "code",
  "dd",
  "del",
  "details",
  "dfn",
  "div",
  "dl",
  "dt",
  "em",
  "fieldset",
  "figcaption",
  "figure",
  "footer",
  "form",
  "h1",
  "h2",
  "h3",
  "h4",
  "h5",
  "h6",
  "header",
  "hgroup",
  "html",
  "i",
  "iframe",
  "img",
  "input",
  "ins",
  "kbd",
  "label",
  "legend",
  "li",
  "main",
  "mark",
  "menu",
  "nav",
  "object",
  "ol",
  "optgroup",
  "option",
  "p",
  "picture",
  "q",
  "quote",
  "samp",
  "section",
  "select",
  "source",
  "span",
  "strong",
  "summary",
  "sup",
  "table",
  "tbody",
  "td",
  "textarea",
  "tfoot",
  "th",
  "thead",
  "time",
  "tr",
  "ul",
  "var",
  "video"
];
var SVG_TAGS = [
  "defs",
  "g",
  "marker",
  "mask",
  "pattern",
  "svg",
  "switch",
  "symbol",
  "feBlend",
  "feColorMatrix",
  "feComponentTransfer",
  "feComposite",
  "feConvolveMatrix",
  "feDiffuseLighting",
  "feDisplacementMap",
  "feFlood",
  "feGaussianBlur",
  "feImage",
  "feMerge",
  "feMorphology",
  "feOffset",
  "feSpecularLighting",
  "feTile",
  "feTurbulence",
  "linearGradient",
  "radialGradient",
  "stop",
  "circle",
  "ellipse",
  "image",
  "line",
  "path",
  "polygon",
  "polyline",
  "rect",
  "text",
  "use",
  "textPath",
  "tspan",
  "foreignObject",
  "clipPath"
];
var TAGS = [
  ...HTML_TAGS,
  ...SVG_TAGS
];
var MEDIA_FEATURES = [
  "any-hover",
  "any-pointer",
  "aspect-ratio",
  "color",
  "color-gamut",
  "color-index",
  "device-aspect-ratio",
  "device-height",
  "device-width",
  "display-mode",
  "forced-colors",
  "grid",
  "height",
  "hover",
  "inverted-colors",
  "monochrome",
  "orientation",
  "overflow-block",
  "overflow-inline",
  "pointer",
  "prefers-color-scheme",
  "prefers-contrast",
  "prefers-reduced-motion",
  "prefers-reduced-transparency",
  "resolution",
  "scan",
  "scripting",
  "update",
  "width",
  // TODO: find a better solution?
  "min-width",
  "max-width",
  "min-height",
  "max-height"
].sort().reverse();
var PSEUDO_CLASSES = [
  "active",
  "any-link",
  "blank",
  "checked",
  "current",
  "default",
  "defined",
  "dir",
  // dir()
  "disabled",
  "drop",
  "empty",
  "enabled",
  "first",
  "first-child",
  "first-of-type",
  "fullscreen",
  "future",
  "focus",
  "focus-visible",
  "focus-within",
  "has",
  // has()
  "host",
  // host or host()
  "host-context",
  // host-context()
  "hover",
  "indeterminate",
  "in-range",
  "invalid",
  "is",
  // is()
  "lang",
  // lang()
  "last-child",
  "last-of-type",
  "left",
  "link",
  "local-link",
  "not",
  // not()
  "nth-child",
  // nth-child()
  "nth-col",
  // nth-col()
  "nth-last-child",
  // nth-last-child()
  "nth-last-col",
  // nth-last-col()
  "nth-last-of-type",
  //nth-last-of-type()
  "nth-of-type",
  //nth-of-type()
  "only-child",
  "only-of-type",
  "optional",
  "out-of-range",
  "past",
  "placeholder-shown",
  "read-only",
  "read-write",
  "required",
  "right",
  "root",
  "scope",
  "target",
  "target-within",
  "user-invalid",
  "valid",
  "visited",
  "where"
  // where()
].sort().reverse();
var PSEUDO_ELEMENTS = [
  "after",
  "backdrop",
  "before",
  "cue",
  "cue-region",
  "first-letter",
  "first-line",
  "grammar-error",
  "marker",
  "part",
  "placeholder",
  "selection",
  "slotted",
  "spelling-error"
].sort().reverse();
var ATTRIBUTES = [
  "accent-color",
  "align-content",
  "align-items",
  "align-self",
  "alignment-baseline",
  "all",
  "anchor-name",
  "animation",
  "animation-composition",
  "animation-delay",
  "animation-direction",
  "animation-duration",
  "animation-fill-mode",
  "animation-iteration-count",
  "animation-name",
  "animation-play-state",
  "animation-range",
  "animation-range-end",
  "animation-range-start",
  "animation-timeline",
  "animation-timing-function",
  "appearance",
  "aspect-ratio",
  "backdrop-filter",
  "backface-visibility",
  "background",
  "background-attachment",
  "background-blend-mode",
  "background-clip",
  "background-color",
  "background-image",
  "background-origin",
  "background-position",
  "background-position-x",
  "background-position-y",
  "background-repeat",
  "background-size",
  "baseline-shift",
  "block-size",
  "border",
  "border-block",
  "border-block-color",
  "border-block-end",
  "border-block-end-color",
  "border-block-end-style",
  "border-block-end-width",
  "border-block-start",
  "border-block-start-color",
  "border-block-start-style",
  "border-block-start-width",
  "border-block-style",
  "border-block-width",
  "border-bottom",
  "border-bottom-color",
  "border-bottom-left-radius",
  "border-bottom-right-radius",
  "border-bottom-style",
  "border-bottom-width",
  "border-collapse",
  "border-color",
  "border-end-end-radius",
  "border-end-start-radius",
  "border-image",
  "border-image-outset",
  "border-image-repeat",
  "border-image-slice",
  "border-image-source",
  "border-image-width",
  "border-inline",
  "border-inline-color",
  "border-inline-end",
  "border-inline-end-color",
  "border-inline-end-style",
  "border-inline-end-width",
  "border-inline-start",
  "border-inline-start-color",
  "border-inline-start-style",
  "border-inline-start-width",
  "border-inline-style",
  "border-inline-width",
  "border-left",
  "border-left-color",
  "border-left-style",
  "border-left-width",
  "border-radius",
  "border-right",
  "border-right-color",
  "border-right-style",
  "border-right-width",
  "border-spacing",
  "border-start-end-radius",
  "border-start-start-radius",
  "border-style",
  "border-top",
  "border-top-color",
  "border-top-left-radius",
  "border-top-right-radius",
  "border-top-style",
  "border-top-width",
  "border-width",
  "bottom",
  "box-align",
  "box-decoration-break",
  "box-direction",
  "box-flex",
  "box-flex-group",
  "box-lines",
  "box-ordinal-group",
  "box-orient",
  "box-pack",
  "box-shadow",
  "box-sizing",
  "break-after",
  "break-before",
  "break-inside",
  "caption-side",
  "caret-color",
  "clear",
  "clip",
  "clip-path",
  "clip-rule",
  "color",
  "color-interpolation",
  "color-interpolation-filters",
  "color-profile",
  "color-rendering",
  "color-scheme",
  "column-count",
  "column-fill",
  "column-gap",
  "column-rule",
  "column-rule-color",
  "column-rule-style",
  "column-rule-width",
  "column-span",
  "column-width",
  "columns",
  "contain",
  "contain-intrinsic-block-size",
  "contain-intrinsic-height",
  "contain-intrinsic-inline-size",
  "contain-intrinsic-size",
  "contain-intrinsic-width",
  "container",
  "container-name",
  "container-type",
  "content",
  "content-visibility",
  "counter-increment",
  "counter-reset",
  "counter-set",
  "cue",
  "cue-after",
  "cue-before",
  "cursor",
  "cx",
  "cy",
  "direction",
  "display",
  "dominant-baseline",
  "empty-cells",
  "enable-background",
  "field-sizing",
  "fill",
  "fill-opacity",
  "fill-rule",
  "filter",
  "flex",
  "flex-basis",
  "flex-direction",
  "flex-flow",
  "flex-grow",
  "flex-shrink",
  "flex-wrap",
  "float",
  "flood-color",
  "flood-opacity",
  "flow",
  "font",
  "font-display",
  "font-family",
  "font-feature-settings",
  "font-kerning",
  "font-language-override",
  "font-optical-sizing",
  "font-palette",
  "font-size",
  "font-size-adjust",
  "font-smooth",
  "font-smoothing",
  "font-stretch",
  "font-style",
  "font-synthesis",
  "font-synthesis-position",
  "font-synthesis-small-caps",
  "font-synthesis-style",
  "font-synthesis-weight",
  "font-variant",
  "font-variant-alternates",
  "font-variant-caps",
  "font-variant-east-asian",
  "font-variant-emoji",
  "font-variant-ligatures",
  "font-variant-numeric",
  "font-variant-position",
  "font-variation-settings",
  "font-weight",
  "forced-color-adjust",
  "gap",
  "glyph-orientation-horizontal",
  "glyph-orientation-vertical",
  "grid",
  "grid-area",
  "grid-auto-columns",
  "grid-auto-flow",
  "grid-auto-rows",
  "grid-column",
  "grid-column-end",
  "grid-column-start",
  "grid-gap",
  "grid-row",
  "grid-row-end",
  "grid-row-start",
  "grid-template",
  "grid-template-areas",
  "grid-template-columns",
  "grid-template-rows",
  "hanging-punctuation",
  "height",
  "hyphenate-character",
  "hyphenate-limit-chars",
  "hyphens",
  "icon",
  "image-orientation",
  "image-rendering",
  "image-resolution",
  "ime-mode",
  "initial-letter",
  "initial-letter-align",
  "inline-size",
  "inset",
  "inset-area",
  "inset-block",
  "inset-block-end",
  "inset-block-start",
  "inset-inline",
  "inset-inline-end",
  "inset-inline-start",
  "isolation",
  "justify-content",
  "justify-items",
  "justify-self",
  "kerning",
  "left",
  "letter-spacing",
  "lighting-color",
  "line-break",
  "line-height",
  "line-height-step",
  "list-style",
  "list-style-image",
  "list-style-position",
  "list-style-type",
  "margin",
  "margin-block",
  "margin-block-end",
  "margin-block-start",
  "margin-bottom",
  "margin-inline",
  "margin-inline-end",
  "margin-inline-start",
  "margin-left",
  "margin-right",
  "margin-top",
  "margin-trim",
  "marker",
  "marker-end",
  "marker-mid",
  "marker-start",
  "marks",
  "mask",
  "mask-border",
  "mask-border-mode",
  "mask-border-outset",
  "mask-border-repeat",
  "mask-border-slice",
  "mask-border-source",
  "mask-border-width",
  "mask-clip",
  "mask-composite",
  "mask-image",
  "mask-mode",
  "mask-origin",
  "mask-position",
  "mask-repeat",
  "mask-size",
  "mask-type",
  "masonry-auto-flow",
  "math-depth",
  "math-shift",
  "math-style",
  "max-block-size",
  "max-height",
  "max-inline-size",
  "max-width",
  "min-block-size",
  "min-height",
  "min-inline-size",
  "min-width",
  "mix-blend-mode",
  "nav-down",
  "nav-index",
  "nav-left",
  "nav-right",
  "nav-up",
  "none",
  "normal",
  "object-fit",
  "object-position",
  "offset",
  "offset-anchor",
  "offset-distance",
  "offset-path",
  "offset-position",
  "offset-rotate",
  "opacity",
  "order",
  "orphans",
  "outline",
  "outline-color",
  "outline-offset",
  "outline-style",
  "outline-width",
  "overflow",
  "overflow-anchor",
  "overflow-block",
  "overflow-clip-margin",
  "overflow-inline",
  "overflow-wrap",
  "overflow-x",
  "overflow-y",
  "overlay",
  "overscroll-behavior",
  "overscroll-behavior-block",
  "overscroll-behavior-inline",
  "overscroll-behavior-x",
  "overscroll-behavior-y",
  "padding",
  "padding-block",
  "padding-block-end",
  "padding-block-start",
  "padding-bottom",
  "padding-inline",
  "padding-inline-end",
  "padding-inline-start",
  "padding-left",
  "padding-right",
  "padding-top",
  "page",
  "page-break-after",
  "page-break-before",
  "page-break-inside",
  "paint-order",
  "pause",
  "pause-after",
  "pause-before",
  "perspective",
  "perspective-origin",
  "place-content",
  "place-items",
  "place-self",
  "pointer-events",
  "position",
  "position-anchor",
  "position-visibility",
  "print-color-adjust",
  "quotes",
  "r",
  "resize",
  "rest",
  "rest-after",
  "rest-before",
  "right",
  "rotate",
  "row-gap",
  "ruby-align",
  "ruby-position",
  "scale",
  "scroll-behavior",
  "scroll-margin",
  "scroll-margin-block",
  "scroll-margin-block-end",
  "scroll-margin-block-start",
  "scroll-margin-bottom",
  "scroll-margin-inline",
  "scroll-margin-inline-end",
  "scroll-margin-inline-start",
  "scroll-margin-left",
  "scroll-margin-right",
  "scroll-margin-top",
  "scroll-padding",
  "scroll-padding-block",
  "scroll-padding-block-end",
  "scroll-padding-block-start",
  "scroll-padding-bottom",
  "scroll-padding-inline",
  "scroll-padding-inline-end",
  "scroll-padding-inline-start",
  "scroll-padding-left",
  "scroll-padding-right",
  "scroll-padding-top",
  "scroll-snap-align",
  "scroll-snap-stop",
  "scroll-snap-type",
  "scroll-timeline",
  "scroll-timeline-axis",
  "scroll-timeline-name",
  "scrollbar-color",
  "scrollbar-gutter",
  "scrollbar-width",
  "shape-image-threshold",
  "shape-margin",
  "shape-outside",
  "shape-rendering",
  "speak",
  "speak-as",
  "src",
  // @font-face
  "stop-color",
  "stop-opacity",
  "stroke",
  "stroke-dasharray",
  "stroke-dashoffset",
  "stroke-linecap",
  "stroke-linejoin",
  "stroke-miterlimit",
  "stroke-opacity",
  "stroke-width",
  "tab-size",
  "table-layout",
  "text-align",
  "text-align-all",
  "text-align-last",
  "text-anchor",
  "text-combine-upright",
  "text-decoration",
  "text-decoration-color",
  "text-decoration-line",
  "text-decoration-skip",
  "text-decoration-skip-ink",
  "text-decoration-style",
  "text-decoration-thickness",
  "text-emphasis",
  "text-emphasis-color",
  "text-emphasis-position",
  "text-emphasis-style",
  "text-indent",
  "text-justify",
  "text-orientation",
  "text-overflow",
  "text-rendering",
  "text-shadow",
  "text-size-adjust",
  "text-transform",
  "text-underline-offset",
  "text-underline-position",
  "text-wrap",
  "text-wrap-mode",
  "text-wrap-style",
  "timeline-scope",
  "top",
  "touch-action",
  "transform",
  "transform-box",
  "transform-origin",
  "transform-style",
  "transition",
  "transition-behavior",
  "transition-delay",
  "transition-duration",
  "transition-property",
  "transition-timing-function",
  "translate",
  "unicode-bidi",
  "user-modify",
  "user-select",
  "vector-effect",
  "vertical-align",
  "view-timeline",
  "view-timeline-axis",
  "view-timeline-inset",
  "view-timeline-name",
  "view-transition-name",
  "visibility",
  "voice-balance",
  "voice-duration",
  "voice-family",
  "voice-pitch",
  "voice-range",
  "voice-rate",
  "voice-stress",
  "voice-volume",
  "white-space",
  "white-space-collapse",
  "widows",
  "width",
  "will-change",
  "word-break",
  "word-spacing",
  "word-wrap",
  "writing-mode",
  "x",
  "y",
  "z-index",
  "zoom"
].sort().reverse();
function css(hljs) {
  const regex = hljs.regex;
  const modes = MODES(hljs);
  const VENDOR_PREFIX = { begin: /-(webkit|moz|ms|o)-(?=[a-z])/ };
  const AT_MODIFIERS = "and or not only";
  const AT_PROPERTY_RE = /@-?\w[\w]*(-\w+)*/;
  const IDENT_RE3 = "[a-zA-Z-][a-zA-Z0-9_-]*";
  const STRINGS = [
    hljs.APOS_STRING_MODE,
    hljs.QUOTE_STRING_MODE
  ];
  return {
    name: "CSS",
    case_insensitive: true,
    illegal: /[=|'\$]/,
    keywords: { keyframePosition: "from to" },
    classNameAliases: {
      // for visual continuity with `tag {}` and because we
      // don't have a great class for this?
      keyframePosition: "selector-tag"
    },
    contains: [
      modes.BLOCK_COMMENT,
      VENDOR_PREFIX,
      // to recognize keyframe 40% etc which are outside the scope of our
      // attribute value mode
      modes.CSS_NUMBER_MODE,
      {
        className: "selector-id",
        begin: /#[A-Za-z0-9_-]+/,
        relevance: 0
      },
      {
        className: "selector-class",
        begin: "\\." + IDENT_RE3,
        relevance: 0
      },
      modes.ATTRIBUTE_SELECTOR_MODE,
      {
        className: "selector-pseudo",
        variants: [
          { begin: ":(" + PSEUDO_CLASSES.join("|") + ")" },
          { begin: ":(:)?(" + PSEUDO_ELEMENTS.join("|") + ")" }
        ]
      },
      // we may actually need this (12/2020)
      // { // pseudo-selector params
      //   begin: /\(/,
      //   end: /\)/,
      //   contains: [ hljs.CSS_NUMBER_MODE ]
      // },
      modes.CSS_VARIABLE,
      {
        className: "attribute",
        begin: "\\b(" + ATTRIBUTES.join("|") + ")\\b"
      },
      // attribute values
      {
        begin: /:/,
        end: /[;}{]/,
        contains: [
          modes.BLOCK_COMMENT,
          modes.HEXCOLOR,
          modes.IMPORTANT,
          modes.CSS_NUMBER_MODE,
          ...STRINGS,
          // needed to highlight these as strings and to avoid issues with
          // illegal characters that might be inside urls that would tigger the
          // languages illegal stack
          {
            begin: /(url|data-uri)\(/,
            end: /\)/,
            relevance: 0,
            // from keywords
            keywords: { built_in: "url data-uri" },
            contains: [
              ...STRINGS,
              {
                className: "string",
                // any character other than `)` as in `url()` will be the start
                // of a string, which ends with `)` (from the parent mode)
                begin: /[^)]/,
                endsWithParent: true,
                excludeEnd: true
              }
            ]
          },
          modes.FUNCTION_DISPATCH
        ]
      },
      {
        begin: regex.lookahead(/@/),
        end: "[{;]",
        relevance: 0,
        illegal: /:/,
        // break on Less variables @var: ...
        contains: [
          {
            className: "keyword",
            begin: AT_PROPERTY_RE
          },
          {
            begin: /\s/,
            endsWithParent: true,
            excludeEnd: true,
            relevance: 0,
            keywords: {
              $pattern: /[a-z-]+/,
              keyword: AT_MODIFIERS,
              attribute: MEDIA_FEATURES.join(" ")
            },
            contains: [
              {
                begin: /[a-z-]+(?=:)/,
                className: "attribute"
              },
              ...STRINGS,
              modes.CSS_NUMBER_MODE
            ]
          }
        ]
      },
      {
        className: "selector-tag",
        begin: "\\b(" + TAGS.join("|") + ")\\b"
      }
    ]
  };
}

// node_modules/highlight.js/es/languages/diff.js
function diff(hljs) {
  const regex = hljs.regex;
  return {
    name: "Diff",
    aliases: ["patch"],
    contains: [
      {
        className: "meta",
        relevance: 10,
        match: regex.either(
          /^@@ +-\d+,\d+ +\+\d+,\d+ +@@/,
          /^\*\*\* +\d+,\d+ +\*\*\*\*$/,
          /^--- +\d+,\d+ +----$/
        )
      },
      {
        className: "comment",
        variants: [
          {
            begin: regex.either(
              /Index: /,
              /^index/,
              /={3,}/,
              /^-{3}/,
              /^\*{3} /,
              /^\+{3}/,
              /^diff --git/
            ),
            end: /$/
          },
          { match: /^\*{15}$/ }
        ]
      },
      {
        className: "addition",
        begin: /^\+/,
        end: /$/
      },
      {
        className: "deletion",
        begin: /^-/,
        end: /$/
      },
      {
        className: "addition",
        begin: /^!/,
        end: /$/
      }
    ]
  };
}

// node_modules/highlight.js/es/languages/go.js
function go(hljs) {
  const LITERALS3 = [
    "true",
    "false",
    "iota",
    "nil"
  ];
  const BUILT_INS3 = [
    "append",
    "cap",
    "close",
    "complex",
    "copy",
    "imag",
    "len",
    "make",
    "new",
    "panic",
    "print",
    "println",
    "real",
    "recover",
    "delete"
  ];
  const TYPES3 = [
    "bool",
    "byte",
    "complex64",
    "complex128",
    "error",
    "float32",
    "float64",
    "int8",
    "int16",
    "int32",
    "int64",
    "string",
    "uint8",
    "uint16",
    "uint32",
    "uint64",
    "int",
    "uint",
    "uintptr",
    "rune"
  ];
  const KWS = [
    "break",
    "case",
    "chan",
    "const",
    "continue",
    "default",
    "defer",
    "else",
    "fallthrough",
    "for",
    "func",
    "go",
    "goto",
    "if",
    "import",
    "interface",
    "map",
    "package",
    "range",
    "return",
    "select",
    "struct",
    "switch",
    "type",
    "var"
  ];
  const KEYWORDS3 = {
    keyword: KWS,
    type: TYPES3,
    literal: LITERALS3,
    built_in: BUILT_INS3
  };
  return {
    name: "Go",
    aliases: ["golang"],
    keywords: KEYWORDS3,
    illegal: "</",
    contains: [
      hljs.C_LINE_COMMENT_MODE,
      hljs.C_BLOCK_COMMENT_MODE,
      {
        className: "string",
        variants: [
          hljs.QUOTE_STRING_MODE,
          hljs.APOS_STRING_MODE,
          {
            begin: "`",
            end: "`"
          }
        ]
      },
      {
        className: "number",
        variants: [
          {
            match: /-?\b0[xX]\.[a-fA-F0-9](_?[a-fA-F0-9])*[pP][+-]?\d(_?\d)*i?/,
            // hex without a present digit before . (making a digit afterwards required)
            relevance: 0
          },
          {
            match: /-?\b0[xX](_?[a-fA-F0-9])+((\.([a-fA-F0-9](_?[a-fA-F0-9])*)?)?[pP][+-]?\d(_?\d)*)?i?/,
            // hex with a present digit before . (making a digit afterwards optional)
            relevance: 0
          },
          {
            match: /-?\b0[oO](_?[0-7])*i?/,
            // leading 0o octal
            relevance: 0
          },
          {
            match: /-?\.\d(_?\d)*([eE][+-]?\d(_?\d)*)?i?/,
            // decimal without a present digit before . (making a digit afterwards required)
            relevance: 0
          },
          {
            match: /-?\b\d(_?\d)*(\.(\d(_?\d)*)?)?([eE][+-]?\d(_?\d)*)?i?/,
            // decimal with a present digit before . (making a digit afterwards optional)
            relevance: 0
          }
        ]
      },
      {
        begin: /:=/
        // relevance booster
      },
      {
        className: "function",
        beginKeywords: "func",
        end: "\\s*(\\{|$)",
        excludeEnd: true,
        contains: [
          hljs.TITLE_MODE,
          {
            className: "params",
            begin: /\(/,
            end: /\)/,
            endsParent: true,
            keywords: KEYWORDS3,
            illegal: /["']/
          }
        ]
      }
    ]
  };
}

// node_modules/highlight.js/es/languages/graphql.js
function graphql(hljs) {
  const regex = hljs.regex;
  const GQL_NAME = /[_A-Za-z][_0-9A-Za-z]*/;
  return {
    name: "GraphQL",
    aliases: ["gql"],
    case_insensitive: true,
    disableAutodetect: false,
    keywords: {
      keyword: [
        "query",
        "mutation",
        "subscription",
        "type",
        "input",
        "schema",
        "directive",
        "interface",
        "union",
        "scalar",
        "fragment",
        "enum",
        "on"
      ],
      literal: [
        "true",
        "false",
        "null"
      ]
    },
    contains: [
      hljs.HASH_COMMENT_MODE,
      hljs.QUOTE_STRING_MODE,
      hljs.NUMBER_MODE,
      {
        scope: "punctuation",
        match: /[.]{3}/,
        relevance: 0
      },
      {
        scope: "punctuation",
        begin: /[\!\(\)\:\=\[\]\{\|\}]{1}/,
        relevance: 0
      },
      {
        scope: "variable",
        begin: /\$/,
        end: /\W/,
        excludeEnd: true,
        relevance: 0
      },
      {
        scope: "meta",
        match: /@\w+/,
        excludeEnd: true
      },
      {
        scope: "symbol",
        begin: regex.concat(GQL_NAME, regex.lookahead(/\s*:/)),
        relevance: 0
      }
    ],
    illegal: [
      /[;<']/,
      /BEGIN/
    ]
  };
}

// node_modules/highlight.js/es/languages/ini.js
function ini(hljs) {
  const regex = hljs.regex;
  const NUMBERS = {
    className: "number",
    relevance: 0,
    variants: [
      { begin: /([+-]+)?[\d]+_[\d_]+/ },
      { begin: hljs.NUMBER_RE }
    ]
  };
  const COMMENTS = hljs.COMMENT();
  COMMENTS.variants = [
    {
      begin: /;/,
      end: /$/
    },
    {
      begin: /#/,
      end: /$/
    }
  ];
  const VARIABLES = {
    className: "variable",
    variants: [
      { begin: /\$[\w\d"][\w\d_]*/ },
      { begin: /\$\{(.*?)\}/ }
    ]
  };
  const LITERALS3 = {
    className: "literal",
    begin: /\bon|off|true|false|yes|no\b/
  };
  const STRINGS = {
    className: "string",
    contains: [hljs.BACKSLASH_ESCAPE],
    variants: [
      {
        begin: "'''",
        end: "'''",
        relevance: 10
      },
      {
        begin: '"""',
        end: '"""',
        relevance: 10
      },
      {
        begin: '"',
        end: '"'
      },
      {
        begin: "'",
        end: "'"
      }
    ]
  };
  const ARRAY = {
    begin: /\[/,
    end: /\]/,
    contains: [
      COMMENTS,
      LITERALS3,
      VARIABLES,
      STRINGS,
      NUMBERS,
      "self"
    ],
    relevance: 0
  };
  const BARE_KEY = /[A-Za-z0-9_-]+/;
  const QUOTED_KEY_DOUBLE_QUOTE = /"(\\"|[^"])*"/;
  const QUOTED_KEY_SINGLE_QUOTE = /'[^']*'/;
  const ANY_KEY = regex.either(
    BARE_KEY,
    QUOTED_KEY_DOUBLE_QUOTE,
    QUOTED_KEY_SINGLE_QUOTE
  );
  const DOTTED_KEY = regex.concat(
    ANY_KEY,
    "(\\s*\\.\\s*",
    ANY_KEY,
    ")*",
    regex.lookahead(/\s*=\s*[^#\s]/)
  );
  return {
    name: "TOML, also INI",
    aliases: ["toml"],
    case_insensitive: true,
    illegal: /\S/,
    contains: [
      COMMENTS,
      {
        className: "section",
        begin: /\[+/,
        end: /\]+/
      },
      {
        begin: DOTTED_KEY,
        className: "attr",
        starts: {
          end: /$/,
          contains: [
            COMMENTS,
            ARRAY,
            LITERALS3,
            VARIABLES,
            STRINGS,
            NUMBERS
          ]
        }
      }
    ]
  };
}

// node_modules/highlight.js/es/languages/java.js
var decimalDigits = "[0-9](_*[0-9])*";
var frac = `\\.(${decimalDigits})`;
var hexDigits = "[0-9a-fA-F](_*[0-9a-fA-F])*";
var NUMERIC = {
  className: "number",
  variants: [
    // DecimalFloatingPointLiteral
    // including ExponentPart
    { begin: `(\\b(${decimalDigits})((${frac})|\\.)?|(${frac}))[eE][+-]?(${decimalDigits})[fFdD]?\\b` },
    // excluding ExponentPart
    { begin: `\\b(${decimalDigits})((${frac})[fFdD]?\\b|\\.([fFdD]\\b)?)` },
    { begin: `(${frac})[fFdD]?\\b` },
    { begin: `\\b(${decimalDigits})[fFdD]\\b` },
    // HexadecimalFloatingPointLiteral
    { begin: `\\b0[xX]((${hexDigits})\\.?|(${hexDigits})?\\.(${hexDigits}))[pP][+-]?(${decimalDigits})[fFdD]?\\b` },
    // DecimalIntegerLiteral
    { begin: "\\b(0|[1-9](_*[0-9])*)[lL]?\\b" },
    // HexIntegerLiteral
    { begin: `\\b0[xX](${hexDigits})[lL]?\\b` },
    // OctalIntegerLiteral
    { begin: "\\b0(_*[0-7])*[lL]?\\b" },
    // BinaryIntegerLiteral
    { begin: "\\b0[bB][01](_*[01])*[lL]?\\b" }
  ],
  relevance: 0
};
function recurRegex(re, substitution, depth) {
  if (depth === -1) return "";
  return re.replace(substitution, (_) => {
    return recurRegex(re, substitution, depth - 1);
  });
}
function java(hljs) {
  const regex = hljs.regex;
  const JAVA_IDENT_RE = "[\xC0-\u02B8a-zA-Z_$][\xC0-\u02B8a-zA-Z_$0-9]*";
  const GENERIC_IDENT_RE = JAVA_IDENT_RE + recurRegex("(?:<" + JAVA_IDENT_RE + "~~~(?:\\s*,\\s*" + JAVA_IDENT_RE + "~~~)*>)?", /~~~/g, 2);
  const MAIN_KEYWORDS = [
    "synchronized",
    "abstract",
    "private",
    "var",
    "static",
    "if",
    "const ",
    "for",
    "while",
    "strictfp",
    "finally",
    "protected",
    "import",
    "native",
    "final",
    "void",
    "enum",
    "else",
    "break",
    "transient",
    "catch",
    "instanceof",
    "volatile",
    "case",
    "assert",
    "package",
    "default",
    "public",
    "try",
    "switch",
    "continue",
    "throws",
    "protected",
    "public",
    "private",
    "module",
    "requires",
    "exports",
    "do",
    "sealed",
    "yield",
    "permits",
    "goto",
    "when"
  ];
  const BUILT_INS3 = [
    "super",
    "this"
  ];
  const LITERALS3 = [
    "false",
    "true",
    "null"
  ];
  const TYPES3 = [
    "char",
    "boolean",
    "long",
    "float",
    "int",
    "byte",
    "short",
    "double"
  ];
  const KEYWORDS3 = {
    keyword: MAIN_KEYWORDS,
    literal: LITERALS3,
    type: TYPES3,
    built_in: BUILT_INS3
  };
  const ANNOTATION = {
    className: "meta",
    begin: "@" + JAVA_IDENT_RE,
    contains: [
      {
        begin: /\(/,
        end: /\)/,
        contains: ["self"]
        // allow nested () inside our annotation
      }
    ]
  };
  const PARAMS = {
    className: "params",
    begin: /\(/,
    end: /\)/,
    keywords: KEYWORDS3,
    relevance: 0,
    contains: [hljs.C_BLOCK_COMMENT_MODE],
    endsParent: true
  };
  return {
    name: "Java",
    aliases: ["jsp"],
    keywords: KEYWORDS3,
    illegal: /<\/|#/,
    contains: [
      hljs.COMMENT(
        "/\\*\\*",
        "\\*/",
        {
          relevance: 0,
          contains: [
            {
              // eat up @'s in emails to prevent them to be recognized as doctags
              begin: /\w+@/,
              relevance: 0
            },
            {
              className: "doctag",
              begin: "@[A-Za-z]+"
            }
          ]
        }
      ),
      // relevance boost
      {
        begin: /import java\.[a-z]+\./,
        keywords: "import",
        relevance: 2
      },
      hljs.C_LINE_COMMENT_MODE,
      hljs.C_BLOCK_COMMENT_MODE,
      {
        begin: /"""/,
        end: /"""/,
        className: "string",
        contains: [hljs.BACKSLASH_ESCAPE]
      },
      hljs.APOS_STRING_MODE,
      hljs.QUOTE_STRING_MODE,
      {
        match: [
          /\b(?:class|interface|enum|extends|implements|new)/,
          /\s+/,
          JAVA_IDENT_RE
        ],
        className: {
          1: "keyword",
          3: "title.class"
        }
      },
      {
        // Exceptions for hyphenated keywords
        match: /non-sealed/,
        scope: "keyword"
      },
      {
        begin: [
          regex.concat(/(?!else)/, JAVA_IDENT_RE),
          /\s+/,
          JAVA_IDENT_RE,
          /\s+/,
          /=(?!=)/
        ],
        className: {
          1: "type",
          3: "variable",
          5: "operator"
        }
      },
      {
        begin: [
          /record/,
          /\s+/,
          JAVA_IDENT_RE
        ],
        className: {
          1: "keyword",
          3: "title.class"
        },
        contains: [
          PARAMS,
          hljs.C_LINE_COMMENT_MODE,
          hljs.C_BLOCK_COMMENT_MODE
        ]
      },
      {
        // Expression keywords prevent 'keyword Name(...)' from being
        // recognized as a function definition
        beginKeywords: "new throw return else",
        relevance: 0
      },
      {
        begin: [
          "(?:" + GENERIC_IDENT_RE + "\\s+)",
          hljs.UNDERSCORE_IDENT_RE,
          /\s*(?=\()/
        ],
        className: { 2: "title.function" },
        keywords: KEYWORDS3,
        contains: [
          {
            className: "params",
            begin: /\(/,
            end: /\)/,
            keywords: KEYWORDS3,
            relevance: 0,
            contains: [
              ANNOTATION,
              hljs.APOS_STRING_MODE,
              hljs.QUOTE_STRING_MODE,
              NUMERIC,
              hljs.C_BLOCK_COMMENT_MODE
            ]
          },
          hljs.C_LINE_COMMENT_MODE,
          hljs.C_BLOCK_COMMENT_MODE
        ]
      },
      NUMERIC,
      ANNOTATION
    ]
  };
}

// node_modules/highlight.js/es/languages/javascript.js
var IDENT_RE = "[A-Za-z$_][0-9A-Za-z$_]*";
var KEYWORDS = [
  "as",
  // for exports
  "in",
  "of",
  "if",
  "for",
  "while",
  "finally",
  "var",
  "new",
  "function",
  "do",
  "return",
  "void",
  "else",
  "break",
  "catch",
  "instanceof",
  "with",
  "throw",
  "case",
  "default",
  "try",
  "switch",
  "continue",
  "typeof",
  "delete",
  "let",
  "yield",
  "const",
  "class",
  // JS handles these with a special rule
  // "get",
  // "set",
  "debugger",
  "async",
  "await",
  "static",
  "import",
  "from",
  "export",
  "extends",
  // It's reached stage 3, which is "recommended for implementation":
  "using"
];
var LITERALS = [
  "true",
  "false",
  "null",
  "undefined",
  "NaN",
  "Infinity"
];
var TYPES = [
  // Fundamental objects
  "Object",
  "Function",
  "Boolean",
  "Symbol",
  // numbers and dates
  "Math",
  "Date",
  "Number",
  "BigInt",
  // text
  "String",
  "RegExp",
  // Indexed collections
  "Array",
  "Float32Array",
  "Float64Array",
  "Int8Array",
  "Uint8Array",
  "Uint8ClampedArray",
  "Int16Array",
  "Int32Array",
  "Uint16Array",
  "Uint32Array",
  "BigInt64Array",
  "BigUint64Array",
  // Keyed collections
  "Set",
  "Map",
  "WeakSet",
  "WeakMap",
  // Structured data
  "ArrayBuffer",
  "SharedArrayBuffer",
  "Atomics",
  "DataView",
  "JSON",
  // Control abstraction objects
  "Promise",
  "Generator",
  "GeneratorFunction",
  "AsyncFunction",
  // Reflection
  "Reflect",
  "Proxy",
  // Internationalization
  "Intl",
  // WebAssembly
  "WebAssembly"
];
var ERROR_TYPES = [
  "Error",
  "EvalError",
  "InternalError",
  "RangeError",
  "ReferenceError",
  "SyntaxError",
  "TypeError",
  "URIError"
];
var BUILT_IN_GLOBALS = [
  "setInterval",
  "setTimeout",
  "clearInterval",
  "clearTimeout",
  "require",
  "exports",
  "eval",
  "isFinite",
  "isNaN",
  "parseFloat",
  "parseInt",
  "decodeURI",
  "decodeURIComponent",
  "encodeURI",
  "encodeURIComponent",
  "escape",
  "unescape"
];
var BUILT_IN_VARIABLES = [
  "arguments",
  "this",
  "super",
  "console",
  "window",
  "document",
  "localStorage",
  "sessionStorage",
  "module",
  "global"
  // Node.js
];
var BUILT_INS = [].concat(
  BUILT_IN_GLOBALS,
  TYPES,
  ERROR_TYPES
);
function javascript(hljs) {
  const regex = hljs.regex;
  const hasClosingTag = (match, { after }) => {
    const tag = "</" + match[0].slice(1);
    const pos = match.input.indexOf(tag, after);
    return pos !== -1;
  };
  const IDENT_RE$1 = IDENT_RE;
  const FRAGMENT = {
    begin: "<>",
    end: "</>"
  };
  const XML_SELF_CLOSING = /<[A-Za-z0-9\\._:-]+\s*\/>/;
  const XML_TAG = {
    begin: /<[A-Za-z0-9\\._:-]+/,
    end: /\/[A-Za-z0-9\\._:-]+>|\/>/,
    /**
     * @param {RegExpMatchArray} match
     * @param {CallbackResponse} response
     */
    isTrulyOpeningTag: (match, response) => {
      const afterMatchIndex = match[0].length + match.index;
      const nextChar = match.input[afterMatchIndex];
      if (
        // HTML should not include another raw `<` inside a tag
        // nested type?
        // `<Array<Array<number>>`, etc.
        nextChar === "<" || // the , gives away that this is not HTML
        // `<T, A extends keyof T, V>`
        nextChar === ","
      ) {
        response.ignoreMatch();
        return;
      }
      if (nextChar === ">") {
        if (!hasClosingTag(match, { after: afterMatchIndex })) {
          response.ignoreMatch();
        }
      }
      let m;
      const afterMatch = match.input.substring(afterMatchIndex);
      if (m = afterMatch.match(/^\s*=/)) {
        response.ignoreMatch();
        return;
      }
      if (m = afterMatch.match(/^\s+extends\s+/)) {
        if (m.index === 0) {
          response.ignoreMatch();
          return;
        }
      }
    }
  };
  const KEYWORDS$1 = {
    $pattern: IDENT_RE,
    keyword: KEYWORDS,
    literal: LITERALS,
    built_in: BUILT_INS,
    "variable.language": BUILT_IN_VARIABLES
  };
  const decimalDigits3 = "[0-9](_?[0-9])*";
  const frac3 = `\\.(${decimalDigits3})`;
  const decimalInteger = `0|[1-9](_?[0-9])*|0[0-7]*[89][0-9]*`;
  const NUMBER = {
    className: "number",
    variants: [
      // DecimalLiteral
      { begin: `(\\b(${decimalInteger})((${frac3})|\\.)?|(${frac3}))[eE][+-]?(${decimalDigits3})\\b` },
      { begin: `\\b(${decimalInteger})\\b((${frac3})\\b|\\.)?|(${frac3})\\b` },
      // DecimalBigIntegerLiteral
      { begin: `\\b(0|[1-9](_?[0-9])*)n\\b` },
      // NonDecimalIntegerLiteral
      { begin: "\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*n?\\b" },
      { begin: "\\b0[bB][0-1](_?[0-1])*n?\\b" },
      { begin: "\\b0[oO][0-7](_?[0-7])*n?\\b" },
      // LegacyOctalIntegerLiteral (does not include underscore separators)
      // https://tc39.es/ecma262/#sec-additional-syntax-numeric-literals
      { begin: "\\b0[0-7]+n?\\b" }
    ],
    relevance: 0
  };
  const SUBST = {
    className: "subst",
    begin: "\\$\\{",
    end: "\\}",
    keywords: KEYWORDS$1,
    contains: []
    // defined later
  };
  const HTML_TEMPLATE = {
    begin: ".?html`",
    end: "",
    starts: {
      end: "`",
      returnEnd: false,
      contains: [
        hljs.BACKSLASH_ESCAPE,
        SUBST
      ],
      subLanguage: "xml"
    }
  };
  const CSS_TEMPLATE = {
    begin: ".?css`",
    end: "",
    starts: {
      end: "`",
      returnEnd: false,
      contains: [
        hljs.BACKSLASH_ESCAPE,
        SUBST
      ],
      subLanguage: "css"
    }
  };
  const GRAPHQL_TEMPLATE = {
    begin: ".?gql`",
    end: "",
    starts: {
      end: "`",
      returnEnd: false,
      contains: [
        hljs.BACKSLASH_ESCAPE,
        SUBST
      ],
      subLanguage: "graphql"
    }
  };
  const TEMPLATE_STRING = {
    className: "string",
    begin: "`",
    end: "`",
    contains: [
      hljs.BACKSLASH_ESCAPE,
      SUBST
    ]
  };
  const JSDOC_COMMENT = hljs.COMMENT(
    /\/\*\*(?!\/)/,
    "\\*/",
    {
      relevance: 0,
      contains: [
        {
          begin: "(?=@[A-Za-z]+)",
          relevance: 0,
          contains: [
            {
              className: "doctag",
              begin: "@[A-Za-z]+"
            },
            {
              className: "type",
              begin: "\\{",
              end: "\\}",
              excludeEnd: true,
              excludeBegin: true,
              relevance: 0
            },
            {
              className: "variable",
              begin: IDENT_RE$1 + "(?=\\s*(-)|$)",
              endsParent: true,
              relevance: 0
            },
            // eat spaces (not newlines) so we can find
            // types or variables
            {
              begin: /(?=[^\n])\s/,
              relevance: 0
            }
          ]
        }
      ]
    }
  );
  const COMMENT = {
    className: "comment",
    variants: [
      JSDOC_COMMENT,
      hljs.C_BLOCK_COMMENT_MODE,
      hljs.C_LINE_COMMENT_MODE
    ]
  };
  const SUBST_INTERNALS = [
    hljs.APOS_STRING_MODE,
    hljs.QUOTE_STRING_MODE,
    HTML_TEMPLATE,
    CSS_TEMPLATE,
    GRAPHQL_TEMPLATE,
    TEMPLATE_STRING,
    // Skip numbers when they are part of a variable name
    { match: /\$\d+/ },
    NUMBER
    // This is intentional:
    // See https://github.com/highlightjs/highlight.js/issues/3288
    // hljs.REGEXP_MODE
  ];
  SUBST.contains = SUBST_INTERNALS.concat({
    // we need to pair up {} inside our subst to prevent
    // it from ending too early by matching another }
    begin: /\{/,
    end: /\}/,
    keywords: KEYWORDS$1,
    contains: [
      "self"
    ].concat(SUBST_INTERNALS)
  });
  const SUBST_AND_COMMENTS = [].concat(COMMENT, SUBST.contains);
  const PARAMS_CONTAINS = SUBST_AND_COMMENTS.concat([
    // eat recursive parens in sub expressions
    {
      begin: /(\s*)\(/,
      end: /\)/,
      keywords: KEYWORDS$1,
      contains: ["self"].concat(SUBST_AND_COMMENTS)
    }
  ]);
  const PARAMS = {
    className: "params",
    // convert this to negative lookbehind in v12
    begin: /(\s*)\(/,
    // to match the parms with
    end: /\)/,
    excludeBegin: true,
    excludeEnd: true,
    keywords: KEYWORDS$1,
    contains: PARAMS_CONTAINS
  };
  const CLASS_OR_EXTENDS = {
    variants: [
      // class Car extends vehicle
      {
        match: [
          /class/,
          /\s+/,
          IDENT_RE$1,
          /\s+/,
          /extends/,
          /\s+/,
          regex.concat(IDENT_RE$1, "(", regex.concat(/\./, IDENT_RE$1), ")*")
        ],
        scope: {
          1: "keyword",
          3: "title.class",
          5: "keyword",
          7: "title.class.inherited"
        }
      },
      // class Car
      {
        match: [
          /class/,
          /\s+/,
          IDENT_RE$1
        ],
        scope: {
          1: "keyword",
          3: "title.class"
        }
      }
    ]
  };
  const CLASS_REFERENCE = {
    relevance: 0,
    match: regex.either(
      // Hard coded exceptions
      /\bJSON/,
      // Float32Array, OutT
      /\b[A-Z][a-z]+([A-Z][a-z]*|\d)*/,
      // CSSFactory, CSSFactoryT
      /\b[A-Z]{2,}([A-Z][a-z]+|\d)+([A-Z][a-z]*)*/,
      // FPs, FPsT
      /\b[A-Z]{2,}[a-z]+([A-Z][a-z]+|\d)*([A-Z][a-z]*)*/
      // P
      // single letters are not highlighted
      // BLAH
      // this will be flagged as a UPPER_CASE_CONSTANT instead
    ),
    className: "title.class",
    keywords: {
      _: [
        // se we still get relevance credit for JS library classes
        ...TYPES,
        ...ERROR_TYPES
      ]
    }
  };
  const USE_STRICT = {
    label: "use_strict",
    className: "meta",
    relevance: 10,
    begin: /^\s*['"]use (strict|asm)['"]/
  };
  const FUNCTION_DEFINITION = {
    variants: [
      {
        match: [
          /function/,
          /\s+/,
          IDENT_RE$1,
          /(?=\s*\()/
        ]
      },
      // anonymous function
      {
        match: [
          /function/,
          /\s*(?=\()/
        ]
      }
    ],
    className: {
      1: "keyword",
      3: "title.function"
    },
    label: "func.def",
    contains: [PARAMS],
    illegal: /%/
  };
  const UPPER_CASE_CONSTANT = {
    relevance: 0,
    match: /\b[A-Z][A-Z_0-9]+\b/,
    className: "variable.constant"
  };
  function noneOf(list) {
    return regex.concat("(?!", list.join("|"), ")");
  }
  const FUNCTION_CALL = {
    match: regex.concat(
      /\b/,
      noneOf([
        ...BUILT_IN_GLOBALS,
        "super",
        "import"
      ].map((x) => `${x}\\s*\\(`)),
      IDENT_RE$1,
      regex.lookahead(/\s*\(/)
    ),
    className: "title.function",
    relevance: 0
  };
  const PROPERTY_ACCESS = {
    begin: regex.concat(/\./, regex.lookahead(
      regex.concat(IDENT_RE$1, /(?![0-9A-Za-z$_(])/)
    )),
    end: IDENT_RE$1,
    excludeBegin: true,
    keywords: "prototype",
    className: "property",
    relevance: 0
  };
  const GETTER_OR_SETTER = {
    match: [
      /get|set/,
      /\s+/,
      IDENT_RE$1,
      /(?=\()/
    ],
    className: {
      1: "keyword",
      3: "title.function"
    },
    contains: [
      {
        // eat to avoid empty params
        begin: /\(\)/
      },
      PARAMS
    ]
  };
  const FUNC_LEAD_IN_RE = "(\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)|" + hljs.UNDERSCORE_IDENT_RE + ")\\s*=>";
  const FUNCTION_VARIABLE = {
    match: [
      /const|var|let/,
      /\s+/,
      IDENT_RE$1,
      /\s*/,
      /=\s*/,
      /(async\s*)?/,
      // async is optional
      regex.lookahead(FUNC_LEAD_IN_RE)
    ],
    keywords: "async",
    className: {
      1: "keyword",
      3: "title.function"
    },
    contains: [
      PARAMS
    ]
  };
  return {
    name: "JavaScript",
    aliases: ["js", "jsx", "mjs", "cjs"],
    keywords: KEYWORDS$1,
    // this will be extended by TypeScript
    exports: { PARAMS_CONTAINS, CLASS_REFERENCE },
    illegal: /#(?![$_A-z])/,
    contains: [
      hljs.SHEBANG({
        label: "shebang",
        binary: "node",
        relevance: 5
      }),
      USE_STRICT,
      hljs.APOS_STRING_MODE,
      hljs.QUOTE_STRING_MODE,
      HTML_TEMPLATE,
      CSS_TEMPLATE,
      GRAPHQL_TEMPLATE,
      TEMPLATE_STRING,
      COMMENT,
      // Skip numbers when they are part of a variable name
      { match: /\$\d+/ },
      NUMBER,
      CLASS_REFERENCE,
      {
        scope: "attr",
        match: IDENT_RE$1 + regex.lookahead(":"),
        relevance: 0
      },
      FUNCTION_VARIABLE,
      {
        // "value" container
        begin: "(" + hljs.RE_STARTERS_RE + "|\\b(case|return|throw)\\b)\\s*",
        keywords: "return throw case",
        relevance: 0,
        contains: [
          COMMENT,
          hljs.REGEXP_MODE,
          {
            className: "function",
            // we have to count the parens to make sure we actually have the
            // correct bounding ( ) before the =>.  There could be any number of
            // sub-expressions inside also surrounded by parens.
            begin: FUNC_LEAD_IN_RE,
            returnBegin: true,
            end: "\\s*=>",
            contains: [
              {
                className: "params",
                variants: [
                  {
                    begin: hljs.UNDERSCORE_IDENT_RE,
                    relevance: 0
                  },
                  {
                    className: null,
                    begin: /\(\s*\)/,
                    skip: true
                  },
                  {
                    begin: /(\s*)\(/,
                    end: /\)/,
                    excludeBegin: true,
                    excludeEnd: true,
                    keywords: KEYWORDS$1,
                    contains: PARAMS_CONTAINS
                  }
                ]
              }
            ]
          },
          {
            // could be a comma delimited list of params to a function call
            begin: /,/,
            relevance: 0
          },
          {
            match: /\s+/,
            relevance: 0
          },
          {
            // JSX
            variants: [
              { begin: FRAGMENT.begin, end: FRAGMENT.end },
              { match: XML_SELF_CLOSING },
              {
                begin: XML_TAG.begin,
                // we carefully check the opening tag to see if it truly
                // is a tag and not a false positive
                "on:begin": XML_TAG.isTrulyOpeningTag,
                end: XML_TAG.end
              }
            ],
            subLanguage: "xml",
            contains: [
              {
                begin: XML_TAG.begin,
                end: XML_TAG.end,
                skip: true,
                contains: ["self"]
              }
            ]
          }
        ]
      },
      FUNCTION_DEFINITION,
      {
        // prevent this from getting swallowed up by function
        // since they appear "function like"
        beginKeywords: "while if switch catch for"
      },
      {
        // we have to count the parens to make sure we actually have the correct
        // bounding ( ).  There could be any number of sub-expressions inside
        // also surrounded by parens.
        begin: "\\b(?!function)" + hljs.UNDERSCORE_IDENT_RE + "\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)\\s*\\{",
        // end parens
        returnBegin: true,
        label: "func.def",
        contains: [
          PARAMS,
          hljs.inherit(hljs.TITLE_MODE, { begin: IDENT_RE$1, className: "title.function" })
        ]
      },
      // catch ... so it won't trigger the property rule below
      {
        match: /\.\.\./,
        relevance: 0
      },
      PROPERTY_ACCESS,
      // hack: prevents detection of keywords in some circumstances
      // .keyword()
      // $keyword = x
      {
        match: "\\$" + IDENT_RE$1,
        relevance: 0
      },
      {
        match: [/\bconstructor(?=\s*\()/],
        className: { 1: "title.function" },
        contains: [PARAMS]
      },
      FUNCTION_CALL,
      UPPER_CASE_CONSTANT,
      CLASS_OR_EXTENDS,
      GETTER_OR_SETTER,
      {
        match: /\$[(.]/
        // relevance booster for a pattern common to JS libs: `$(something)` and `$.something`
      }
    ]
  };
}

// node_modules/highlight.js/es/languages/json.js
function json(hljs) {
  const ATTRIBUTE = {
    className: "attr",
    begin: /"(\\.|[^\\"\r\n])*"(?=\s*:)/,
    relevance: 1.01
  };
  const PUNCTUATION = {
    match: /[{}[\],:]/,
    className: "punctuation",
    relevance: 0
  };
  const LITERALS3 = [
    "true",
    "false",
    "null"
  ];
  const LITERALS_MODE = {
    scope: "literal",
    beginKeywords: LITERALS3.join(" ")
  };
  return {
    name: "JSON",
    aliases: ["jsonc"],
    keywords: {
      literal: LITERALS3
    },
    contains: [
      ATTRIBUTE,
      PUNCTUATION,
      hljs.QUOTE_STRING_MODE,
      LITERALS_MODE,
      hljs.C_NUMBER_MODE,
      hljs.C_LINE_COMMENT_MODE,
      hljs.C_BLOCK_COMMENT_MODE
    ],
    illegal: "\\S"
  };
}

// node_modules/highlight.js/es/languages/kotlin.js
var decimalDigits2 = "[0-9](_*[0-9])*";
var frac2 = `\\.(${decimalDigits2})`;
var hexDigits2 = "[0-9a-fA-F](_*[0-9a-fA-F])*";
var NUMERIC2 = {
  className: "number",
  variants: [
    // DecimalFloatingPointLiteral
    // including ExponentPart
    { begin: `(\\b(${decimalDigits2})((${frac2})|\\.)?|(${frac2}))[eE][+-]?(${decimalDigits2})[fFdD]?\\b` },
    // excluding ExponentPart
    { begin: `\\b(${decimalDigits2})((${frac2})[fFdD]?\\b|\\.([fFdD]\\b)?)` },
    { begin: `(${frac2})[fFdD]?\\b` },
    { begin: `\\b(${decimalDigits2})[fFdD]\\b` },
    // HexadecimalFloatingPointLiteral
    { begin: `\\b0[xX]((${hexDigits2})\\.?|(${hexDigits2})?\\.(${hexDigits2}))[pP][+-]?(${decimalDigits2})[fFdD]?\\b` },
    // DecimalIntegerLiteral
    { begin: "\\b(0|[1-9](_*[0-9])*)[lL]?\\b" },
    // HexIntegerLiteral
    { begin: `\\b0[xX](${hexDigits2})[lL]?\\b` },
    // OctalIntegerLiteral
    { begin: "\\b0(_*[0-7])*[lL]?\\b" },
    // BinaryIntegerLiteral
    { begin: "\\b0[bB][01](_*[01])*[lL]?\\b" }
  ],
  relevance: 0
};
function kotlin(hljs) {
  const KEYWORDS3 = {
    keyword: "abstract as val var vararg get set class object open private protected public noinline crossinline dynamic final enum if else do while for when throw try catch finally import package is in fun override companion reified inline lateinit init interface annotation data sealed internal infix operator out by constructor super tailrec where const inner suspend typealias external expect actual",
    built_in: "Byte Short Char Int Long Boolean Float Double Void Unit Nothing",
    literal: "true false null"
  };
  const KEYWORDS_WITH_LABEL = {
    className: "keyword",
    begin: /\b(break|continue|return|this)\b/,
    starts: { contains: [
      {
        className: "symbol",
        begin: /@\w+/
      }
    ] }
  };
  const LABEL = {
    className: "symbol",
    begin: hljs.UNDERSCORE_IDENT_RE + "@"
  };
  const SUBST = {
    className: "subst",
    begin: /\$\{/,
    end: /\}/,
    contains: [hljs.C_NUMBER_MODE]
  };
  const VARIABLE = {
    className: "variable",
    begin: "\\$" + hljs.UNDERSCORE_IDENT_RE
  };
  const STRING = {
    className: "string",
    variants: [
      {
        begin: '"""',
        end: '"""(?=[^"])',
        contains: [
          VARIABLE,
          SUBST
        ]
      },
      // Can't use built-in modes easily, as we want to use STRING in the meta
      // context as 'meta-string' and there's no syntax to remove explicitly set
      // classNames in built-in modes.
      {
        begin: "'",
        end: "'",
        illegal: /\n/,
        contains: [hljs.BACKSLASH_ESCAPE]
      },
      {
        begin: '"',
        end: '"',
        illegal: /\n/,
        contains: [
          hljs.BACKSLASH_ESCAPE,
          VARIABLE,
          SUBST
        ]
      }
    ]
  };
  SUBST.contains.push(STRING);
  const ANNOTATION_USE_SITE = {
    className: "meta",
    begin: "@(?:file|property|field|get|set|receiver|param|setparam|delegate)\\s*:(?:\\s*" + hljs.UNDERSCORE_IDENT_RE + ")?"
  };
  const ANNOTATION = {
    className: "meta",
    begin: "@" + hljs.UNDERSCORE_IDENT_RE,
    contains: [
      {
        begin: /\(/,
        end: /\)/,
        contains: [
          hljs.inherit(STRING, { className: "string" }),
          "self"
        ]
      }
    ]
  };
  const KOTLIN_NUMBER_MODE = NUMERIC2;
  const KOTLIN_NESTED_COMMENT = hljs.COMMENT(
    "/\\*",
    "\\*/",
    { contains: [hljs.C_BLOCK_COMMENT_MODE] }
  );
  const KOTLIN_PAREN_TYPE = { variants: [
    {
      className: "type",
      begin: hljs.UNDERSCORE_IDENT_RE
    },
    {
      begin: /\(/,
      end: /\)/,
      contains: []
      // defined later
    }
  ] };
  const KOTLIN_PAREN_TYPE2 = KOTLIN_PAREN_TYPE;
  KOTLIN_PAREN_TYPE2.variants[1].contains = [KOTLIN_PAREN_TYPE];
  KOTLIN_PAREN_TYPE.variants[1].contains = [KOTLIN_PAREN_TYPE2];
  return {
    name: "Kotlin",
    aliases: [
      "kt",
      "kts"
    ],
    keywords: KEYWORDS3,
    contains: [
      hljs.COMMENT(
        "/\\*\\*",
        "\\*/",
        {
          relevance: 0,
          contains: [
            {
              className: "doctag",
              begin: "@[A-Za-z]+"
            }
          ]
        }
      ),
      hljs.C_LINE_COMMENT_MODE,
      KOTLIN_NESTED_COMMENT,
      KEYWORDS_WITH_LABEL,
      LABEL,
      ANNOTATION_USE_SITE,
      ANNOTATION,
      {
        className: "function",
        beginKeywords: "fun",
        end: "[(]|$",
        returnBegin: true,
        excludeEnd: true,
        keywords: KEYWORDS3,
        relevance: 5,
        contains: [
          {
            begin: hljs.UNDERSCORE_IDENT_RE + "\\s*\\(",
            returnBegin: true,
            relevance: 0,
            contains: [hljs.UNDERSCORE_TITLE_MODE]
          },
          {
            className: "type",
            begin: /</,
            end: />/,
            keywords: "reified",
            relevance: 0
          },
          {
            className: "params",
            begin: /\(/,
            end: /\)/,
            endsParent: true,
            keywords: KEYWORDS3,
            relevance: 0,
            contains: [
              {
                begin: /:/,
                end: /[=,\/]/,
                endsWithParent: true,
                contains: [
                  KOTLIN_PAREN_TYPE,
                  hljs.C_LINE_COMMENT_MODE,
                  KOTLIN_NESTED_COMMENT
                ],
                relevance: 0
              },
              hljs.C_LINE_COMMENT_MODE,
              KOTLIN_NESTED_COMMENT,
              ANNOTATION_USE_SITE,
              ANNOTATION,
              STRING,
              hljs.C_NUMBER_MODE
            ]
          },
          KOTLIN_NESTED_COMMENT
        ]
      },
      {
        begin: [
          /class|interface|trait/,
          /\s+/,
          hljs.UNDERSCORE_IDENT_RE
        ],
        beginScope: {
          3: "title.class"
        },
        keywords: "class interface trait",
        end: /[:\{(]|$/,
        excludeEnd: true,
        illegal: "extends implements",
        contains: [
          { beginKeywords: "public protected internal private constructor" },
          hljs.UNDERSCORE_TITLE_MODE,
          {
            className: "type",
            begin: /</,
            end: />/,
            excludeBegin: true,
            excludeEnd: true,
            relevance: 0
          },
          {
            className: "type",
            begin: /[,:]\s*/,
            end: /[<\(,){\s]|$/,
            excludeBegin: true,
            returnEnd: true
          },
          ANNOTATION_USE_SITE,
          ANNOTATION
        ]
      },
      STRING,
      {
        className: "meta",
        begin: "^#!/usr/bin/env",
        end: "$",
        illegal: "\n"
      },
      KOTLIN_NUMBER_MODE
    ]
  };
}

// node_modules/highlight.js/es/languages/less.js
var MODES2 = (hljs) => {
  return {
    IMPORTANT: {
      scope: "meta",
      begin: "!important"
    },
    BLOCK_COMMENT: hljs.C_BLOCK_COMMENT_MODE,
    HEXCOLOR: {
      scope: "number",
      begin: /#(([0-9a-fA-F]{3,4})|(([0-9a-fA-F]{2}){3,4}))\b/
    },
    FUNCTION_DISPATCH: {
      className: "built_in",
      begin: /[\w-]+(?=\()/
    },
    ATTRIBUTE_SELECTOR_MODE: {
      scope: "selector-attr",
      begin: /\[/,
      end: /\]/,
      illegal: "$",
      contains: [
        hljs.APOS_STRING_MODE,
        hljs.QUOTE_STRING_MODE
      ]
    },
    CSS_NUMBER_MODE: {
      scope: "number",
      begin: hljs.NUMBER_RE + "(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",
      relevance: 0
    },
    CSS_VARIABLE: {
      className: "attr",
      begin: /--[A-Za-z_][A-Za-z0-9_-]*/
    }
  };
};
var HTML_TAGS2 = [
  "a",
  "abbr",
  "address",
  "article",
  "aside",
  "audio",
  "b",
  "blockquote",
  "body",
  "button",
  "canvas",
  "caption",
  "cite",
  "code",
  "dd",
  "del",
  "details",
  "dfn",
  "div",
  "dl",
  "dt",
  "em",
  "fieldset",
  "figcaption",
  "figure",
  "footer",
  "form",
  "h1",
  "h2",
  "h3",
  "h4",
  "h5",
  "h6",
  "header",
  "hgroup",
  "html",
  "i",
  "iframe",
  "img",
  "input",
  "ins",
  "kbd",
  "label",
  "legend",
  "li",
  "main",
  "mark",
  "menu",
  "nav",
  "object",
  "ol",
  "optgroup",
  "option",
  "p",
  "picture",
  "q",
  "quote",
  "samp",
  "section",
  "select",
  "source",
  "span",
  "strong",
  "summary",
  "sup",
  "table",
  "tbody",
  "td",
  "textarea",
  "tfoot",
  "th",
  "thead",
  "time",
  "tr",
  "ul",
  "var",
  "video"
];
var SVG_TAGS2 = [
  "defs",
  "g",
  "marker",
  "mask",
  "pattern",
  "svg",
  "switch",
  "symbol",
  "feBlend",
  "feColorMatrix",
  "feComponentTransfer",
  "feComposite",
  "feConvolveMatrix",
  "feDiffuseLighting",
  "feDisplacementMap",
  "feFlood",
  "feGaussianBlur",
  "feImage",
  "feMerge",
  "feMorphology",
  "feOffset",
  "feSpecularLighting",
  "feTile",
  "feTurbulence",
  "linearGradient",
  "radialGradient",
  "stop",
  "circle",
  "ellipse",
  "image",
  "line",
  "path",
  "polygon",
  "polyline",
  "rect",
  "text",
  "use",
  "textPath",
  "tspan",
  "foreignObject",
  "clipPath"
];
var TAGS2 = [
  ...HTML_TAGS2,
  ...SVG_TAGS2
];
var MEDIA_FEATURES2 = [
  "any-hover",
  "any-pointer",
  "aspect-ratio",
  "color",
  "color-gamut",
  "color-index",
  "device-aspect-ratio",
  "device-height",
  "device-width",
  "display-mode",
  "forced-colors",
  "grid",
  "height",
  "hover",
  "inverted-colors",
  "monochrome",
  "orientation",
  "overflow-block",
  "overflow-inline",
  "pointer",
  "prefers-color-scheme",
  "prefers-contrast",
  "prefers-reduced-motion",
  "prefers-reduced-transparency",
  "resolution",
  "scan",
  "scripting",
  "update",
  "width",
  // TODO: find a better solution?
  "min-width",
  "max-width",
  "min-height",
  "max-height"
].sort().reverse();
var PSEUDO_CLASSES2 = [
  "active",
  "any-link",
  "blank",
  "checked",
  "current",
  "default",
  "defined",
  "dir",
  // dir()
  "disabled",
  "drop",
  "empty",
  "enabled",
  "first",
  "first-child",
  "first-of-type",
  "fullscreen",
  "future",
  "focus",
  "focus-visible",
  "focus-within",
  "has",
  // has()
  "host",
  // host or host()
  "host-context",
  // host-context()
  "hover",
  "indeterminate",
  "in-range",
  "invalid",
  "is",
  // is()
  "lang",
  // lang()
  "last-child",
  "last-of-type",
  "left",
  "link",
  "local-link",
  "not",
  // not()
  "nth-child",
  // nth-child()
  "nth-col",
  // nth-col()
  "nth-last-child",
  // nth-last-child()
  "nth-last-col",
  // nth-last-col()
  "nth-last-of-type",
  //nth-last-of-type()
  "nth-of-type",
  //nth-of-type()
  "only-child",
  "only-of-type",
  "optional",
  "out-of-range",
  "past",
  "placeholder-shown",
  "read-only",
  "read-write",
  "required",
  "right",
  "root",
  "scope",
  "target",
  "target-within",
  "user-invalid",
  "valid",
  "visited",
  "where"
  // where()
].sort().reverse();
var PSEUDO_ELEMENTS2 = [
  "after",
  "backdrop",
  "before",
  "cue",
  "cue-region",
  "first-letter",
  "first-line",
  "grammar-error",
  "marker",
  "part",
  "placeholder",
  "selection",
  "slotted",
  "spelling-error"
].sort().reverse();
var ATTRIBUTES2 = [
  "accent-color",
  "align-content",
  "align-items",
  "align-self",
  "alignment-baseline",
  "all",
  "anchor-name",
  "animation",
  "animation-composition",
  "animation-delay",
  "animation-direction",
  "animation-duration",
  "animation-fill-mode",
  "animation-iteration-count",
  "animation-name",
  "animation-play-state",
  "animation-range",
  "animation-range-end",
  "animation-range-start",
  "animation-timeline",
  "animation-timing-function",
  "appearance",
  "aspect-ratio",
  "backdrop-filter",
  "backface-visibility",
  "background",
  "background-attachment",
  "background-blend-mode",
  "background-clip",
  "background-color",
  "background-image",
  "background-origin",
  "background-position",
  "background-position-x",
  "background-position-y",
  "background-repeat",
  "background-size",
  "baseline-shift",
  "block-size",
  "border",
  "border-block",
  "border-block-color",
  "border-block-end",
  "border-block-end-color",
  "border-block-end-style",
  "border-block-end-width",
  "border-block-start",
  "border-block-start-color",
  "border-block-start-style",
  "border-block-start-width",
  "border-block-style",
  "border-block-width",
  "border-bottom",
  "border-bottom-color",
  "border-bottom-left-radius",
  "border-bottom-right-radius",
  "border-bottom-style",
  "border-bottom-width",
  "border-collapse",
  "border-color",
  "border-end-end-radius",
  "border-end-start-radius",
  "border-image",
  "border-image-outset",
  "border-image-repeat",
  "border-image-slice",
  "border-image-source",
  "border-image-width",
  "border-inline",
  "border-inline-color",
  "border-inline-end",
  "border-inline-end-color",
  "border-inline-end-style",
  "border-inline-end-width",
  "border-inline-start",
  "border-inline-start-color",
  "border-inline-start-style",
  "border-inline-start-width",
  "border-inline-style",
  "border-inline-width",
  "border-left",
  "border-left-color",
  "border-left-style",
  "border-left-width",
  "border-radius",
  "border-right",
  "border-right-color",
  "border-right-style",
  "border-right-width",
  "border-spacing",
  "border-start-end-radius",
  "border-start-start-radius",
  "border-style",
  "border-top",
  "border-top-color",
  "border-top-left-radius",
  "border-top-right-radius",
  "border-top-style",
  "border-top-width",
  "border-width",
  "bottom",
  "box-align",
  "box-decoration-break",
  "box-direction",
  "box-flex",
  "box-flex-group",
  "box-lines",
  "box-ordinal-group",
  "box-orient",
  "box-pack",
  "box-shadow",
  "box-sizing",
  "break-after",
  "break-before",
  "break-inside",
  "caption-side",
  "caret-color",
  "clear",
  "clip",
  "clip-path",
  "clip-rule",
  "color",
  "color-interpolation",
  "color-interpolation-filters",
  "color-profile",
  "color-rendering",
  "color-scheme",
  "column-count",
  "column-fill",
  "column-gap",
  "column-rule",
  "column-rule-color",
  "column-rule-style",
  "column-rule-width",
  "column-span",
  "column-width",
  "columns",
  "contain",
  "contain-intrinsic-block-size",
  "contain-intrinsic-height",
  "contain-intrinsic-inline-size",
  "contain-intrinsic-size",
  "contain-intrinsic-width",
  "container",
  "container-name",
  "container-type",
  "content",
  "content-visibility",
  "counter-increment",
  "counter-reset",
  "counter-set",
  "cue",
  "cue-after",
  "cue-before",
  "cursor",
  "cx",
  "cy",
  "direction",
  "display",
  "dominant-baseline",
  "empty-cells",
  "enable-background",
  "field-sizing",
  "fill",
  "fill-opacity",
  "fill-rule",
  "filter",
  "flex",
  "flex-basis",
  "flex-direction",
  "flex-flow",
  "flex-grow",
  "flex-shrink",
  "flex-wrap",
  "float",
  "flood-color",
  "flood-opacity",
  "flow",
  "font",
  "font-display",
  "font-family",
  "font-feature-settings",
  "font-kerning",
  "font-language-override",
  "font-optical-sizing",
  "font-palette",
  "font-size",
  "font-size-adjust",
  "font-smooth",
  "font-smoothing",
  "font-stretch",
  "font-style",
  "font-synthesis",
  "font-synthesis-position",
  "font-synthesis-small-caps",
  "font-synthesis-style",
  "font-synthesis-weight",
  "font-variant",
  "font-variant-alternates",
  "font-variant-caps",
  "font-variant-east-asian",
  "font-variant-emoji",
  "font-variant-ligatures",
  "font-variant-numeric",
  "font-variant-position",
  "font-variation-settings",
  "font-weight",
  "forced-color-adjust",
  "gap",
  "glyph-orientation-horizontal",
  "glyph-orientation-vertical",
  "grid",
  "grid-area",
  "grid-auto-columns",
  "grid-auto-flow",
  "grid-auto-rows",
  "grid-column",
  "grid-column-end",
  "grid-column-start",
  "grid-gap",
  "grid-row",
  "grid-row-end",
  "grid-row-start",
  "grid-template",
  "grid-template-areas",
  "grid-template-columns",
  "grid-template-rows",
  "hanging-punctuation",
  "height",
  "hyphenate-character",
  "hyphenate-limit-chars",
  "hyphens",
  "icon",
  "image-orientation",
  "image-rendering",
  "image-resolution",
  "ime-mode",
  "initial-letter",
  "initial-letter-align",
  "inline-size",
  "inset",
  "inset-area",
  "inset-block",
  "inset-block-end",
  "inset-block-start",
  "inset-inline",
  "inset-inline-end",
  "inset-inline-start",
  "isolation",
  "justify-content",
  "justify-items",
  "justify-self",
  "kerning",
  "left",
  "letter-spacing",
  "lighting-color",
  "line-break",
  "line-height",
  "line-height-step",
  "list-style",
  "list-style-image",
  "list-style-position",
  "list-style-type",
  "margin",
  "margin-block",
  "margin-block-end",
  "margin-block-start",
  "margin-bottom",
  "margin-inline",
  "margin-inline-end",
  "margin-inline-start",
  "margin-left",
  "margin-right",
  "margin-top",
  "margin-trim",
  "marker",
  "marker-end",
  "marker-mid",
  "marker-start",
  "marks",
  "mask",
  "mask-border",
  "mask-border-mode",
  "mask-border-outset",
  "mask-border-repeat",
  "mask-border-slice",
  "mask-border-source",
  "mask-border-width",
  "mask-clip",
  "mask-composite",
  "mask-image",
  "mask-mode",
  "mask-origin",
  "mask-position",
  "mask-repeat",
  "mask-size",
  "mask-type",
  "masonry-auto-flow",
  "math-depth",
  "math-shift",
  "math-style",
  "max-block-size",
  "max-height",
  "max-inline-size",
  "max-width",
  "min-block-size",
  "min-height",
  "min-inline-size",
  "min-width",
  "mix-blend-mode",
  "nav-down",
  "nav-index",
  "nav-left",
  "nav-right",
  "nav-up",
  "none",
  "normal",
  "object-fit",
  "object-position",
  "offset",
  "offset-anchor",
  "offset-distance",
  "offset-path",
  "offset-position",
  "offset-rotate",
  "opacity",
  "order",
  "orphans",
  "outline",
  "outline-color",
  "outline-offset",
  "outline-style",
  "outline-width",
  "overflow",
  "overflow-anchor",
  "overflow-block",
  "overflow-clip-margin",
  "overflow-inline",
  "overflow-wrap",
  "overflow-x",
  "overflow-y",
  "overlay",
  "overscroll-behavior",
  "overscroll-behavior-block",
  "overscroll-behavior-inline",
  "overscroll-behavior-x",
  "overscroll-behavior-y",
  "padding",
  "padding-block",
  "padding-block-end",
  "padding-block-start",
  "padding-bottom",
  "padding-inline",
  "padding-inline-end",
  "padding-inline-start",
  "padding-left",
  "padding-right",
  "padding-top",
  "page",
  "page-break-after",
  "page-break-before",
  "page-break-inside",
  "paint-order",
  "pause",
  "pause-after",
  "pause-before",
  "perspective",
  "perspective-origin",
  "place-content",
  "place-items",
  "place-self",
  "pointer-events",
  "position",
  "position-anchor",
  "position-visibility",
  "print-color-adjust",
  "quotes",
  "r",
  "resize",
  "rest",
  "rest-after",
  "rest-before",
  "right",
  "rotate",
  "row-gap",
  "ruby-align",
  "ruby-position",
  "scale",
  "scroll-behavior",
  "scroll-margin",
  "scroll-margin-block",
  "scroll-margin-block-end",
  "scroll-margin-block-start",
  "scroll-margin-bottom",
  "scroll-margin-inline",
  "scroll-margin-inline-end",
  "scroll-margin-inline-start",
  "scroll-margin-left",
  "scroll-margin-right",
  "scroll-margin-top",
  "scroll-padding",
  "scroll-padding-block",
  "scroll-padding-block-end",
  "scroll-padding-block-start",
  "scroll-padding-bottom",
  "scroll-padding-inline",
  "scroll-padding-inline-end",
  "scroll-padding-inline-start",
  "scroll-padding-left",
  "scroll-padding-right",
  "scroll-padding-top",
  "scroll-snap-align",
  "scroll-snap-stop",
  "scroll-snap-type",
  "scroll-timeline",
  "scroll-timeline-axis",
  "scroll-timeline-name",
  "scrollbar-color",
  "scrollbar-gutter",
  "scrollbar-width",
  "shape-image-threshold",
  "shape-margin",
  "shape-outside",
  "shape-rendering",
  "speak",
  "speak-as",
  "src",
  // @font-face
  "stop-color",
  "stop-opacity",
  "stroke",
  "stroke-dasharray",
  "stroke-dashoffset",
  "stroke-linecap",
  "stroke-linejoin",
  "stroke-miterlimit",
  "stroke-opacity",
  "stroke-width",
  "tab-size",
  "table-layout",
  "text-align",
  "text-align-all",
  "text-align-last",
  "text-anchor",
  "text-combine-upright",
  "text-decoration",
  "text-decoration-color",
  "text-decoration-line",
  "text-decoration-skip",
  "text-decoration-skip-ink",
  "text-decoration-style",
  "text-decoration-thickness",
  "text-emphasis",
  "text-emphasis-color",
  "text-emphasis-position",
  "text-emphasis-style",
  "text-indent",
  "text-justify",
  "text-orientation",
  "text-overflow",
  "text-rendering",
  "text-shadow",
  "text-size-adjust",
  "text-transform",
  "text-underline-offset",
  "text-underline-position",
  "text-wrap",
  "text-wrap-mode",
  "text-wrap-style",
  "timeline-scope",
  "top",
  "touch-action",
  "transform",
  "transform-box",
  "transform-origin",
  "transform-style",
  "transition",
  "transition-behavior",
  "transition-delay",
  "transition-duration",
  "transition-property",
  "transition-timing-function",
  "translate",
  "unicode-bidi",
  "user-modify",
  "user-select",
  "vector-effect",
  "vertical-align",
  "view-timeline",
  "view-timeline-axis",
  "view-timeline-inset",
  "view-timeline-name",
  "view-transition-name",
  "visibility",
  "voice-balance",
  "voice-duration",
  "voice-family",
  "voice-pitch",
  "voice-range",
  "voice-rate",
  "voice-stress",
  "voice-volume",
  "white-space",
  "white-space-collapse",
  "widows",
  "width",
  "will-change",
  "word-break",
  "word-spacing",
  "word-wrap",
  "writing-mode",
  "x",
  "y",
  "z-index",
  "zoom"
].sort().reverse();
var PSEUDO_SELECTORS = PSEUDO_CLASSES2.concat(PSEUDO_ELEMENTS2).sort().reverse();
function less(hljs) {
  const modes = MODES2(hljs);
  const PSEUDO_SELECTORS$1 = PSEUDO_SELECTORS;
  const AT_MODIFIERS = "and or not only";
  const IDENT_RE3 = "[\\w-]+";
  const INTERP_IDENT_RE = "(" + IDENT_RE3 + "|@\\{" + IDENT_RE3 + "\\})";
  const RULES = [];
  const VALUE_MODES = [];
  const STRING_MODE = function(c2) {
    return {
      // Less strings are not multiline (also include '~' for more consistent coloring of "escaped" strings)
      className: "string",
      begin: "~?" + c2 + ".*?" + c2
    };
  };
  const IDENT_MODE = function(name, begin, relevance) {
    return {
      className: name,
      begin,
      relevance
    };
  };
  const AT_KEYWORDS = {
    $pattern: /[a-z-]+/,
    keyword: AT_MODIFIERS,
    attribute: MEDIA_FEATURES2.join(" ")
  };
  const PARENS_MODE = {
    // used only to properly balance nested parens inside mixin call, def. arg list
    begin: "\\(",
    end: "\\)",
    contains: VALUE_MODES,
    keywords: AT_KEYWORDS,
    relevance: 0
  };
  VALUE_MODES.push(
    hljs.C_LINE_COMMENT_MODE,
    hljs.C_BLOCK_COMMENT_MODE,
    STRING_MODE("'"),
    STRING_MODE('"'),
    modes.CSS_NUMBER_MODE,
    // fixme: it does not include dot for numbers like .5em :(
    {
      begin: "(url|data-uri)\\(",
      starts: {
        className: "string",
        end: "[\\)\\n]",
        excludeEnd: true
      }
    },
    modes.HEXCOLOR,
    PARENS_MODE,
    IDENT_MODE("variable", "@@?" + IDENT_RE3, 10),
    IDENT_MODE("variable", "@\\{" + IDENT_RE3 + "\\}"),
    IDENT_MODE("built_in", "~?`[^`]*?`"),
    // inline javascript (or whatever host language) *multiline* string
    {
      // @media features (it’s here to not duplicate things in AT_RULE_MODE with extra PARENS_MODE overriding):
      className: "attribute",
      begin: IDENT_RE3 + "\\s*:",
      end: ":",
      returnBegin: true,
      excludeEnd: true
    },
    modes.IMPORTANT,
    { beginKeywords: "and not" },
    modes.FUNCTION_DISPATCH
  );
  const VALUE_WITH_RULESETS = VALUE_MODES.concat({
    begin: /\{/,
    end: /\}/,
    contains: RULES
  });
  const MIXIN_GUARD_MODE = {
    beginKeywords: "when",
    endsWithParent: true,
    contains: [{ beginKeywords: "and not" }].concat(VALUE_MODES)
    // using this form to override VALUE’s 'function' match
  };
  const RULE_MODE = {
    begin: INTERP_IDENT_RE + "\\s*:",
    returnBegin: true,
    end: /[;}]/,
    relevance: 0,
    contains: [
      { begin: /-(webkit|moz|ms|o)-/ },
      modes.CSS_VARIABLE,
      {
        className: "attribute",
        begin: "\\b(" + ATTRIBUTES2.join("|") + ")\\b",
        end: /(?=:)/,
        starts: {
          endsWithParent: true,
          illegal: "[<=$]",
          relevance: 0,
          contains: VALUE_MODES
        }
      }
    ]
  };
  const AT_RULE_MODE = {
    className: "keyword",
    begin: "@(import|media|charset|font-face|(-[a-z]+-)?keyframes|supports|document|namespace|page|viewport|host)\\b",
    starts: {
      end: "[;{}]",
      keywords: AT_KEYWORDS,
      returnEnd: true,
      contains: VALUE_MODES,
      relevance: 0
    }
  };
  const VAR_RULE_MODE = {
    className: "variable",
    variants: [
      // using more strict pattern for higher relevance to increase chances of Less detection.
      // this is *the only* Less specific statement used in most of the sources, so...
      // (we’ll still often loose to the css-parser unless there's '//' comment,
      // simply because 1 variable just can't beat 99 properties :)
      {
        begin: "@" + IDENT_RE3 + "\\s*:",
        relevance: 15
      },
      { begin: "@" + IDENT_RE3 }
    ],
    starts: {
      end: "[;}]",
      returnEnd: true,
      contains: VALUE_WITH_RULESETS
    }
  };
  const SELECTOR_MODE = {
    // first parse unambiguous selectors (i.e. those not starting with tag)
    // then fall into the scary lookahead-discriminator variant.
    // this mode also handles mixin definitions and calls
    variants: [
      {
        begin: "[\\.#:&\\[>]",
        end: "[;{}]"
        // mixin calls end with ';'
      },
      {
        begin: INTERP_IDENT_RE,
        end: /\{/
      }
    ],
    returnBegin: true,
    returnEnd: true,
    illegal: `[<='$"]`,
    relevance: 0,
    contains: [
      hljs.C_LINE_COMMENT_MODE,
      hljs.C_BLOCK_COMMENT_MODE,
      MIXIN_GUARD_MODE,
      IDENT_MODE("keyword", "all\\b"),
      IDENT_MODE("variable", "@\\{" + IDENT_RE3 + "\\}"),
      // otherwise it’s identified as tag
      {
        begin: "\\b(" + TAGS2.join("|") + ")\\b",
        className: "selector-tag"
      },
      modes.CSS_NUMBER_MODE,
      IDENT_MODE("selector-tag", INTERP_IDENT_RE, 0),
      IDENT_MODE("selector-id", "#" + INTERP_IDENT_RE),
      IDENT_MODE("selector-class", "\\." + INTERP_IDENT_RE, 0),
      IDENT_MODE("selector-tag", "&", 0),
      modes.ATTRIBUTE_SELECTOR_MODE,
      {
        className: "selector-pseudo",
        begin: ":(" + PSEUDO_CLASSES2.join("|") + ")"
      },
      {
        className: "selector-pseudo",
        begin: ":(:)?(" + PSEUDO_ELEMENTS2.join("|") + ")"
      },
      {
        begin: /\(/,
        end: /\)/,
        relevance: 0,
        contains: VALUE_WITH_RULESETS
      },
      // argument list of parametric mixins
      { begin: "!important" },
      // eat !important after mixin call or it will be colored as tag
      modes.FUNCTION_DISPATCH
    ]
  };
  const PSEUDO_SELECTOR_MODE = {
    begin: IDENT_RE3 + `:(:)?(${PSEUDO_SELECTORS$1.join("|")})`,
    returnBegin: true,
    contains: [SELECTOR_MODE]
  };
  RULES.push(
    hljs.C_LINE_COMMENT_MODE,
    hljs.C_BLOCK_COMMENT_MODE,
    AT_RULE_MODE,
    VAR_RULE_MODE,
    PSEUDO_SELECTOR_MODE,
    RULE_MODE,
    SELECTOR_MODE,
    MIXIN_GUARD_MODE,
    modes.FUNCTION_DISPATCH
  );
  return {
    name: "Less",
    case_insensitive: true,
    illegal: `[=>'/<($"]`,
    contains: RULES
  };
}

// node_modules/highlight.js/es/languages/lua.js
function lua(hljs) {
  const OPENING_LONG_BRACKET = "\\[=*\\[";
  const CLOSING_LONG_BRACKET = "\\]=*\\]";
  const LONG_BRACKETS = {
    begin: OPENING_LONG_BRACKET,
    end: CLOSING_LONG_BRACKET,
    contains: ["self"]
  };
  const COMMENTS = [
    hljs.COMMENT("--(?!" + OPENING_LONG_BRACKET + ")", "$"),
    hljs.COMMENT(
      "--" + OPENING_LONG_BRACKET,
      CLOSING_LONG_BRACKET,
      {
        contains: [LONG_BRACKETS],
        relevance: 10
      }
    )
  ];
  return {
    name: "Lua",
    aliases: ["pluto"],
    keywords: {
      $pattern: hljs.UNDERSCORE_IDENT_RE,
      literal: "true false nil",
      keyword: "and break do else elseif end for goto if in local not or repeat return then until while",
      built_in: (
        // Metatags and globals:
        "_G _ENV _VERSION __index __newindex __mode __call __metatable __tostring __len __gc __add __sub __mul __div __mod __pow __concat __unm __eq __lt __le assert collectgarbage dofile error getfenv getmetatable ipairs load loadfile loadstring module next pairs pcall print rawequal rawget rawset require select setfenv setmetatable tonumber tostring type unpack xpcall arg self coroutine resume yield status wrap create running debug getupvalue debug sethook getmetatable gethook setmetatable setlocal traceback setfenv getinfo setupvalue getlocal getregistry getfenv io lines write close flush open output type read stderr stdin input stdout popen tmpfile math log max acos huge ldexp pi cos tanh pow deg tan cosh sinh random randomseed frexp ceil floor rad abs sqrt modf asin min mod fmod log10 atan2 exp sin atan os exit setlocale date getenv difftime remove time clock tmpname rename execute package preload loadlib loaded loaders cpath config path seeall string sub upper len gfind rep find match char dump gmatch reverse byte format gsub lower table setn insert getn foreachi maxn foreach concat sort remove"
      )
    },
    contains: COMMENTS.concat([
      {
        className: "function",
        beginKeywords: "function",
        end: "\\)",
        contains: [
          hljs.inherit(hljs.TITLE_MODE, { begin: "([_a-zA-Z]\\w*\\.)*([_a-zA-Z]\\w*:)?[_a-zA-Z]\\w*" }),
          {
            className: "params",
            begin: "\\(",
            endsWithParent: true,
            contains: COMMENTS
          }
        ].concat(COMMENTS)
      },
      hljs.C_NUMBER_MODE,
      hljs.APOS_STRING_MODE,
      hljs.QUOTE_STRING_MODE,
      {
        className: "string",
        begin: OPENING_LONG_BRACKET,
        end: CLOSING_LONG_BRACKET,
        contains: [LONG_BRACKETS],
        relevance: 5
      }
    ])
  };
}

// node_modules/highlight.js/es/languages/makefile.js
function makefile(hljs) {
  const VARIABLE = {
    className: "variable",
    variants: [
      {
        begin: "\\$\\(" + hljs.UNDERSCORE_IDENT_RE + "\\)",
        contains: [hljs.BACKSLASH_ESCAPE]
      },
      { begin: /\$[@%<?\^\+\*]/ }
    ]
  };
  const QUOTE_STRING = {
    className: "string",
    begin: /"/,
    end: /"/,
    contains: [
      hljs.BACKSLASH_ESCAPE,
      VARIABLE
    ]
  };
  const FUNC = {
    className: "variable",
    begin: /\$\([\w-]+\s/,
    end: /\)/,
    keywords: { built_in: "subst patsubst strip findstring filter filter-out sort word wordlist firstword lastword dir notdir suffix basename addsuffix addprefix join wildcard realpath abspath error warning shell origin flavor foreach if or and call eval file value" },
    contains: [
      VARIABLE,
      QUOTE_STRING
      // Added QUOTE_STRING as they can be a part of functions
    ]
  };
  const ASSIGNMENT = { begin: "^" + hljs.UNDERSCORE_IDENT_RE + "\\s*(?=[:+?]?=)" };
  const META = {
    className: "meta",
    begin: /^\.PHONY:/,
    end: /$/,
    keywords: {
      $pattern: /[\.\w]+/,
      keyword: ".PHONY"
    }
  };
  const TARGET = {
    className: "section",
    begin: /^[^\s]+:/,
    end: /$/,
    contains: [VARIABLE]
  };
  return {
    name: "Makefile",
    aliases: [
      "mk",
      "mak",
      "make"
    ],
    keywords: {
      $pattern: /[\w-]+/,
      keyword: "define endef undefine ifdef ifndef ifeq ifneq else endif include -include sinclude override export unexport private vpath"
    },
    contains: [
      hljs.HASH_COMMENT_MODE,
      VARIABLE,
      QUOTE_STRING,
      FUNC,
      ASSIGNMENT,
      META,
      TARGET
    ]
  };
}

// node_modules/highlight.js/es/languages/markdown.js
function markdown(hljs) {
  const regex = hljs.regex;
  const INLINE_HTML = {
    begin: /<\/?[A-Za-z_]/,
    end: ">",
    subLanguage: "xml",
    relevance: 0
  };
  const HORIZONTAL_RULE = {
    begin: "^[-\\*]{3,}",
    end: "$"
  };
  const CODE = {
    className: "code",
    variants: [
      // TODO: fix to allow these to work with sublanguage also
      { begin: "(`{3,})[^`](.|\\n)*?\\1`*[ ]*" },
      { begin: "(~{3,})[^~](.|\\n)*?\\1~*[ ]*" },
      // needed to allow markdown as a sublanguage to work
      {
        begin: "```",
        end: "```+[ ]*$"
      },
      {
        begin: "~~~",
        end: "~~~+[ ]*$"
      },
      { begin: "`.+?`" },
      {
        begin: "(?=^( {4}|\\t))",
        // use contains to gobble up multiple lines to allow the block to be whatever size
        // but only have a single open/close tag vs one per line
        contains: [
          {
            begin: "^( {4}|\\t)",
            end: "(\\n)$"
          }
        ],
        relevance: 0
      }
    ]
  };
  const LIST = {
    className: "bullet",
    begin: "^[ 	]*([*+-]|(\\d+\\.))(?=\\s+)",
    end: "\\s+",
    excludeEnd: true
  };
  const LINK_REFERENCE = {
    begin: /^\[[^\n]+\]:/,
    returnBegin: true,
    contains: [
      {
        className: "symbol",
        begin: /\[/,
        end: /\]/,
        excludeBegin: true,
        excludeEnd: true
      },
      {
        className: "link",
        begin: /:\s*/,
        end: /$/,
        excludeBegin: true
      }
    ]
  };
  const URL_SCHEME = /[A-Za-z][A-Za-z0-9+.-]*/;
  const LINK = {
    variants: [
      // too much like nested array access in so many languages
      // to have any real relevance
      {
        begin: /\[.+?\]\[.*?\]/,
        relevance: 0
      },
      // popular internet URLs
      {
        begin: /\[.+?\]\(((data|javascript|mailto):|(?:http|ftp)s?:\/\/).*?\)/,
        relevance: 2
      },
      {
        begin: regex.concat(/\[.+?\]\(/, URL_SCHEME, /:\/\/.*?\)/),
        relevance: 2
      },
      // relative urls
      {
        begin: /\[.+?\]\([./?&#].*?\)/,
        relevance: 1
      },
      // whatever else, lower relevance (might not be a link at all)
      {
        begin: /\[.*?\]\(.*?\)/,
        relevance: 0
      }
    ],
    returnBegin: true,
    contains: [
      {
        // empty strings for alt or link text
        match: /\[(?=\])/
      },
      {
        className: "string",
        relevance: 0,
        begin: "\\[",
        end: "\\]",
        excludeBegin: true,
        returnEnd: true
      },
      {
        className: "link",
        relevance: 0,
        begin: "\\]\\(",
        end: "\\)",
        excludeBegin: true,
        excludeEnd: true
      },
      {
        className: "symbol",
        relevance: 0,
        begin: "\\]\\[",
        end: "\\]",
        excludeBegin: true,
        excludeEnd: true
      }
    ]
  };
  const BOLD = {
    className: "strong",
    contains: [],
    // defined later
    variants: [
      {
        begin: /_{2}(?!\s)/,
        end: /_{2}/
      },
      {
        begin: /\*{2}(?!\s)/,
        end: /\*{2}/
      }
    ]
  };
  const ITALIC = {
    className: "emphasis",
    contains: [],
    // defined later
    variants: [
      {
        begin: /\*(?![*\s])/,
        end: /\*/
      },
      {
        begin: /_(?![_\s])/,
        end: /_/,
        relevance: 0
      }
    ]
  };
  const BOLD_WITHOUT_ITALIC = hljs.inherit(BOLD, { contains: [] });
  const ITALIC_WITHOUT_BOLD = hljs.inherit(ITALIC, { contains: [] });
  BOLD.contains.push(ITALIC_WITHOUT_BOLD);
  ITALIC.contains.push(BOLD_WITHOUT_ITALIC);
  let CONTAINABLE = [
    INLINE_HTML,
    LINK
  ];
  [
    BOLD,
    ITALIC,
    BOLD_WITHOUT_ITALIC,
    ITALIC_WITHOUT_BOLD
  ].forEach((m) => {
    m.contains = m.contains.concat(CONTAINABLE);
  });
  CONTAINABLE = CONTAINABLE.concat(BOLD, ITALIC);
  const HEADER = {
    className: "section",
    variants: [
      {
        begin: "^#{1,6}",
        end: "$",
        contains: CONTAINABLE
      },
      {
        begin: "(?=^.+?\\n[=-]{2,}$)",
        contains: [
          { begin: "^[=-]*$" },
          {
            begin: "^",
            end: "\\n",
            contains: CONTAINABLE
          }
        ]
      }
    ]
  };
  const BLOCKQUOTE = {
    className: "quote",
    begin: "^>\\s+",
    contains: CONTAINABLE,
    end: "$"
  };
  const ENTITY = {
    //https://spec.commonmark.org/0.31.2/#entity-references
    scope: "literal",
    match: /&([a-zA-Z0-9]+|#[0-9]{1,7}|#[Xx][0-9a-fA-F]{1,6});/
  };
  return {
    name: "Markdown",
    aliases: [
      "md",
      "mkdown",
      "mkd"
    ],
    contains: [
      HEADER,
      INLINE_HTML,
      LIST,
      BOLD,
      ITALIC,
      BLOCKQUOTE,
      CODE,
      HORIZONTAL_RULE,
      LINK,
      LINK_REFERENCE,
      ENTITY
    ]
  };
}

// node_modules/highlight.js/es/languages/objectivec.js
function objectivec(hljs) {
  const API_CLASS = {
    className: "built_in",
    begin: "\\b(AV|CA|CF|CG|CI|CL|CM|CN|CT|MK|MP|MTK|MTL|NS|SCN|SK|UI|WK|XC)\\w+"
  };
  const IDENTIFIER_RE = /[a-zA-Z@][a-zA-Z0-9_]*/;
  const TYPES3 = [
    "int",
    "float",
    "char",
    "unsigned",
    "signed",
    "short",
    "long",
    "double",
    "wchar_t",
    "unichar",
    "void",
    "bool",
    "BOOL",
    "id|0",
    "_Bool"
  ];
  const KWS = [
    "while",
    "export",
    "sizeof",
    "typedef",
    "const",
    "struct",
    "for",
    "union",
    "volatile",
    "static",
    "mutable",
    "if",
    "do",
    "return",
    "goto",
    "enum",
    "else",
    "break",
    "extern",
    "asm",
    "case",
    "default",
    "register",
    "explicit",
    "typename",
    "switch",
    "continue",
    "inline",
    "readonly",
    "assign",
    "readwrite",
    "self",
    "@synchronized",
    "id",
    "typeof",
    "nonatomic",
    "IBOutlet",
    "IBAction",
    "strong",
    "weak",
    "copy",
    "in",
    "out",
    "inout",
    "bycopy",
    "byref",
    "oneway",
    "__strong",
    "__weak",
    "__block",
    "__autoreleasing",
    "@private",
    "@protected",
    "@public",
    "@try",
    "@property",
    "@end",
    "@throw",
    "@catch",
    "@finally",
    "@autoreleasepool",
    "@synthesize",
    "@dynamic",
    "@selector",
    "@optional",
    "@required",
    "@encode",
    "@package",
    "@import",
    "@defs",
    "@compatibility_alias",
    "__bridge",
    "__bridge_transfer",
    "__bridge_retained",
    "__bridge_retain",
    "__covariant",
    "__contravariant",
    "__kindof",
    "_Nonnull",
    "_Nullable",
    "_Null_unspecified",
    "__FUNCTION__",
    "__PRETTY_FUNCTION__",
    "__attribute__",
    "getter",
    "setter",
    "retain",
    "unsafe_unretained",
    "nonnull",
    "nullable",
    "null_unspecified",
    "null_resettable",
    "class",
    "instancetype",
    "NS_DESIGNATED_INITIALIZER",
    "NS_UNAVAILABLE",
    "NS_REQUIRES_SUPER",
    "NS_RETURNS_INNER_POINTER",
    "NS_INLINE",
    "NS_AVAILABLE",
    "NS_DEPRECATED",
    "NS_ENUM",
    "NS_OPTIONS",
    "NS_SWIFT_UNAVAILABLE",
    "NS_ASSUME_NONNULL_BEGIN",
    "NS_ASSUME_NONNULL_END",
    "NS_REFINED_FOR_SWIFT",
    "NS_SWIFT_NAME",
    "NS_SWIFT_NOTHROW",
    "NS_DURING",
    "NS_HANDLER",
    "NS_ENDHANDLER",
    "NS_VALUERETURN",
    "NS_VOIDRETURN"
  ];
  const LITERALS3 = [
    "false",
    "true",
    "FALSE",
    "TRUE",
    "nil",
    "YES",
    "NO",
    "NULL"
  ];
  const BUILT_INS3 = [
    "dispatch_once_t",
    "dispatch_queue_t",
    "dispatch_sync",
    "dispatch_async",
    "dispatch_once"
  ];
  const KEYWORDS3 = {
    "variable.language": [
      "this",
      "super"
    ],
    $pattern: IDENTIFIER_RE,
    keyword: KWS,
    literal: LITERALS3,
    built_in: BUILT_INS3,
    type: TYPES3
  };
  const CLASS_KEYWORDS = {
    $pattern: IDENTIFIER_RE,
    keyword: [
      "@interface",
      "@class",
      "@protocol",
      "@implementation"
    ]
  };
  return {
    name: "Objective-C",
    aliases: [
      "mm",
      "objc",
      "obj-c",
      "obj-c++",
      "objective-c++"
    ],
    keywords: KEYWORDS3,
    illegal: "</",
    contains: [
      API_CLASS,
      hljs.C_LINE_COMMENT_MODE,
      hljs.C_BLOCK_COMMENT_MODE,
      hljs.C_NUMBER_MODE,
      hljs.QUOTE_STRING_MODE,
      hljs.APOS_STRING_MODE,
      {
        className: "string",
        variants: [
          {
            begin: '@"',
            end: '"',
            illegal: "\\n",
            contains: [hljs.BACKSLASH_ESCAPE]
          }
        ]
      },
      {
        className: "meta",
        begin: /#\s*[a-z]+\b/,
        end: /$/,
        keywords: { keyword: "if else elif endif define undef warning error line pragma ifdef ifndef include" },
        contains: [
          {
            begin: /\\\n/,
            relevance: 0
          },
          hljs.inherit(hljs.QUOTE_STRING_MODE, { className: "string" }),
          {
            className: "string",
            begin: /<.*?>/,
            end: /$/,
            illegal: "\\n"
          },
          hljs.C_LINE_COMMENT_MODE,
          hljs.C_BLOCK_COMMENT_MODE
        ]
      },
      {
        className: "class",
        begin: "(" + CLASS_KEYWORDS.keyword.join("|") + ")\\b",
        end: /(\{|$)/,
        excludeEnd: true,
        keywords: CLASS_KEYWORDS,
        contains: [hljs.UNDERSCORE_TITLE_MODE]
      },
      {
        begin: "\\." + hljs.UNDERSCORE_IDENT_RE,
        relevance: 0
      }
    ]
  };
}

// node_modules/highlight.js/es/languages/perl.js
function perl(hljs) {
  const regex = hljs.regex;
  const KEYWORDS3 = [
    "abs",
    "accept",
    "alarm",
    "and",
    "atan2",
    "bind",
    "binmode",
    "bless",
    "break",
    "caller",
    "chdir",
    "chmod",
    "chomp",
    "chop",
    "chown",
    "chr",
    "chroot",
    "class",
    "close",
    "closedir",
    "connect",
    "continue",
    "cos",
    "crypt",
    "dbmclose",
    "dbmopen",
    "defined",
    "delete",
    "die",
    "do",
    "dump",
    "each",
    "else",
    "elsif",
    "endgrent",
    "endhostent",
    "endnetent",
    "endprotoent",
    "endpwent",
    "endservent",
    "eof",
    "eval",
    "exec",
    "exists",
    "exit",
    "exp",
    "fcntl",
    "field",
    "fileno",
    "flock",
    "for",
    "foreach",
    "fork",
    "format",
    "formline",
    "getc",
    "getgrent",
    "getgrgid",
    "getgrnam",
    "gethostbyaddr",
    "gethostbyname",
    "gethostent",
    "getlogin",
    "getnetbyaddr",
    "getnetbyname",
    "getnetent",
    "getpeername",
    "getpgrp",
    "getpriority",
    "getprotobyname",
    "getprotobynumber",
    "getprotoent",
    "getpwent",
    "getpwnam",
    "getpwuid",
    "getservbyname",
    "getservbyport",
    "getservent",
    "getsockname",
    "getsockopt",
    "given",
    "glob",
    "gmtime",
    "goto",
    "grep",
    "gt",
    "hex",
    "if",
    "index",
    "int",
    "ioctl",
    "join",
    "keys",
    "kill",
    "last",
    "lc",
    "lcfirst",
    "length",
    "link",
    "listen",
    "local",
    "localtime",
    "log",
    "lstat",
    "lt",
    "ma",
    "map",
    "method",
    "mkdir",
    "msgctl",
    "msgget",
    "msgrcv",
    "msgsnd",
    "my",
    "ne",
    "next",
    "no",
    "not",
    "oct",
    "open",
    "opendir",
    "or",
    "ord",
    "our",
    "pack",
    "package",
    "pipe",
    "pop",
    "pos",
    "print",
    "printf",
    "prototype",
    "push",
    "q|0",
    "qq",
    "quotemeta",
    "qw",
    "qx",
    "rand",
    "read",
    "readdir",
    "readline",
    "readlink",
    "readpipe",
    "recv",
    "redo",
    "ref",
    "rename",
    "require",
    "reset",
    "return",
    "reverse",
    "rewinddir",
    "rindex",
    "rmdir",
    "say",
    "scalar",
    "seek",
    "seekdir",
    "select",
    "semctl",
    "semget",
    "semop",
    "send",
    "setgrent",
    "sethostent",
    "setnetent",
    "setpgrp",
    "setpriority",
    "setprotoent",
    "setpwent",
    "setservent",
    "setsockopt",
    "shift",
    "shmctl",
    "shmget",
    "shmread",
    "shmwrite",
    "shutdown",
    "sin",
    "sleep",
    "socket",
    "socketpair",
    "sort",
    "splice",
    "split",
    "sprintf",
    "sqrt",
    "srand",
    "stat",
    "state",
    "study",
    "sub",
    "substr",
    "symlink",
    "syscall",
    "sysopen",
    "sysread",
    "sysseek",
    "system",
    "syswrite",
    "tell",
    "telldir",
    "tie",
    "tied",
    "time",
    "times",
    "tr",
    "truncate",
    "uc",
    "ucfirst",
    "umask",
    "undef",
    "unless",
    "unlink",
    "unpack",
    "unshift",
    "untie",
    "until",
    "use",
    "utime",
    "values",
    "vec",
    "wait",
    "waitpid",
    "wantarray",
    "warn",
    "when",
    "while",
    "write",
    "x|0",
    "xor",
    "y|0"
  ];
  const REGEX_MODIFIERS = /[dualxmsipngr]{0,12}/;
  const PERL_KEYWORDS = {
    $pattern: /[\w.]+/,
    keyword: KEYWORDS3.join(" ")
  };
  const SUBST = {
    className: "subst",
    begin: "[$@]\\{",
    end: "\\}",
    keywords: PERL_KEYWORDS
  };
  const METHOD = {
    begin: /->\{/,
    end: /\}/
    // contains defined later
  };
  const ATTR = {
    scope: "attr",
    match: /\s+:\s*\w+(\s*\(.*?\))?/
  };
  const VAR = {
    scope: "variable",
    variants: [
      { begin: /\$\d/ },
      {
        begin: regex.concat(
          /[$%@](?!")(\^\w\b|#\w+(::\w+)*|\{\w+\}|\w+(::\w*)*)/,
          // negative look-ahead tries to avoid matching patterns that are not
          // Perl at all like $ident$, @ident@, etc.
          `(?![A-Za-z])(?![@$%])`
        )
      },
      {
        // Only $= is a special Perl variable and one can't declare @= or %=.
        begin: /[$%@](?!")[^\s\w{=]|\$=/,
        relevance: 0
      }
    ],
    contains: [ATTR]
  };
  const NUMBER = {
    className: "number",
    variants: [
      // decimal numbers:
      // include the case where a number starts with a dot (eg. .9), and
      // the leading 0? avoids mixing the first and second match on 0.x cases
      { match: /0?\.[0-9][0-9_]+\b/ },
      // include the special versioned number (eg. v5.38)
      { match: /\bv?(0|[1-9][0-9_]*(\.[0-9_]+)?|[1-9][0-9_]*)\b/ },
      // non-decimal numbers:
      { match: /\b0[0-7][0-7_]*\b/ },
      { match: /\b0x[0-9a-fA-F][0-9a-fA-F_]*\b/ },
      { match: /\b0b[0-1][0-1_]*\b/ }
    ],
    relevance: 0
  };
  const STRING_CONTAINS = [
    hljs.BACKSLASH_ESCAPE,
    SUBST,
    VAR
  ];
  const REGEX_DELIMS = [
    /!/,
    /\//,
    /\|/,
    /\?/,
    /'/,
    /"/,
    // valid but infrequent and weird
    /#/
    // valid but infrequent and weird
  ];
  const PAIRED_DOUBLE_RE = (prefix, open, close = "\\1") => {
    const middle = close === "\\1" ? close : regex.concat(close, open);
    return regex.concat(
      regex.concat("(?:", prefix, ")"),
      open,
      /(?:\\.|[^\\\/])*?/,
      middle,
      /(?:\\.|[^\\\/])*?/,
      close,
      REGEX_MODIFIERS
    );
  };
  const PAIRED_RE = (prefix, open, close) => {
    return regex.concat(
      regex.concat("(?:", prefix, ")"),
      open,
      /(?:\\.|[^\\\/])*?/,
      close,
      REGEX_MODIFIERS
    );
  };
  const PERL_DEFAULT_CONTAINS = [
    VAR,
    hljs.HASH_COMMENT_MODE,
    hljs.COMMENT(
      /^=\w/,
      /=cut/,
      { endsWithParent: true }
    ),
    METHOD,
    {
      className: "string",
      contains: STRING_CONTAINS,
      variants: [
        {
          begin: "q[qwxr]?\\s*\\(",
          end: "\\)",
          relevance: 5
        },
        {
          begin: "q[qwxr]?\\s*\\[",
          end: "\\]",
          relevance: 5
        },
        {
          begin: "q[qwxr]?\\s*\\{",
          end: "\\}",
          relevance: 5
        },
        {
          begin: "q[qwxr]?\\s*\\|",
          end: "\\|",
          relevance: 5
        },
        {
          begin: "q[qwxr]?\\s*<",
          end: ">",
          relevance: 5
        },
        {
          begin: "qw\\s+q",
          end: "q",
          relevance: 5
        },
        {
          begin: "'",
          end: "'",
          contains: [hljs.BACKSLASH_ESCAPE]
        },
        {
          begin: '"',
          end: '"'
        },
        {
          begin: "`",
          end: "`",
          contains: [hljs.BACKSLASH_ESCAPE]
        },
        {
          begin: /\{\w+\}/,
          relevance: 0
        },
        {
          begin: "-?\\w+\\s*=>",
          relevance: 0
        }
      ]
    },
    NUMBER,
    {
      // regexp container
      begin: "(\\/\\/|" + hljs.RE_STARTERS_RE + "|\\b(split|return|print|reverse|grep)\\b)\\s*",
      keywords: "split return print reverse grep",
      relevance: 0,
      contains: [
        hljs.HASH_COMMENT_MODE,
        {
          className: "regexp",
          variants: [
            // allow matching common delimiters
            { begin: PAIRED_DOUBLE_RE("s|tr|y", regex.either(...REGEX_DELIMS, { capture: true })) },
            // and then paired delmis
            { begin: PAIRED_DOUBLE_RE("s|tr|y", "\\(", "\\)") },
            { begin: PAIRED_DOUBLE_RE("s|tr|y", "\\[", "\\]") },
            { begin: PAIRED_DOUBLE_RE("s|tr|y", "\\{", "\\}") }
          ],
          relevance: 2
        },
        {
          className: "regexp",
          variants: [
            {
              // could be a comment in many languages so do not count
              // as relevant
              begin: /(m|qr)\/\//,
              relevance: 0
            },
            // prefix is optional with /regex/
            { begin: PAIRED_RE("(?:m|qr)?", /\//, /\//) },
            // allow matching common delimiters
            { begin: PAIRED_RE("m|qr", regex.either(...REGEX_DELIMS, { capture: true }), /\1/) },
            // allow common paired delmins
            { begin: PAIRED_RE("m|qr", /\(/, /\)/) },
            { begin: PAIRED_RE("m|qr", /\[/, /\]/) },
            { begin: PAIRED_RE("m|qr", /\{/, /\}/) }
          ]
        }
      ]
    },
    {
      className: "function",
      beginKeywords: "sub method",
      end: "(\\s*\\(.*?\\))?[;{]",
      excludeEnd: true,
      relevance: 5,
      contains: [hljs.TITLE_MODE, ATTR]
    },
    {
      className: "class",
      beginKeywords: "class",
      end: "[;{]",
      excludeEnd: true,
      relevance: 5,
      contains: [hljs.TITLE_MODE, ATTR, NUMBER]
    },
    {
      begin: "-\\w\\b",
      relevance: 0
    },
    {
      begin: "^__DATA__$",
      end: "^__END__$",
      subLanguage: "mojolicious",
      contains: [
        {
          begin: "^@@.*",
          end: "$",
          className: "comment"
        }
      ]
    }
  ];
  SUBST.contains = PERL_DEFAULT_CONTAINS;
  METHOD.contains = PERL_DEFAULT_CONTAINS;
  return {
    name: "Perl",
    aliases: [
      "pl",
      "pm"
    ],
    keywords: PERL_KEYWORDS,
    contains: PERL_DEFAULT_CONTAINS
  };
}

// node_modules/highlight.js/es/languages/php.js
function php(hljs) {
  const regex = hljs.regex;
  const NOT_PERL_ETC = /(?![A-Za-z0-9])(?![$])/;
  const IDENT_RE3 = regex.concat(
    /[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/,
    NOT_PERL_ETC
  );
  const PASCAL_CASE_CLASS_NAME_RE = regex.concat(
    /(\\?[A-Z][a-z0-9_\x7f-\xff]+|\\?[A-Z]+(?=[A-Z][a-z0-9_\x7f-\xff])){1,}/,
    NOT_PERL_ETC
  );
  const UPCASE_NAME_RE = regex.concat(
    /[A-Z]+/,
    NOT_PERL_ETC
  );
  const VARIABLE = {
    scope: "variable",
    match: "\\$+" + IDENT_RE3
  };
  const PREPROCESSOR = {
    scope: "meta",
    variants: [
      { begin: /<\?php/, relevance: 10 },
      // boost for obvious PHP
      { begin: /<\?=/ },
      // less relevant per PSR-1 which says not to use short-tags
      { begin: /<\?/, relevance: 0.1 },
      { begin: /\?>/ }
      // end php tag
    ]
  };
  const SUBST = {
    scope: "subst",
    variants: [
      { begin: /\$\w+/ },
      {
        begin: /\{\$/,
        end: /\}/
      }
    ]
  };
  const SINGLE_QUOTED = hljs.inherit(hljs.APOS_STRING_MODE, { illegal: null });
  const DOUBLE_QUOTED = hljs.inherit(hljs.QUOTE_STRING_MODE, {
    illegal: null,
    contains: hljs.QUOTE_STRING_MODE.contains.concat(SUBST)
  });
  const HEREDOC = {
    begin: /<<<[ \t]*(?:(\w+)|"(\w+)")\n/,
    end: /[ \t]*(\w+)\b/,
    contains: hljs.QUOTE_STRING_MODE.contains.concat(SUBST),
    "on:begin": (m, resp) => {
      resp.data._beginMatch = m[1] || m[2];
    },
    "on:end": (m, resp) => {
      if (resp.data._beginMatch !== m[1]) resp.ignoreMatch();
    }
  };
  const NOWDOC = hljs.END_SAME_AS_BEGIN({
    begin: /<<<[ \t]*'(\w+)'\n/,
    end: /[ \t]*(\w+)\b/
  });
  const WHITESPACE = "[ 	\n]";
  const STRING = {
    scope: "string",
    variants: [
      DOUBLE_QUOTED,
      SINGLE_QUOTED,
      HEREDOC,
      NOWDOC
    ]
  };
  const NUMBER = {
    scope: "number",
    variants: [
      { begin: `\\b0[bB][01]+(?:_[01]+)*\\b` },
      // Binary w/ underscore support
      { begin: `\\b0[oO][0-7]+(?:_[0-7]+)*\\b` },
      // Octals w/ underscore support
      { begin: `\\b0[xX][\\da-fA-F]+(?:_[\\da-fA-F]+)*\\b` },
      // Hex w/ underscore support
      // Decimals w/ underscore support, with optional fragments and scientific exponent (e) suffix.
      { begin: `(?:\\b\\d+(?:_\\d+)*(\\.(?:\\d+(?:_\\d+)*))?|\\B\\.\\d+)(?:[eE][+-]?\\d+)?` }
    ],
    relevance: 0
  };
  const LITERALS3 = [
    "false",
    "null",
    "true"
  ];
  const KWS = [
    // Magic constants:
    // <https://www.php.net/manual/en/language.constants.predefined.php>
    "__CLASS__",
    "__DIR__",
    "__FILE__",
    "__FUNCTION__",
    "__COMPILER_HALT_OFFSET__",
    "__LINE__",
    "__METHOD__",
    "__NAMESPACE__",
    "__TRAIT__",
    // Function that look like language construct or language construct that look like function:
    // List of keywords that may not require parenthesis
    "die",
    "echo",
    "exit",
    "include",
    "include_once",
    "print",
    "require",
    "require_once",
    // These are not language construct (function) but operate on the currently-executing function and can access the current symbol table
    // 'compact extract func_get_arg func_get_args func_num_args get_called_class get_parent_class ' +
    // Other keywords:
    // <https://www.php.net/manual/en/reserved.php>
    // <https://www.php.net/manual/en/language.types.type-juggling.php>
    "array",
    "abstract",
    "and",
    "as",
    "binary",
    "bool",
    "boolean",
    "break",
    "callable",
    "case",
    "catch",
    "class",
    "clone",
    "const",
    "continue",
    "declare",
    "default",
    "do",
    "double",
    "else",
    "elseif",
    "empty",
    "enddeclare",
    "endfor",
    "endforeach",
    "endif",
    "endswitch",
    "endwhile",
    "enum",
    "eval",
    "extends",
    "final",
    "finally",
    "float",
    "for",
    "foreach",
    "from",
    "global",
    "goto",
    "if",
    "implements",
    "instanceof",
    "insteadof",
    "int",
    "integer",
    "interface",
    "isset",
    "iterable",
    "list",
    "match|0",
    "mixed",
    "new",
    "never",
    "object",
    "or",
    "private",
    "protected",
    "public",
    "readonly",
    "real",
    "return",
    "string",
    "switch",
    "throw",
    "trait",
    "try",
    "unset",
    "use",
    "var",
    "void",
    "while",
    "xor",
    "yield"
  ];
  const BUILT_INS3 = [
    // Standard PHP library:
    // <https://www.php.net/manual/en/book.spl.php>
    "Error|0",
    "AppendIterator",
    "ArgumentCountError",
    "ArithmeticError",
    "ArrayIterator",
    "ArrayObject",
    "AssertionError",
    "BadFunctionCallException",
    "BadMethodCallException",
    "CachingIterator",
    "CallbackFilterIterator",
    "CompileError",
    "Countable",
    "DirectoryIterator",
    "DivisionByZeroError",
    "DomainException",
    "EmptyIterator",
    "ErrorException",
    "Exception",
    "FilesystemIterator",
    "FilterIterator",
    "GlobIterator",
    "InfiniteIterator",
    "InvalidArgumentException",
    "IteratorIterator",
    "LengthException",
    "LimitIterator",
    "LogicException",
    "MultipleIterator",
    "NoRewindIterator",
    "OutOfBoundsException",
    "OutOfRangeException",
    "OuterIterator",
    "OverflowException",
    "ParentIterator",
    "ParseError",
    "RangeException",
    "RecursiveArrayIterator",
    "RecursiveCachingIterator",
    "RecursiveCallbackFilterIterator",
    "RecursiveDirectoryIterator",
    "RecursiveFilterIterator",
    "RecursiveIterator",
    "RecursiveIteratorIterator",
    "RecursiveRegexIterator",
    "RecursiveTreeIterator",
    "RegexIterator",
    "RuntimeException",
    "SeekableIterator",
    "SplDoublyLinkedList",
    "SplFileInfo",
    "SplFileObject",
    "SplFixedArray",
    "SplHeap",
    "SplMaxHeap",
    "SplMinHeap",
    "SplObjectStorage",
    "SplObserver",
    "SplPriorityQueue",
    "SplQueue",
    "SplStack",
    "SplSubject",
    "SplTempFileObject",
    "TypeError",
    "UnderflowException",
    "UnexpectedValueException",
    "UnhandledMatchError",
    // Reserved interfaces:
    // <https://www.php.net/manual/en/reserved.interfaces.php>
    "ArrayAccess",
    "BackedEnum",
    "Closure",
    "Fiber",
    "Generator",
    "Iterator",
    "IteratorAggregate",
    "Serializable",
    "Stringable",
    "Throwable",
    "Traversable",
    "UnitEnum",
    "WeakReference",
    "WeakMap",
    // Reserved classes:
    // <https://www.php.net/manual/en/reserved.classes.php>
    "Directory",
    "__PHP_Incomplete_Class",
    "parent",
    "php_user_filter",
    "self",
    "static",
    "stdClass"
  ];
  const dualCase = (items) => {
    const result = [];
    items.forEach((item) => {
      result.push(item);
      if (item.toLowerCase() === item) {
        result.push(item.toUpperCase());
      } else {
        result.push(item.toLowerCase());
      }
    });
    return result;
  };
  const KEYWORDS3 = {
    keyword: KWS,
    literal: dualCase(LITERALS3),
    built_in: BUILT_INS3
  };
  const normalizeKeywords = (items) => {
    return items.map((item) => {
      return item.replace(/\|\d+$/, "");
    });
  };
  const CONSTRUCTOR_CALL = { variants: [
    {
      match: [
        /new/,
        regex.concat(WHITESPACE, "+"),
        // to prevent built ins from being confused as the class constructor call
        regex.concat("(?!", normalizeKeywords(BUILT_INS3).join("\\b|"), "\\b)"),
        PASCAL_CASE_CLASS_NAME_RE
      ],
      scope: {
        1: "keyword",
        4: "title.class"
      }
    }
  ] };
  const CONSTANT_REFERENCE = regex.concat(IDENT_RE3, "\\b(?!\\()");
  const LEFT_AND_RIGHT_SIDE_OF_DOUBLE_COLON = { variants: [
    {
      match: [
        regex.concat(
          /::/,
          regex.lookahead(/(?!class\b)/)
        ),
        CONSTANT_REFERENCE
      ],
      scope: { 2: "variable.constant" }
    },
    {
      match: [
        /::/,
        /class/
      ],
      scope: { 2: "variable.language" }
    },
    {
      match: [
        PASCAL_CASE_CLASS_NAME_RE,
        regex.concat(
          /::/,
          regex.lookahead(/(?!class\b)/)
        ),
        CONSTANT_REFERENCE
      ],
      scope: {
        1: "title.class",
        3: "variable.constant"
      }
    },
    {
      match: [
        PASCAL_CASE_CLASS_NAME_RE,
        regex.concat(
          "::",
          regex.lookahead(/(?!class\b)/)
        )
      ],
      scope: { 1: "title.class" }
    },
    {
      match: [
        PASCAL_CASE_CLASS_NAME_RE,
        /::/,
        /class/
      ],
      scope: {
        1: "title.class",
        3: "variable.language"
      }
    }
  ] };
  const NAMED_ARGUMENT = {
    scope: "attr",
    match: regex.concat(IDENT_RE3, regex.lookahead(":"), regex.lookahead(/(?!::)/))
  };
  const PARAMS_MODE = {
    relevance: 0,
    begin: /\(/,
    end: /\)/,
    keywords: KEYWORDS3,
    contains: [
      NAMED_ARGUMENT,
      VARIABLE,
      LEFT_AND_RIGHT_SIDE_OF_DOUBLE_COLON,
      hljs.C_BLOCK_COMMENT_MODE,
      STRING,
      NUMBER,
      CONSTRUCTOR_CALL
    ]
  };
  const FUNCTION_INVOKE = {
    relevance: 0,
    match: [
      /\b/,
      // to prevent keywords from being confused as the function title
      regex.concat("(?!fn\\b|function\\b|", normalizeKeywords(KWS).join("\\b|"), "|", normalizeKeywords(BUILT_INS3).join("\\b|"), "\\b)"),
      IDENT_RE3,
      regex.concat(WHITESPACE, "*"),
      regex.lookahead(/(?=\()/)
    ],
    scope: { 3: "title.function.invoke" },
    contains: [PARAMS_MODE]
  };
  PARAMS_MODE.contains.push(FUNCTION_INVOKE);
  const ATTRIBUTE_CONTAINS = [
    NAMED_ARGUMENT,
    LEFT_AND_RIGHT_SIDE_OF_DOUBLE_COLON,
    hljs.C_BLOCK_COMMENT_MODE,
    STRING,
    NUMBER,
    CONSTRUCTOR_CALL
  ];
  const ATTRIBUTES4 = {
    begin: regex.concat(
      /#\[\s*\\?/,
      regex.either(
        PASCAL_CASE_CLASS_NAME_RE,
        UPCASE_NAME_RE
      )
    ),
    beginScope: "meta",
    end: /]/,
    endScope: "meta",
    keywords: {
      literal: LITERALS3,
      keyword: [
        "new",
        "array"
      ]
    },
    contains: [
      {
        begin: /\[/,
        end: /]/,
        keywords: {
          literal: LITERALS3,
          keyword: [
            "new",
            "array"
          ]
        },
        contains: [
          "self",
          ...ATTRIBUTE_CONTAINS
        ]
      },
      ...ATTRIBUTE_CONTAINS,
      {
        scope: "meta",
        variants: [
          { match: PASCAL_CASE_CLASS_NAME_RE },
          { match: UPCASE_NAME_RE }
        ]
      }
    ]
  };
  return {
    case_insensitive: false,
    keywords: KEYWORDS3,
    contains: [
      ATTRIBUTES4,
      hljs.HASH_COMMENT_MODE,
      hljs.COMMENT("//", "$"),
      hljs.COMMENT(
        "/\\*",
        "\\*/",
        { contains: [
          {
            scope: "doctag",
            match: "@[A-Za-z]+"
          }
        ] }
      ),
      {
        match: /__halt_compiler\(\);/,
        keywords: "__halt_compiler",
        starts: {
          scope: "comment",
          end: hljs.MATCH_NOTHING_RE,
          contains: [
            {
              match: /\?>/,
              scope: "meta",
              endsParent: true
            }
          ]
        }
      },
      PREPROCESSOR,
      {
        scope: "variable.language",
        match: /\$this\b/
      },
      VARIABLE,
      FUNCTION_INVOKE,
      LEFT_AND_RIGHT_SIDE_OF_DOUBLE_COLON,
      {
        match: [
          /const/,
          /\s/,
          IDENT_RE3
        ],
        scope: {
          1: "keyword",
          3: "variable.constant"
        }
      },
      CONSTRUCTOR_CALL,
      {
        scope: "function",
        relevance: 0,
        beginKeywords: "fn function",
        end: /[;{]/,
        excludeEnd: true,
        illegal: "[$%\\[]",
        contains: [
          { beginKeywords: "use" },
          hljs.UNDERSCORE_TITLE_MODE,
          {
            begin: "=>",
            // No markup, just a relevance booster
            endsParent: true
          },
          {
            scope: "params",
            begin: "\\(",
            end: "\\)",
            excludeBegin: true,
            excludeEnd: true,
            keywords: KEYWORDS3,
            contains: [
              "self",
              ATTRIBUTES4,
              VARIABLE,
              LEFT_AND_RIGHT_SIDE_OF_DOUBLE_COLON,
              hljs.C_BLOCK_COMMENT_MODE,
              STRING,
              NUMBER
            ]
          }
        ]
      },
      {
        scope: "class",
        variants: [
          {
            beginKeywords: "enum",
            illegal: /[($"]/
          },
          {
            beginKeywords: "class interface trait",
            illegal: /[:($"]/
          }
        ],
        relevance: 0,
        end: /\{/,
        excludeEnd: true,
        contains: [
          { beginKeywords: "extends implements" },
          hljs.UNDERSCORE_TITLE_MODE
        ]
      },
      // both use and namespace still use "old style" rules (vs multi-match)
      // because the namespace name can include `\` and we still want each
      // element to be treated as its own *individual* title
      {
        beginKeywords: "namespace",
        relevance: 0,
        end: ";",
        illegal: /[.']/,
        contains: [hljs.inherit(hljs.UNDERSCORE_TITLE_MODE, { scope: "title.class" })]
      },
      {
        beginKeywords: "use",
        relevance: 0,
        end: ";",
        contains: [
          // TODO: title.function vs title.class
          {
            match: /\b(as|const|function)\b/,
            scope: "keyword"
          },
          // TODO: could be title.class or title.function
          hljs.UNDERSCORE_TITLE_MODE
        ]
      },
      STRING,
      NUMBER
    ]
  };
}

// node_modules/highlight.js/es/languages/php-template.js
function phpTemplate(hljs) {
  return {
    name: "PHP template",
    subLanguage: "xml",
    contains: [
      {
        begin: /<\?(php|=)?/,
        end: /\?>/,
        subLanguage: "php",
        contains: [
          // We don't want the php closing tag ?> to close the PHP block when
          // inside any of the following blocks:
          {
            begin: "/\\*",
            end: "\\*/",
            skip: true
          },
          {
            begin: 'b"',
            end: '"',
            skip: true
          },
          {
            begin: "b'",
            end: "'",
            skip: true
          },
          hljs.inherit(hljs.APOS_STRING_MODE, {
            illegal: null,
            className: null,
            contains: null,
            skip: true
          }),
          hljs.inherit(hljs.QUOTE_STRING_MODE, {
            illegal: null,
            className: null,
            contains: null,
            skip: true
          })
        ]
      }
    ]
  };
}

// node_modules/highlight.js/es/languages/plaintext.js
function plaintext(hljs) {
  return {
    name: "Plain text",
    aliases: [
      "text",
      "txt"
    ],
    disableAutodetect: true
  };
}

// node_modules/highlight.js/es/languages/python.js
function python(hljs) {
  const regex = hljs.regex;
  const IDENT_RE3 = /[\p{XID_Start}_]\p{XID_Continue}*/u;
  const RESERVED_WORDS = [
    "and",
    "as",
    "assert",
    "async",
    "await",
    "break",
    "case",
    "class",
    "continue",
    "def",
    "del",
    "elif",
    "else",
    "except",
    "finally",
    "for",
    "from",
    "global",
    "if",
    "import",
    "in",
    "is",
    "lambda",
    "match",
    "nonlocal|10",
    "not",
    "or",
    "pass",
    "raise",
    "return",
    "try",
    "while",
    "with",
    "yield"
  ];
  const BUILT_INS3 = [
    "__import__",
    "abs",
    "all",
    "any",
    "ascii",
    "bin",
    "bool",
    "breakpoint",
    "bytearray",
    "bytes",
    "callable",
    "chr",
    "classmethod",
    "compile",
    "complex",
    "delattr",
    "dict",
    "dir",
    "divmod",
    "enumerate",
    "eval",
    "exec",
    "filter",
    "float",
    "format",
    "frozenset",
    "getattr",
    "globals",
    "hasattr",
    "hash",
    "help",
    "hex",
    "id",
    "input",
    "int",
    "isinstance",
    "issubclass",
    "iter",
    "len",
    "list",
    "locals",
    "map",
    "max",
    "memoryview",
    "min",
    "next",
    "object",
    "oct",
    "open",
    "ord",
    "pow",
    "print",
    "property",
    "range",
    "repr",
    "reversed",
    "round",
    "set",
    "setattr",
    "slice",
    "sorted",
    "staticmethod",
    "str",
    "sum",
    "super",
    "tuple",
    "type",
    "vars",
    "zip"
  ];
  const LITERALS3 = [
    "__debug__",
    "Ellipsis",
    "False",
    "None",
    "NotImplemented",
    "True"
  ];
  const TYPES3 = [
    "Any",
    "Callable",
    "Coroutine",
    "Dict",
    "List",
    "Literal",
    "Generic",
    "Optional",
    "Sequence",
    "Set",
    "Tuple",
    "Type",
    "Union"
  ];
  const KEYWORDS3 = {
    $pattern: /[A-Za-z]\w+|__\w+__/,
    keyword: RESERVED_WORDS,
    built_in: BUILT_INS3,
    literal: LITERALS3,
    type: TYPES3
  };
  const PROMPT = {
    className: "meta",
    begin: /^(>>>|\.\.\.) /
  };
  const SUBST = {
    className: "subst",
    begin: /\{/,
    end: /\}/,
    keywords: KEYWORDS3,
    illegal: /#/
  };
  const LITERAL_BRACKET = {
    begin: /\{\{/,
    relevance: 0
  };
  const STRING = {
    className: "string",
    contains: [hljs.BACKSLASH_ESCAPE],
    variants: [
      {
        begin: /([uU]|[bB]|[rR]|[bB][rR]|[rR][bB])?'''/,
        end: /'''/,
        contains: [
          hljs.BACKSLASH_ESCAPE,
          PROMPT
        ],
        relevance: 10
      },
      {
        begin: /([uU]|[bB]|[rR]|[bB][rR]|[rR][bB])?"""/,
        end: /"""/,
        contains: [
          hljs.BACKSLASH_ESCAPE,
          PROMPT
        ],
        relevance: 10
      },
      {
        begin: /([fF][rR]|[rR][fF]|[fF])'''/,
        end: /'''/,
        contains: [
          hljs.BACKSLASH_ESCAPE,
          PROMPT,
          LITERAL_BRACKET,
          SUBST
        ]
      },
      {
        begin: /([fF][rR]|[rR][fF]|[fF])"""/,
        end: /"""/,
        contains: [
          hljs.BACKSLASH_ESCAPE,
          PROMPT,
          LITERAL_BRACKET,
          SUBST
        ]
      },
      {
        begin: /([uU]|[rR])'/,
        end: /'/,
        relevance: 10
      },
      {
        begin: /([uU]|[rR])"/,
        end: /"/,
        relevance: 10
      },
      {
        begin: /([bB]|[bB][rR]|[rR][bB])'/,
        end: /'/
      },
      {
        begin: /([bB]|[bB][rR]|[rR][bB])"/,
        end: /"/
      },
      {
        begin: /([fF][rR]|[rR][fF]|[fF])'/,
        end: /'/,
        contains: [
          hljs.BACKSLASH_ESCAPE,
          LITERAL_BRACKET,
          SUBST
        ]
      },
      {
        begin: /([fF][rR]|[rR][fF]|[fF])"/,
        end: /"/,
        contains: [
          hljs.BACKSLASH_ESCAPE,
          LITERAL_BRACKET,
          SUBST
        ]
      },
      hljs.APOS_STRING_MODE,
      hljs.QUOTE_STRING_MODE
    ]
  };
  const digitpart = "[0-9](_?[0-9])*";
  const pointfloat = `(\\b(${digitpart}))?\\.(${digitpart})|\\b(${digitpart})\\.`;
  const lookahead2 = `\\b|${RESERVED_WORDS.join("|")}`;
  const NUMBER = {
    className: "number",
    relevance: 0,
    variants: [
      // exponentfloat, pointfloat
      // https://docs.python.org/3.9/reference/lexical_analysis.html#floating-point-literals
      // optionally imaginary
      // https://docs.python.org/3.9/reference/lexical_analysis.html#imaginary-literals
      // Note: no leading \b because floats can start with a decimal point
      // and we don't want to mishandle e.g. `fn(.5)`,
      // no trailing \b for pointfloat because it can end with a decimal point
      // and we don't want to mishandle e.g. `0..hex()`; this should be safe
      // because both MUST contain a decimal point and so cannot be confused with
      // the interior part of an identifier
      {
        begin: `(\\b(${digitpart})|(${pointfloat}))[eE][+-]?(${digitpart})[jJ]?(?=${lookahead2})`
      },
      {
        begin: `(${pointfloat})[jJ]?`
      },
      // decinteger, bininteger, octinteger, hexinteger
      // https://docs.python.org/3.9/reference/lexical_analysis.html#integer-literals
      // optionally "long" in Python 2
      // https://docs.python.org/2.7/reference/lexical_analysis.html#integer-and-long-integer-literals
      // decinteger is optionally imaginary
      // https://docs.python.org/3.9/reference/lexical_analysis.html#imaginary-literals
      {
        begin: `\\b([1-9](_?[0-9])*|0+(_?0)*)[lLjJ]?(?=${lookahead2})`
      },
      {
        begin: `\\b0[bB](_?[01])+[lL]?(?=${lookahead2})`
      },
      {
        begin: `\\b0[oO](_?[0-7])+[lL]?(?=${lookahead2})`
      },
      {
        begin: `\\b0[xX](_?[0-9a-fA-F])+[lL]?(?=${lookahead2})`
      },
      // imagnumber (digitpart-based)
      // https://docs.python.org/3.9/reference/lexical_analysis.html#imaginary-literals
      {
        begin: `\\b(${digitpart})[jJ](?=${lookahead2})`
      }
    ]
  };
  const COMMENT_TYPE = {
    className: "comment",
    begin: regex.lookahead(/# type:/),
    end: /$/,
    keywords: KEYWORDS3,
    contains: [
      {
        // prevent keywords from coloring `type`
        begin: /# type:/
      },
      // comment within a datatype comment includes no keywords
      {
        begin: /#/,
        end: /\b\B/,
        endsWithParent: true
      }
    ]
  };
  const PARAMS = {
    className: "params",
    variants: [
      // Exclude params in functions without params
      {
        className: "",
        begin: /\(\s*\)/,
        skip: true
      },
      {
        begin: /\(/,
        end: /\)/,
        excludeBegin: true,
        excludeEnd: true,
        keywords: KEYWORDS3,
        contains: [
          "self",
          PROMPT,
          NUMBER,
          STRING,
          hljs.HASH_COMMENT_MODE
        ]
      }
    ]
  };
  SUBST.contains = [
    STRING,
    NUMBER,
    PROMPT
  ];
  return {
    name: "Python",
    aliases: [
      "py",
      "gyp",
      "ipython"
    ],
    unicodeRegex: true,
    keywords: KEYWORDS3,
    illegal: /(<\/|\?)|=>/,
    contains: [
      PROMPT,
      NUMBER,
      {
        // very common convention
        scope: "variable.language",
        match: /\bself\b/
      },
      {
        // eat "if" prior to string so that it won't accidentally be
        // labeled as an f-string
        beginKeywords: "if",
        relevance: 0
      },
      { match: /\bor\b/, scope: "keyword" },
      STRING,
      COMMENT_TYPE,
      hljs.HASH_COMMENT_MODE,
      {
        match: [
          /\bdef/,
          /\s+/,
          IDENT_RE3
        ],
        scope: {
          1: "keyword",
          3: "title.function"
        },
        contains: [PARAMS]
      },
      {
        variants: [
          {
            match: [
              /\bclass/,
              /\s+/,
              IDENT_RE3,
              /\s*/,
              /\(\s*/,
              IDENT_RE3,
              /\s*\)/
            ]
          },
          {
            match: [
              /\bclass/,
              /\s+/,
              IDENT_RE3
            ]
          }
        ],
        scope: {
          1: "keyword",
          3: "title.class",
          6: "title.class.inherited"
        }
      },
      {
        className: "meta",
        begin: /^[\t ]*@/,
        end: /(?=#)|$/,
        contains: [
          NUMBER,
          PARAMS,
          STRING
        ]
      }
    ]
  };
}

// node_modules/highlight.js/es/languages/python-repl.js
function pythonRepl(hljs) {
  return {
    aliases: ["pycon"],
    contains: [
      {
        className: "meta.prompt",
        starts: {
          // a space separates the REPL prefix from the actual code
          // this is purely for cleaner HTML output
          end: / |$/,
          starts: {
            end: "$",
            subLanguage: "python"
          }
        },
        variants: [
          { begin: /^>>>(?=[ ]|$)/ },
          { begin: /^\.\.\.(?=[ ]|$)/ }
        ]
      }
    ]
  };
}

// node_modules/highlight.js/es/languages/r.js
function r(hljs) {
  const regex = hljs.regex;
  const IDENT_RE3 = /(?:(?:[a-zA-Z]|\.[._a-zA-Z])[._a-zA-Z0-9]*)|\.(?!\d)/;
  const NUMBER_TYPES_RE = regex.either(
    // Special case: only hexadecimal binary powers can contain fractions
    /0[xX][0-9a-fA-F]+\.[0-9a-fA-F]*[pP][+-]?\d+i?/,
    // Hexadecimal numbers without fraction and optional binary power
    /0[xX][0-9a-fA-F]+(?:[pP][+-]?\d+)?[Li]?/,
    // Decimal numbers
    /(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?[Li]?/
  );
  const OPERATORS_RE = /[=!<>:]=|\|\||&&|:::?|<-|<<-|->>|->|\|>|[-+*\/?!$&|:<=>@^~]|\*\*/;
  const PUNCTUATION_RE = regex.either(
    /[()]/,
    /[{}]/,
    /\[\[/,
    /[[\]]/,
    /\\/,
    /,/
  );
  return {
    name: "R",
    keywords: {
      $pattern: IDENT_RE3,
      keyword: "function if in break next repeat else for while",
      literal: "NULL NA TRUE FALSE Inf NaN NA_integer_|10 NA_real_|10 NA_character_|10 NA_complex_|10",
      built_in: (
        // Builtin constants
        "LETTERS letters month.abb month.name pi T F abs acos acosh all any anyNA Arg as.call as.character as.complex as.double as.environment as.integer as.logical as.null.default as.numeric as.raw asin asinh atan atanh attr attributes baseenv browser c call ceiling class Conj cos cosh cospi cummax cummin cumprod cumsum digamma dim dimnames emptyenv exp expression floor forceAndCall gamma gc.time globalenv Im interactive invisible is.array is.atomic is.call is.character is.complex is.double is.environment is.expression is.finite is.function is.infinite is.integer is.language is.list is.logical is.matrix is.na is.name is.nan is.null is.numeric is.object is.pairlist is.raw is.recursive is.single is.symbol lazyLoadDBfetch length lgamma list log max min missing Mod names nargs nzchar oldClass on.exit pos.to.env proc.time prod quote range Re rep retracemem return round seq_along seq_len seq.int sign signif sin sinh sinpi sqrt standardGeneric substitute sum switch tan tanh tanpi tracemem trigamma trunc unclass untracemem UseMethod xtfrm"
      )
    },
    contains: [
      // Roxygen comments
      hljs.COMMENT(
        /#'/,
        /$/,
        { contains: [
          {
            // Handle `@examples` separately to cause all subsequent code
            // until the next `@`-tag on its own line to be kept as-is,
            // preventing highlighting. This code is example R code, so nested
            // doctags shouldn’t be treated as such. See
            // `test/markup/r/roxygen.txt` for an example.
            scope: "doctag",
            match: /@examples/,
            starts: {
              end: regex.lookahead(regex.either(
                // end if another doc comment
                /\n^#'\s*(?=@[a-zA-Z]+)/,
                // or a line with no comment
                /\n^(?!#')/
              )),
              endsParent: true
            }
          },
          {
            // Handle `@param` to highlight the parameter name following
            // after.
            scope: "doctag",
            begin: "@param",
            end: /$/,
            contains: [
              {
                scope: "variable",
                variants: [
                  { match: IDENT_RE3 },
                  { match: /`(?:\\.|[^`\\])+`/ }
                ],
                endsParent: true
              }
            ]
          },
          {
            scope: "doctag",
            match: /@[a-zA-Z]+/
          },
          {
            scope: "keyword",
            match: /\\[a-zA-Z]+/
          }
        ] }
      ),
      hljs.HASH_COMMENT_MODE,
      {
        scope: "string",
        contains: [hljs.BACKSLASH_ESCAPE],
        variants: [
          hljs.END_SAME_AS_BEGIN({
            begin: /[rR]"(-*)\(/,
            end: /\)(-*)"/
          }),
          hljs.END_SAME_AS_BEGIN({
            begin: /[rR]"(-*)\{/,
            end: /\}(-*)"/
          }),
          hljs.END_SAME_AS_BEGIN({
            begin: /[rR]"(-*)\[/,
            end: /\](-*)"/
          }),
          hljs.END_SAME_AS_BEGIN({
            begin: /[rR]'(-*)\(/,
            end: /\)(-*)'/
          }),
          hljs.END_SAME_AS_BEGIN({
            begin: /[rR]'(-*)\{/,
            end: /\}(-*)'/
          }),
          hljs.END_SAME_AS_BEGIN({
            begin: /[rR]'(-*)\[/,
            end: /\](-*)'/
          }),
          {
            begin: '"',
            end: '"',
            relevance: 0
          },
          {
            begin: "'",
            end: "'",
            relevance: 0
          }
        ]
      },
      // Matching numbers immediately following punctuation and operators is
      // tricky since we need to look at the character ahead of a number to
      // ensure the number is not part of an identifier, and we cannot use
      // negative look-behind assertions. So instead we explicitly handle all
      // possible combinations of (operator|punctuation), number.
      // TODO: replace with negative look-behind when available
      // { begin: /(?<![a-zA-Z0-9._])0[xX][0-9a-fA-F]+\.[0-9a-fA-F]*[pP][+-]?\d+i?/ },
      // { begin: /(?<![a-zA-Z0-9._])0[xX][0-9a-fA-F]+([pP][+-]?\d+)?[Li]?/ },
      // { begin: /(?<![a-zA-Z0-9._])(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?[Li]?/ }
      {
        relevance: 0,
        variants: [
          {
            scope: {
              1: "operator",
              2: "number"
            },
            match: [
              OPERATORS_RE,
              NUMBER_TYPES_RE
            ]
          },
          {
            scope: {
              1: "operator",
              2: "number"
            },
            match: [
              /%[^%]*%/,
              NUMBER_TYPES_RE
            ]
          },
          {
            scope: {
              1: "punctuation",
              2: "number"
            },
            match: [
              PUNCTUATION_RE,
              NUMBER_TYPES_RE
            ]
          },
          {
            scope: { 2: "number" },
            match: [
              /[^a-zA-Z0-9._]|^/,
              // not part of an identifier, or start of document
              NUMBER_TYPES_RE
            ]
          }
        ]
      },
      // Operators/punctuation when they're not directly followed by numbers
      {
        // Relevance boost for the most common assignment form.
        scope: { 3: "operator" },
        match: [
          IDENT_RE3,
          /\s+/,
          /<-/,
          /\s+/
        ]
      },
      {
        scope: "operator",
        relevance: 0,
        variants: [
          { match: OPERATORS_RE },
          { match: /%[^%]*%/ }
        ]
      },
      {
        scope: "punctuation",
        relevance: 0,
        match: PUNCTUATION_RE
      },
      {
        // Escaped identifier
        begin: "`",
        end: "`",
        contains: [{ begin: /\\./ }]
      }
    ]
  };
}

// node_modules/highlight.js/es/languages/ruby.js
function ruby(hljs) {
  const regex = hljs.regex;
  const RUBY_METHOD_RE = "([a-zA-Z_]\\w*[!?=]?|[-+~]@|<<|>>|=~|===?|<=>|[<>]=?|\\*\\*|[-/+%^&*~`|]|\\[\\]=?)";
  const CLASS_NAME_RE = regex.either(
    /\b([A-Z]+[a-z0-9]+)+/,
    // ends in caps
    /\b([A-Z]+[a-z0-9]+)+[A-Z]+/
  );
  const CLASS_NAME_WITH_NAMESPACE_RE = regex.concat(CLASS_NAME_RE, /(::\w+)*/);
  const PSEUDO_KWS = [
    "include",
    "extend",
    "prepend",
    "public",
    "private",
    "protected",
    "raise",
    "throw"
  ];
  const RUBY_KEYWORDS = {
    "variable.constant": [
      "__FILE__",
      "__LINE__",
      "__ENCODING__"
    ],
    "variable.language": [
      "self",
      "super"
    ],
    keyword: [
      "alias",
      "and",
      "begin",
      "BEGIN",
      "break",
      "case",
      "class",
      "defined",
      "do",
      "else",
      "elsif",
      "end",
      "END",
      "ensure",
      "for",
      "if",
      "in",
      "module",
      "next",
      "not",
      "or",
      "redo",
      "require",
      "rescue",
      "retry",
      "return",
      "then",
      "undef",
      "unless",
      "until",
      "when",
      "while",
      "yield",
      ...PSEUDO_KWS
    ],
    built_in: [
      "proc",
      "lambda",
      "attr_accessor",
      "attr_reader",
      "attr_writer",
      "define_method",
      "private_constant",
      "module_function"
    ],
    literal: [
      "true",
      "false",
      "nil"
    ]
  };
  const YARDOCTAG = {
    className: "doctag",
    begin: "@[A-Za-z]+"
  };
  const IRB_OBJECT = {
    begin: "#<",
    end: ">"
  };
  const COMMENT_MODES = [
    hljs.COMMENT(
      "#",
      "$",
      { contains: [YARDOCTAG] }
    ),
    hljs.COMMENT(
      "^=begin",
      "^=end",
      {
        contains: [YARDOCTAG],
        relevance: 10
      }
    ),
    hljs.COMMENT("^__END__", hljs.MATCH_NOTHING_RE)
  ];
  const SUBST = {
    className: "subst",
    begin: /#\{/,
    end: /\}/,
    keywords: RUBY_KEYWORDS
  };
  const STRING = {
    className: "string",
    contains: [
      hljs.BACKSLASH_ESCAPE,
      SUBST
    ],
    variants: [
      {
        begin: /'/,
        end: /'/
      },
      {
        begin: /"/,
        end: /"/
      },
      {
        begin: /`/,
        end: /`/
      },
      {
        begin: /%[qQwWx]?\(/,
        end: /\)/
      },
      {
        begin: /%[qQwWx]?\[/,
        end: /\]/
      },
      {
        begin: /%[qQwWx]?\{/,
        end: /\}/
      },
      {
        begin: /%[qQwWx]?</,
        end: />/
      },
      {
        begin: /%[qQwWx]?\//,
        end: /\//
      },
      {
        begin: /%[qQwWx]?%/,
        end: /%/
      },
      {
        begin: /%[qQwWx]?-/,
        end: /-/
      },
      {
        begin: /%[qQwWx]?\|/,
        end: /\|/
      },
      // in the following expressions, \B in the beginning suppresses recognition of ?-sequences
      // where ? is the last character of a preceding identifier, as in: `func?4`
      { begin: /\B\?(\\\d{1,3})/ },
      { begin: /\B\?(\\x[A-Fa-f0-9]{1,2})/ },
      { begin: /\B\?(\\u\{?[A-Fa-f0-9]{1,6}\}?)/ },
      { begin: /\B\?(\\M-\\C-|\\M-\\c|\\c\\M-|\\M-|\\C-\\M-)[\x20-\x7e]/ },
      { begin: /\B\?\\(c|C-)[\x20-\x7e]/ },
      { begin: /\B\?\\?\S/ },
      // heredocs
      {
        // this guard makes sure that we have an entire heredoc and not a false
        // positive (auto-detect, etc.)
        begin: regex.concat(
          /<<[-~]?'?/,
          regex.lookahead(/(\w+)(?=\W)[^\n]*\n(?:[^\n]*\n)*?\s*\1\b/)
        ),
        contains: [
          hljs.END_SAME_AS_BEGIN({
            begin: /(\w+)/,
            end: /(\w+)/,
            contains: [
              hljs.BACKSLASH_ESCAPE,
              SUBST
            ]
          })
        ]
      }
    ]
  };
  const decimal = "[1-9](_?[0-9])*|0";
  const digits = "[0-9](_?[0-9])*";
  const NUMBER = {
    className: "number",
    relevance: 0,
    variants: [
      // decimal integer/float, optionally exponential or rational, optionally imaginary
      { begin: `\\b(${decimal})(\\.(${digits}))?([eE][+-]?(${digits})|r)?i?\\b` },
      // explicit decimal/binary/octal/hexadecimal integer,
      // optionally rational and/or imaginary
      { begin: "\\b0[dD][0-9](_?[0-9])*r?i?\\b" },
      { begin: "\\b0[bB][0-1](_?[0-1])*r?i?\\b" },
      { begin: "\\b0[oO][0-7](_?[0-7])*r?i?\\b" },
      { begin: "\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*r?i?\\b" },
      // 0-prefixed implicit octal integer, optionally rational and/or imaginary
      { begin: "\\b0(_?[0-7])+r?i?\\b" }
    ]
  };
  const PARAMS = {
    variants: [
      {
        match: /\(\)/
      },
      {
        className: "params",
        begin: /\(/,
        end: /(?=\))/,
        excludeBegin: true,
        endsParent: true,
        keywords: RUBY_KEYWORDS
      }
    ]
  };
  const INCLUDE_EXTEND = {
    match: [
      /(include|extend)\s+/,
      CLASS_NAME_WITH_NAMESPACE_RE
    ],
    scope: {
      2: "title.class"
    },
    keywords: RUBY_KEYWORDS
  };
  const CLASS_DEFINITION = {
    variants: [
      {
        match: [
          /class\s+/,
          CLASS_NAME_WITH_NAMESPACE_RE,
          /\s+<\s+/,
          CLASS_NAME_WITH_NAMESPACE_RE
        ]
      },
      {
        match: [
          /\b(class|module)\s+/,
          CLASS_NAME_WITH_NAMESPACE_RE
        ]
      }
    ],
    scope: {
      2: "title.class",
      4: "title.class.inherited"
    },
    keywords: RUBY_KEYWORDS
  };
  const UPPER_CASE_CONSTANT = {
    relevance: 0,
    match: /\b[A-Z][A-Z_0-9]+\b/,
    className: "variable.constant"
  };
  const METHOD_DEFINITION = {
    match: [
      /def/,
      /\s+/,
      RUBY_METHOD_RE
    ],
    scope: {
      1: "keyword",
      3: "title.function"
    },
    contains: [
      PARAMS
    ]
  };
  const OBJECT_CREATION = {
    relevance: 0,
    match: [
      CLASS_NAME_WITH_NAMESPACE_RE,
      /\.new[. (]/
    ],
    scope: {
      1: "title.class"
    }
  };
  const CLASS_REFERENCE = {
    relevance: 0,
    match: CLASS_NAME_RE,
    scope: "title.class"
  };
  const RUBY_DEFAULT_CONTAINS = [
    STRING,
    CLASS_DEFINITION,
    INCLUDE_EXTEND,
    OBJECT_CREATION,
    UPPER_CASE_CONSTANT,
    CLASS_REFERENCE,
    METHOD_DEFINITION,
    {
      // swallow namespace qualifiers before symbols
      begin: hljs.IDENT_RE + "::"
    },
    {
      className: "symbol",
      begin: hljs.UNDERSCORE_IDENT_RE + "(!|\\?)?:",
      relevance: 0
    },
    {
      className: "symbol",
      begin: ":(?!\\s)",
      contains: [
        STRING,
        { begin: RUBY_METHOD_RE }
      ],
      relevance: 0
    },
    NUMBER,
    {
      // negative-look forward attempts to prevent false matches like:
      // @ident@ or $ident$ that might indicate this is not ruby at all
      className: "variable",
      begin: `(\\$\\W)|((\\$|@@?)(\\w+))(?=[^@$?])(?![A-Za-z])(?![@$?'])`
    },
    {
      className: "params",
      begin: /\|(?!=)/,
      end: /\|/,
      excludeBegin: true,
      excludeEnd: true,
      relevance: 0,
      // this could be a lot of things (in other languages) other than params
      keywords: RUBY_KEYWORDS
    },
    {
      // regexp container
      begin: "(" + hljs.RE_STARTERS_RE + "|unless)\\s*",
      keywords: "unless",
      contains: [
        {
          className: "regexp",
          contains: [
            hljs.BACKSLASH_ESCAPE,
            SUBST
          ],
          illegal: /\n/,
          variants: [
            {
              begin: "/",
              end: "/[a-z]*"
            },
            {
              begin: /%r\{/,
              end: /\}[a-z]*/
            },
            {
              begin: "%r\\(",
              end: "\\)[a-z]*"
            },
            {
              begin: "%r!",
              end: "![a-z]*"
            },
            {
              begin: "%r\\[",
              end: "\\][a-z]*"
            }
          ]
        }
      ].concat(IRB_OBJECT, COMMENT_MODES),
      relevance: 0
    }
  ].concat(IRB_OBJECT, COMMENT_MODES);
  SUBST.contains = RUBY_DEFAULT_CONTAINS;
  PARAMS.contains = RUBY_DEFAULT_CONTAINS;
  const SIMPLE_PROMPT = "[>?]>";
  const DEFAULT_PROMPT = "[\\w#]+\\(\\w+\\):\\d+:\\d+[>*]";
  const RVM_PROMPT = "(\\w+-)?\\d+\\.\\d+\\.\\d+(p\\d+)?[^\\d][^>]+>";
  const IRB_DEFAULT = [
    {
      begin: /^\s*=>/,
      starts: {
        end: "$",
        contains: RUBY_DEFAULT_CONTAINS
      }
    },
    {
      className: "meta.prompt",
      begin: "^(" + SIMPLE_PROMPT + "|" + DEFAULT_PROMPT + "|" + RVM_PROMPT + ")(?=[ ])",
      starts: {
        end: "$",
        keywords: RUBY_KEYWORDS,
        contains: RUBY_DEFAULT_CONTAINS
      }
    }
  ];
  COMMENT_MODES.unshift(IRB_OBJECT);
  return {
    name: "Ruby",
    aliases: [
      "rb",
      "gemspec",
      "podspec",
      "thor",
      "irb"
    ],
    keywords: RUBY_KEYWORDS,
    illegal: /\/\*/,
    contains: [hljs.SHEBANG({ binary: "ruby" })].concat(IRB_DEFAULT).concat(COMMENT_MODES).concat(RUBY_DEFAULT_CONTAINS)
  };
}

// node_modules/highlight.js/es/languages/rust.js
function rust(hljs) {
  const regex = hljs.regex;
  const RAW_IDENTIFIER = /(r#)?/;
  const UNDERSCORE_IDENT_RE = regex.concat(RAW_IDENTIFIER, hljs.UNDERSCORE_IDENT_RE);
  const IDENT_RE3 = regex.concat(RAW_IDENTIFIER, hljs.IDENT_RE);
  const FUNCTION_INVOKE = {
    className: "title.function.invoke",
    relevance: 0,
    begin: regex.concat(
      /\b/,
      /(?!let|for|while|if|else|match\b)/,
      IDENT_RE3,
      regex.lookahead(/\s*\(/)
    )
  };
  const NUMBER_SUFFIX = "([ui](8|16|32|64|128|size)|f(32|64))?";
  const KEYWORDS3 = [
    "abstract",
    "as",
    "async",
    "await",
    "become",
    "box",
    "break",
    "const",
    "continue",
    "crate",
    "do",
    "dyn",
    "else",
    "enum",
    "extern",
    "false",
    "final",
    "fn",
    "for",
    "if",
    "impl",
    "in",
    "let",
    "loop",
    "macro",
    "match",
    "mod",
    "move",
    "mut",
    "override",
    "priv",
    "pub",
    "ref",
    "return",
    "self",
    "Self",
    "static",
    "struct",
    "super",
    "trait",
    "true",
    "try",
    "type",
    "typeof",
    "union",
    "unsafe",
    "unsized",
    "use",
    "virtual",
    "where",
    "while",
    "yield"
  ];
  const LITERALS3 = [
    "true",
    "false",
    "Some",
    "None",
    "Ok",
    "Err"
  ];
  const BUILTINS = [
    // functions
    "drop ",
    // traits
    "Copy",
    "Send",
    "Sized",
    "Sync",
    "Drop",
    "Fn",
    "FnMut",
    "FnOnce",
    "ToOwned",
    "Clone",
    "Debug",
    "PartialEq",
    "PartialOrd",
    "Eq",
    "Ord",
    "AsRef",
    "AsMut",
    "Into",
    "From",
    "Default",
    "Iterator",
    "Extend",
    "IntoIterator",
    "DoubleEndedIterator",
    "ExactSizeIterator",
    "SliceConcatExt",
    "ToString",
    // macros
    "assert!",
    "assert_eq!",
    "bitflags!",
    "bytes!",
    "cfg!",
    "col!",
    "concat!",
    "concat_idents!",
    "debug_assert!",
    "debug_assert_eq!",
    "env!",
    "eprintln!",
    "panic!",
    "file!",
    "format!",
    "format_args!",
    "include_bytes!",
    "include_str!",
    "line!",
    "local_data_key!",
    "module_path!",
    "option_env!",
    "print!",
    "println!",
    "select!",
    "stringify!",
    "try!",
    "unimplemented!",
    "unreachable!",
    "vec!",
    "write!",
    "writeln!",
    "macro_rules!",
    "assert_ne!",
    "debug_assert_ne!"
  ];
  const TYPES3 = [
    "i8",
    "i16",
    "i32",
    "i64",
    "i128",
    "isize",
    "u8",
    "u16",
    "u32",
    "u64",
    "u128",
    "usize",
    "f32",
    "f64",
    "str",
    "char",
    "bool",
    "Box",
    "Option",
    "Result",
    "String",
    "Vec"
  ];
  return {
    name: "Rust",
    aliases: ["rs"],
    keywords: {
      $pattern: hljs.IDENT_RE + "!?",
      type: TYPES3,
      keyword: KEYWORDS3,
      literal: LITERALS3,
      built_in: BUILTINS
    },
    illegal: "</",
    contains: [
      hljs.C_LINE_COMMENT_MODE,
      hljs.COMMENT("/\\*", "\\*/", { contains: ["self"] }),
      hljs.inherit(hljs.QUOTE_STRING_MODE, {
        begin: /b?"/,
        illegal: null
      }),
      {
        className: "symbol",
        // negative lookahead to avoid matching `'`
        begin: /'[a-zA-Z_][a-zA-Z0-9_]*(?!')/
      },
      {
        scope: "string",
        variants: [
          { begin: /b?r(#*)"(.|\n)*?"\1(?!#)/ },
          {
            begin: /b?'/,
            end: /'/,
            contains: [
              {
                scope: "char.escape",
                match: /\\('|\w|x\w{2}|u\w{4}|U\w{8})/
              }
            ]
          }
        ]
      },
      {
        className: "number",
        variants: [
          { begin: "\\b0b([01_]+)" + NUMBER_SUFFIX },
          { begin: "\\b0o([0-7_]+)" + NUMBER_SUFFIX },
          { begin: "\\b0x([A-Fa-f0-9_]+)" + NUMBER_SUFFIX },
          { begin: "\\b(\\d[\\d_]*(\\.[0-9_]+)?([eE][+-]?[0-9_]+)?)" + NUMBER_SUFFIX }
        ],
        relevance: 0
      },
      {
        begin: [
          /fn/,
          /\s+/,
          UNDERSCORE_IDENT_RE
        ],
        className: {
          1: "keyword",
          3: "title.function"
        }
      },
      {
        className: "meta",
        begin: "#!?\\[",
        end: "\\]",
        contains: [
          {
            className: "string",
            begin: /"/,
            end: /"/,
            contains: [
              hljs.BACKSLASH_ESCAPE
            ]
          }
        ]
      },
      {
        begin: [
          /let/,
          /\s+/,
          /(?:mut\s+)?/,
          UNDERSCORE_IDENT_RE
        ],
        className: {
          1: "keyword",
          3: "keyword",
          4: "variable"
        }
      },
      // must come before impl/for rule later
      {
        begin: [
          /for/,
          /\s+/,
          UNDERSCORE_IDENT_RE,
          /\s+/,
          /in/
        ],
        className: {
          1: "keyword",
          3: "variable",
          5: "keyword"
        }
      },
      {
        begin: [
          /type/,
          /\s+/,
          UNDERSCORE_IDENT_RE
        ],
        className: {
          1: "keyword",
          3: "title.class"
        }
      },
      {
        begin: [
          /(?:trait|enum|struct|union|impl|for)/,
          /\s+/,
          UNDERSCORE_IDENT_RE
        ],
        className: {
          1: "keyword",
          3: "title.class"
        }
      },
      {
        begin: hljs.IDENT_RE + "::",
        keywords: {
          keyword: "Self",
          built_in: BUILTINS,
          type: TYPES3
        }
      },
      {
        className: "punctuation",
        begin: "->"
      },
      FUNCTION_INVOKE
    ]
  };
}

// node_modules/highlight.js/es/languages/scss.js
var MODES3 = (hljs) => {
  return {
    IMPORTANT: {
      scope: "meta",
      begin: "!important"
    },
    BLOCK_COMMENT: hljs.C_BLOCK_COMMENT_MODE,
    HEXCOLOR: {
      scope: "number",
      begin: /#(([0-9a-fA-F]{3,4})|(([0-9a-fA-F]{2}){3,4}))\b/
    },
    FUNCTION_DISPATCH: {
      className: "built_in",
      begin: /[\w-]+(?=\()/
    },
    ATTRIBUTE_SELECTOR_MODE: {
      scope: "selector-attr",
      begin: /\[/,
      end: /\]/,
      illegal: "$",
      contains: [
        hljs.APOS_STRING_MODE,
        hljs.QUOTE_STRING_MODE
      ]
    },
    CSS_NUMBER_MODE: {
      scope: "number",
      begin: hljs.NUMBER_RE + "(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",
      relevance: 0
    },
    CSS_VARIABLE: {
      className: "attr",
      begin: /--[A-Za-z_][A-Za-z0-9_-]*/
    }
  };
};
var HTML_TAGS3 = [
  "a",
  "abbr",
  "address",
  "article",
  "aside",
  "audio",
  "b",
  "blockquote",
  "body",
  "button",
  "canvas",
  "caption",
  "cite",
  "code",
  "dd",
  "del",
  "details",
  "dfn",
  "div",
  "dl",
  "dt",
  "em",
  "fieldset",
  "figcaption",
  "figure",
  "footer",
  "form",
  "h1",
  "h2",
  "h3",
  "h4",
  "h5",
  "h6",
  "header",
  "hgroup",
  "html",
  "i",
  "iframe",
  "img",
  "input",
  "ins",
  "kbd",
  "label",
  "legend",
  "li",
  "main",
  "mark",
  "menu",
  "nav",
  "object",
  "ol",
  "optgroup",
  "option",
  "p",
  "picture",
  "q",
  "quote",
  "samp",
  "section",
  "select",
  "source",
  "span",
  "strong",
  "summary",
  "sup",
  "table",
  "tbody",
  "td",
  "textarea",
  "tfoot",
  "th",
  "thead",
  "time",
  "tr",
  "ul",
  "var",
  "video"
];
var SVG_TAGS3 = [
  "defs",
  "g",
  "marker",
  "mask",
  "pattern",
  "svg",
  "switch",
  "symbol",
  "feBlend",
  "feColorMatrix",
  "feComponentTransfer",
  "feComposite",
  "feConvolveMatrix",
  "feDiffuseLighting",
  "feDisplacementMap",
  "feFlood",
  "feGaussianBlur",
  "feImage",
  "feMerge",
  "feMorphology",
  "feOffset",
  "feSpecularLighting",
  "feTile",
  "feTurbulence",
  "linearGradient",
  "radialGradient",
  "stop",
  "circle",
  "ellipse",
  "image",
  "line",
  "path",
  "polygon",
  "polyline",
  "rect",
  "text",
  "use",
  "textPath",
  "tspan",
  "foreignObject",
  "clipPath"
];
var TAGS3 = [
  ...HTML_TAGS3,
  ...SVG_TAGS3
];
var MEDIA_FEATURES3 = [
  "any-hover",
  "any-pointer",
  "aspect-ratio",
  "color",
  "color-gamut",
  "color-index",
  "device-aspect-ratio",
  "device-height",
  "device-width",
  "display-mode",
  "forced-colors",
  "grid",
  "height",
  "hover",
  "inverted-colors",
  "monochrome",
  "orientation",
  "overflow-block",
  "overflow-inline",
  "pointer",
  "prefers-color-scheme",
  "prefers-contrast",
  "prefers-reduced-motion",
  "prefers-reduced-transparency",
  "resolution",
  "scan",
  "scripting",
  "update",
  "width",
  // TODO: find a better solution?
  "min-width",
  "max-width",
  "min-height",
  "max-height"
].sort().reverse();
var PSEUDO_CLASSES3 = [
  "active",
  "any-link",
  "blank",
  "checked",
  "current",
  "default",
  "defined",
  "dir",
  // dir()
  "disabled",
  "drop",
  "empty",
  "enabled",
  "first",
  "first-child",
  "first-of-type",
  "fullscreen",
  "future",
  "focus",
  "focus-visible",
  "focus-within",
  "has",
  // has()
  "host",
  // host or host()
  "host-context",
  // host-context()
  "hover",
  "indeterminate",
  "in-range",
  "invalid",
  "is",
  // is()
  "lang",
  // lang()
  "last-child",
  "last-of-type",
  "left",
  "link",
  "local-link",
  "not",
  // not()
  "nth-child",
  // nth-child()
  "nth-col",
  // nth-col()
  "nth-last-child",
  // nth-last-child()
  "nth-last-col",
  // nth-last-col()
  "nth-last-of-type",
  //nth-last-of-type()
  "nth-of-type",
  //nth-of-type()
  "only-child",
  "only-of-type",
  "optional",
  "out-of-range",
  "past",
  "placeholder-shown",
  "read-only",
  "read-write",
  "required",
  "right",
  "root",
  "scope",
  "target",
  "target-within",
  "user-invalid",
  "valid",
  "visited",
  "where"
  // where()
].sort().reverse();
var PSEUDO_ELEMENTS3 = [
  "after",
  "backdrop",
  "before",
  "cue",
  "cue-region",
  "first-letter",
  "first-line",
  "grammar-error",
  "marker",
  "part",
  "placeholder",
  "selection",
  "slotted",
  "spelling-error"
].sort().reverse();
var ATTRIBUTES3 = [
  "accent-color",
  "align-content",
  "align-items",
  "align-self",
  "alignment-baseline",
  "all",
  "anchor-name",
  "animation",
  "animation-composition",
  "animation-delay",
  "animation-direction",
  "animation-duration",
  "animation-fill-mode",
  "animation-iteration-count",
  "animation-name",
  "animation-play-state",
  "animation-range",
  "animation-range-end",
  "animation-range-start",
  "animation-timeline",
  "animation-timing-function",
  "appearance",
  "aspect-ratio",
  "backdrop-filter",
  "backface-visibility",
  "background",
  "background-attachment",
  "background-blend-mode",
  "background-clip",
  "background-color",
  "background-image",
  "background-origin",
  "background-position",
  "background-position-x",
  "background-position-y",
  "background-repeat",
  "background-size",
  "baseline-shift",
  "block-size",
  "border",
  "border-block",
  "border-block-color",
  "border-block-end",
  "border-block-end-color",
  "border-block-end-style",
  "border-block-end-width",
  "border-block-start",
  "border-block-start-color",
  "border-block-start-style",
  "border-block-start-width",
  "border-block-style",
  "border-block-width",
  "border-bottom",
  "border-bottom-color",
  "border-bottom-left-radius",
  "border-bottom-right-radius",
  "border-bottom-style",
  "border-bottom-width",
  "border-collapse",
  "border-color",
  "border-end-end-radius",
  "border-end-start-radius",
  "border-image",
  "border-image-outset",
  "border-image-repeat",
  "border-image-slice",
  "border-image-source",
  "border-image-width",
  "border-inline",
  "border-inline-color",
  "border-inline-end",
  "border-inline-end-color",
  "border-inline-end-style",
  "border-inline-end-width",
  "border-inline-start",
  "border-inline-start-color",
  "border-inline-start-style",
  "border-inline-start-width",
  "border-inline-style",
  "border-inline-width",
  "border-left",
  "border-left-color",
  "border-left-style",
  "border-left-width",
  "border-radius",
  "border-right",
  "border-right-color",
  "border-right-style",
  "border-right-width",
  "border-spacing",
  "border-start-end-radius",
  "border-start-start-radius",
  "border-style",
  "border-top",
  "border-top-color",
  "border-top-left-radius",
  "border-top-right-radius",
  "border-top-style",
  "border-top-width",
  "border-width",
  "bottom",
  "box-align",
  "box-decoration-break",
  "box-direction",
  "box-flex",
  "box-flex-group",
  "box-lines",
  "box-ordinal-group",
  "box-orient",
  "box-pack",
  "box-shadow",
  "box-sizing",
  "break-after",
  "break-before",
  "break-inside",
  "caption-side",
  "caret-color",
  "clear",
  "clip",
  "clip-path",
  "clip-rule",
  "color",
  "color-interpolation",
  "color-interpolation-filters",
  "color-profile",
  "color-rendering",
  "color-scheme",
  "column-count",
  "column-fill",
  "column-gap",
  "column-rule",
  "column-rule-color",
  "column-rule-style",
  "column-rule-width",
  "column-span",
  "column-width",
  "columns",
  "contain",
  "contain-intrinsic-block-size",
  "contain-intrinsic-height",
  "contain-intrinsic-inline-size",
  "contain-intrinsic-size",
  "contain-intrinsic-width",
  "container",
  "container-name",
  "container-type",
  "content",
  "content-visibility",
  "counter-increment",
  "counter-reset",
  "counter-set",
  "cue",
  "cue-after",
  "cue-before",
  "cursor",
  "cx",
  "cy",
  "direction",
  "display",
  "dominant-baseline",
  "empty-cells",
  "enable-background",
  "field-sizing",
  "fill",
  "fill-opacity",
  "fill-rule",
  "filter",
  "flex",
  "flex-basis",
  "flex-direction",
  "flex-flow",
  "flex-grow",
  "flex-shrink",
  "flex-wrap",
  "float",
  "flood-color",
  "flood-opacity",
  "flow",
  "font",
  "font-display",
  "font-family",
  "font-feature-settings",
  "font-kerning",
  "font-language-override",
  "font-optical-sizing",
  "font-palette",
  "font-size",
  "font-size-adjust",
  "font-smooth",
  "font-smoothing",
  "font-stretch",
  "font-style",
  "font-synthesis",
  "font-synthesis-position",
  "font-synthesis-small-caps",
  "font-synthesis-style",
  "font-synthesis-weight",
  "font-variant",
  "font-variant-alternates",
  "font-variant-caps",
  "font-variant-east-asian",
  "font-variant-emoji",
  "font-variant-ligatures",
  "font-variant-numeric",
  "font-variant-position",
  "font-variation-settings",
  "font-weight",
  "forced-color-adjust",
  "gap",
  "glyph-orientation-horizontal",
  "glyph-orientation-vertical",
  "grid",
  "grid-area",
  "grid-auto-columns",
  "grid-auto-flow",
  "grid-auto-rows",
  "grid-column",
  "grid-column-end",
  "grid-column-start",
  "grid-gap",
  "grid-row",
  "grid-row-end",
  "grid-row-start",
  "grid-template",
  "grid-template-areas",
  "grid-template-columns",
  "grid-template-rows",
  "hanging-punctuation",
  "height",
  "hyphenate-character",
  "hyphenate-limit-chars",
  "hyphens",
  "icon",
  "image-orientation",
  "image-rendering",
  "image-resolution",
  "ime-mode",
  "initial-letter",
  "initial-letter-align",
  "inline-size",
  "inset",
  "inset-area",
  "inset-block",
  "inset-block-end",
  "inset-block-start",
  "inset-inline",
  "inset-inline-end",
  "inset-inline-start",
  "isolation",
  "justify-content",
  "justify-items",
  "justify-self",
  "kerning",
  "left",
  "letter-spacing",
  "lighting-color",
  "line-break",
  "line-height",
  "line-height-step",
  "list-style",
  "list-style-image",
  "list-style-position",
  "list-style-type",
  "margin",
  "margin-block",
  "margin-block-end",
  "margin-block-start",
  "margin-bottom",
  "margin-inline",
  "margin-inline-end",
  "margin-inline-start",
  "margin-left",
  "margin-right",
  "margin-top",
  "margin-trim",
  "marker",
  "marker-end",
  "marker-mid",
  "marker-start",
  "marks",
  "mask",
  "mask-border",
  "mask-border-mode",
  "mask-border-outset",
  "mask-border-repeat",
  "mask-border-slice",
  "mask-border-source",
  "mask-border-width",
  "mask-clip",
  "mask-composite",
  "mask-image",
  "mask-mode",
  "mask-origin",
  "mask-position",
  "mask-repeat",
  "mask-size",
  "mask-type",
  "masonry-auto-flow",
  "math-depth",
  "math-shift",
  "math-style",
  "max-block-size",
  "max-height",
  "max-inline-size",
  "max-width",
  "min-block-size",
  "min-height",
  "min-inline-size",
  "min-width",
  "mix-blend-mode",
  "nav-down",
  "nav-index",
  "nav-left",
  "nav-right",
  "nav-up",
  "none",
  "normal",
  "object-fit",
  "object-position",
  "offset",
  "offset-anchor",
  "offset-distance",
  "offset-path",
  "offset-position",
  "offset-rotate",
  "opacity",
  "order",
  "orphans",
  "outline",
  "outline-color",
  "outline-offset",
  "outline-style",
  "outline-width",
  "overflow",
  "overflow-anchor",
  "overflow-block",
  "overflow-clip-margin",
  "overflow-inline",
  "overflow-wrap",
  "overflow-x",
  "overflow-y",
  "overlay",
  "overscroll-behavior",
  "overscroll-behavior-block",
  "overscroll-behavior-inline",
  "overscroll-behavior-x",
  "overscroll-behavior-y",
  "padding",
  "padding-block",
  "padding-block-end",
  "padding-block-start",
  "padding-bottom",
  "padding-inline",
  "padding-inline-end",
  "padding-inline-start",
  "padding-left",
  "padding-right",
  "padding-top",
  "page",
  "page-break-after",
  "page-break-before",
  "page-break-inside",
  "paint-order",
  "pause",
  "pause-after",
  "pause-before",
  "perspective",
  "perspective-origin",
  "place-content",
  "place-items",
  "place-self",
  "pointer-events",
  "position",
  "position-anchor",
  "position-visibility",
  "print-color-adjust",
  "quotes",
  "r",
  "resize",
  "rest",
  "rest-after",
  "rest-before",
  "right",
  "rotate",
  "row-gap",
  "ruby-align",
  "ruby-position",
  "scale",
  "scroll-behavior",
  "scroll-margin",
  "scroll-margin-block",
  "scroll-margin-block-end",
  "scroll-margin-block-start",
  "scroll-margin-bottom",
  "scroll-margin-inline",
  "scroll-margin-inline-end",
  "scroll-margin-inline-start",
  "scroll-margin-left",
  "scroll-margin-right",
  "scroll-margin-top",
  "scroll-padding",
  "scroll-padding-block",
  "scroll-padding-block-end",
  "scroll-padding-block-start",
  "scroll-padding-bottom",
  "scroll-padding-inline",
  "scroll-padding-inline-end",
  "scroll-padding-inline-start",
  "scroll-padding-left",
  "scroll-padding-right",
  "scroll-padding-top",
  "scroll-snap-align",
  "scroll-snap-stop",
  "scroll-snap-type",
  "scroll-timeline",
  "scroll-timeline-axis",
  "scroll-timeline-name",
  "scrollbar-color",
  "scrollbar-gutter",
  "scrollbar-width",
  "shape-image-threshold",
  "shape-margin",
  "shape-outside",
  "shape-rendering",
  "speak",
  "speak-as",
  "src",
  // @font-face
  "stop-color",
  "stop-opacity",
  "stroke",
  "stroke-dasharray",
  "stroke-dashoffset",
  "stroke-linecap",
  "stroke-linejoin",
  "stroke-miterlimit",
  "stroke-opacity",
  "stroke-width",
  "tab-size",
  "table-layout",
  "text-align",
  "text-align-all",
  "text-align-last",
  "text-anchor",
  "text-combine-upright",
  "text-decoration",
  "text-decoration-color",
  "text-decoration-line",
  "text-decoration-skip",
  "text-decoration-skip-ink",
  "text-decoration-style",
  "text-decoration-thickness",
  "text-emphasis",
  "text-emphasis-color",
  "text-emphasis-position",
  "text-emphasis-style",
  "text-indent",
  "text-justify",
  "text-orientation",
  "text-overflow",
  "text-rendering",
  "text-shadow",
  "text-size-adjust",
  "text-transform",
  "text-underline-offset",
  "text-underline-position",
  "text-wrap",
  "text-wrap-mode",
  "text-wrap-style",
  "timeline-scope",
  "top",
  "touch-action",
  "transform",
  "transform-box",
  "transform-origin",
  "transform-style",
  "transition",
  "transition-behavior",
  "transition-delay",
  "transition-duration",
  "transition-property",
  "transition-timing-function",
  "translate",
  "unicode-bidi",
  "user-modify",
  "user-select",
  "vector-effect",
  "vertical-align",
  "view-timeline",
  "view-timeline-axis",
  "view-timeline-inset",
  "view-timeline-name",
  "view-transition-name",
  "visibility",
  "voice-balance",
  "voice-duration",
  "voice-family",
  "voice-pitch",
  "voice-range",
  "voice-rate",
  "voice-stress",
  "voice-volume",
  "white-space",
  "white-space-collapse",
  "widows",
  "width",
  "will-change",
  "word-break",
  "word-spacing",
  "word-wrap",
  "writing-mode",
  "x",
  "y",
  "z-index",
  "zoom"
].sort().reverse();
function scss(hljs) {
  const modes = MODES3(hljs);
  const PSEUDO_ELEMENTS$1 = PSEUDO_ELEMENTS3;
  const PSEUDO_CLASSES$1 = PSEUDO_CLASSES3;
  const AT_IDENTIFIER = "@[a-z-]+";
  const AT_MODIFIERS = "and or not only";
  const IDENT_RE3 = "[a-zA-Z-][a-zA-Z0-9_-]*";
  const VARIABLE = {
    className: "variable",
    begin: "(\\$" + IDENT_RE3 + ")\\b",
    relevance: 0
  };
  return {
    name: "SCSS",
    case_insensitive: true,
    illegal: "[=/|']",
    contains: [
      hljs.C_LINE_COMMENT_MODE,
      hljs.C_BLOCK_COMMENT_MODE,
      // to recognize keyframe 40% etc which are outside the scope of our
      // attribute value mode
      modes.CSS_NUMBER_MODE,
      {
        className: "selector-id",
        begin: "#[A-Za-z0-9_-]+",
        relevance: 0
      },
      {
        className: "selector-class",
        begin: "\\.[A-Za-z0-9_-]+",
        relevance: 0
      },
      modes.ATTRIBUTE_SELECTOR_MODE,
      {
        className: "selector-tag",
        begin: "\\b(" + TAGS3.join("|") + ")\\b",
        // was there, before, but why?
        relevance: 0
      },
      {
        className: "selector-pseudo",
        begin: ":(" + PSEUDO_CLASSES$1.join("|") + ")"
      },
      {
        className: "selector-pseudo",
        begin: ":(:)?(" + PSEUDO_ELEMENTS$1.join("|") + ")"
      },
      VARIABLE,
      {
        // pseudo-selector params
        begin: /\(/,
        end: /\)/,
        contains: [modes.CSS_NUMBER_MODE]
      },
      modes.CSS_VARIABLE,
      {
        className: "attribute",
        begin: "\\b(" + ATTRIBUTES3.join("|") + ")\\b"
      },
      { begin: "\\b(whitespace|wait|w-resize|visible|vertical-text|vertical-ideographic|uppercase|upper-roman|upper-alpha|underline|transparent|top|thin|thick|text|text-top|text-bottom|tb-rl|table-header-group|table-footer-group|sw-resize|super|strict|static|square|solid|small-caps|separate|se-resize|scroll|s-resize|rtl|row-resize|ridge|right|repeat|repeat-y|repeat-x|relative|progress|pointer|overline|outside|outset|oblique|nowrap|not-allowed|normal|none|nw-resize|no-repeat|no-drop|newspaper|ne-resize|n-resize|move|middle|medium|ltr|lr-tb|lowercase|lower-roman|lower-alpha|loose|list-item|line|line-through|line-edge|lighter|left|keep-all|justify|italic|inter-word|inter-ideograph|inside|inset|inline|inline-block|inherit|inactive|ideograph-space|ideograph-parenthesis|ideograph-numeric|ideograph-alpha|horizontal|hidden|help|hand|groove|fixed|ellipsis|e-resize|double|dotted|distribute|distribute-space|distribute-letter|distribute-all-lines|disc|disabled|default|decimal|dashed|crosshair|collapse|col-resize|circle|char|center|capitalize|break-word|break-all|bottom|both|bolder|bold|block|bidi-override|below|baseline|auto|always|all-scroll|absolute|table|table-cell)\\b" },
      {
        begin: /:/,
        end: /[;}{]/,
        relevance: 0,
        contains: [
          modes.BLOCK_COMMENT,
          VARIABLE,
          modes.HEXCOLOR,
          modes.CSS_NUMBER_MODE,
          hljs.QUOTE_STRING_MODE,
          hljs.APOS_STRING_MODE,
          modes.IMPORTANT,
          modes.FUNCTION_DISPATCH
        ]
      },
      // matching these here allows us to treat them more like regular CSS
      // rules so everything between the {} gets regular rule highlighting,
      // which is what we want for page and font-face
      {
        begin: "@(page|font-face)",
        keywords: {
          $pattern: AT_IDENTIFIER,
          keyword: "@page @font-face"
        }
      },
      {
        begin: "@",
        end: "[{;]",
        returnBegin: true,
        keywords: {
          $pattern: /[a-z-]+/,
          keyword: AT_MODIFIERS,
          attribute: MEDIA_FEATURES3.join(" ")
        },
        contains: [
          {
            begin: AT_IDENTIFIER,
            className: "keyword"
          },
          {
            begin: /[a-z-]+(?=:)/,
            className: "attribute"
          },
          VARIABLE,
          hljs.QUOTE_STRING_MODE,
          hljs.APOS_STRING_MODE,
          modes.HEXCOLOR,
          modes.CSS_NUMBER_MODE
        ]
      },
      modes.FUNCTION_DISPATCH
    ]
  };
}

// node_modules/highlight.js/es/languages/shell.js
function shell(hljs) {
  return {
    name: "Shell Session",
    aliases: [
      "console",
      "shellsession"
    ],
    contains: [
      {
        className: "meta.prompt",
        // We cannot add \s (spaces) in the regular expression otherwise it will be too broad and produce unexpected result.
        // For instance, in the following example, it would match "echo /path/to/home >" as a prompt:
        // echo /path/to/home > t.exe
        begin: /^\s{0,3}[/~\w\d[\]()@-]*[>%$#][ ]?/,
        starts: {
          end: /[^\\](?=\s*$)/,
          subLanguage: "bash"
        }
      }
    ]
  };
}

// node_modules/highlight.js/es/languages/sql.js
function sql(hljs) {
  const regex = hljs.regex;
  const COMMENT_MODE = hljs.COMMENT("--", "$");
  const STRING = {
    scope: "string",
    variants: [
      {
        begin: /'/,
        end: /'/,
        contains: [{ match: /''/ }]
      }
    ]
  };
  const QUOTED_IDENTIFIER = {
    begin: /"/,
    end: /"/,
    contains: [{ match: /""/ }]
  };
  const LITERALS3 = [
    "true",
    "false",
    // Not sure it's correct to call NULL literal, and clauses like IS [NOT] NULL look strange that way.
    // "null",
    "unknown"
  ];
  const MULTI_WORD_TYPES = [
    "double precision",
    "large object",
    "with timezone",
    "without timezone"
  ];
  const TYPES3 = [
    "bigint",
    "binary",
    "blob",
    "boolean",
    "char",
    "character",
    "clob",
    "date",
    "dec",
    "decfloat",
    "decimal",
    "float",
    "int",
    "integer",
    "interval",
    "nchar",
    "nclob",
    "national",
    "numeric",
    "real",
    "row",
    "smallint",
    "time",
    "timestamp",
    "varchar",
    "varying",
    // modifier (character varying)
    "varbinary"
  ];
  const NON_RESERVED_WORDS = [
    "add",
    "asc",
    "collation",
    "desc",
    "final",
    "first",
    "last",
    "view"
  ];
  const RESERVED_WORDS = [
    "abs",
    "acos",
    "all",
    "allocate",
    "alter",
    "and",
    "any",
    "are",
    "array",
    "array_agg",
    "array_max_cardinality",
    "as",
    "asensitive",
    "asin",
    "asymmetric",
    "at",
    "atan",
    "atomic",
    "authorization",
    "avg",
    "begin",
    "begin_frame",
    "begin_partition",
    "between",
    "bigint",
    "binary",
    "blob",
    "boolean",
    "both",
    "by",
    "call",
    "called",
    "cardinality",
    "cascaded",
    "case",
    "cast",
    "ceil",
    "ceiling",
    "char",
    "char_length",
    "character",
    "character_length",
    "check",
    "classifier",
    "clob",
    "close",
    "coalesce",
    "collate",
    "collect",
    "column",
    "commit",
    "condition",
    "connect",
    "constraint",
    "contains",
    "convert",
    "copy",
    "corr",
    "corresponding",
    "cos",
    "cosh",
    "count",
    "covar_pop",
    "covar_samp",
    "create",
    "cross",
    "cube",
    "cume_dist",
    "current",
    "current_catalog",
    "current_date",
    "current_default_transform_group",
    "current_path",
    "current_role",
    "current_row",
    "current_schema",
    "current_time",
    "current_timestamp",
    "current_path",
    "current_role",
    "current_transform_group_for_type",
    "current_user",
    "cursor",
    "cycle",
    "date",
    "day",
    "deallocate",
    "dec",
    "decimal",
    "decfloat",
    "declare",
    "default",
    "define",
    "delete",
    "dense_rank",
    "deref",
    "describe",
    "deterministic",
    "disconnect",
    "distinct",
    "double",
    "drop",
    "dynamic",
    "each",
    "element",
    "else",
    "empty",
    "end",
    "end_frame",
    "end_partition",
    "end-exec",
    "equals",
    "escape",
    "every",
    "except",
    "exec",
    "execute",
    "exists",
    "exp",
    "external",
    "extract",
    "false",
    "fetch",
    "filter",
    "first_value",
    "float",
    "floor",
    "for",
    "foreign",
    "frame_row",
    "free",
    "from",
    "full",
    "function",
    "fusion",
    "get",
    "global",
    "grant",
    "group",
    "grouping",
    "groups",
    "having",
    "hold",
    "hour",
    "identity",
    "in",
    "indicator",
    "initial",
    "inner",
    "inout",
    "insensitive",
    "insert",
    "int",
    "integer",
    "intersect",
    "intersection",
    "interval",
    "into",
    "is",
    "join",
    "json_array",
    "json_arrayagg",
    "json_exists",
    "json_object",
    "json_objectagg",
    "json_query",
    "json_table",
    "json_table_primitive",
    "json_value",
    "lag",
    "language",
    "large",
    "last_value",
    "lateral",
    "lead",
    "leading",
    "left",
    "like",
    "like_regex",
    "listagg",
    "ln",
    "local",
    "localtime",
    "localtimestamp",
    "log",
    "log10",
    "lower",
    "match",
    "match_number",
    "match_recognize",
    "matches",
    "max",
    "member",
    "merge",
    "method",
    "min",
    "minute",
    "mod",
    "modifies",
    "module",
    "month",
    "multiset",
    "national",
    "natural",
    "nchar",
    "nclob",
    "new",
    "no",
    "none",
    "normalize",
    "not",
    "nth_value",
    "ntile",
    "null",
    "nullif",
    "numeric",
    "octet_length",
    "occurrences_regex",
    "of",
    "offset",
    "old",
    "omit",
    "on",
    "one",
    "only",
    "open",
    "or",
    "order",
    "out",
    "outer",
    "over",
    "overlaps",
    "overlay",
    "parameter",
    "partition",
    "pattern",
    "per",
    "percent",
    "percent_rank",
    "percentile_cont",
    "percentile_disc",
    "period",
    "portion",
    "position",
    "position_regex",
    "power",
    "precedes",
    "precision",
    "prepare",
    "primary",
    "procedure",
    "ptf",
    "range",
    "rank",
    "reads",
    "real",
    "recursive",
    "ref",
    "references",
    "referencing",
    "regr_avgx",
    "regr_avgy",
    "regr_count",
    "regr_intercept",
    "regr_r2",
    "regr_slope",
    "regr_sxx",
    "regr_sxy",
    "regr_syy",
    "release",
    "result",
    "return",
    "returns",
    "revoke",
    "right",
    "rollback",
    "rollup",
    "row",
    "row_number",
    "rows",
    "running",
    "savepoint",
    "scope",
    "scroll",
    "search",
    "second",
    "seek",
    "select",
    "sensitive",
    "session_user",
    "set",
    "show",
    "similar",
    "sin",
    "sinh",
    "skip",
    "smallint",
    "some",
    "specific",
    "specifictype",
    "sql",
    "sqlexception",
    "sqlstate",
    "sqlwarning",
    "sqrt",
    "start",
    "static",
    "stddev_pop",
    "stddev_samp",
    "submultiset",
    "subset",
    "substring",
    "substring_regex",
    "succeeds",
    "sum",
    "symmetric",
    "system",
    "system_time",
    "system_user",
    "table",
    "tablesample",
    "tan",
    "tanh",
    "then",
    "time",
    "timestamp",
    "timezone_hour",
    "timezone_minute",
    "to",
    "trailing",
    "translate",
    "translate_regex",
    "translation",
    "treat",
    "trigger",
    "trim",
    "trim_array",
    "true",
    "truncate",
    "uescape",
    "union",
    "unique",
    "unknown",
    "unnest",
    "update",
    "upper",
    "user",
    "using",
    "value",
    "values",
    "value_of",
    "var_pop",
    "var_samp",
    "varbinary",
    "varchar",
    "varying",
    "versioning",
    "when",
    "whenever",
    "where",
    "width_bucket",
    "window",
    "with",
    "within",
    "without",
    "year"
  ];
  const RESERVED_FUNCTIONS = [
    "abs",
    "acos",
    "array_agg",
    "asin",
    "atan",
    "avg",
    "cast",
    "ceil",
    "ceiling",
    "coalesce",
    "corr",
    "cos",
    "cosh",
    "count",
    "covar_pop",
    "covar_samp",
    "cume_dist",
    "dense_rank",
    "deref",
    "element",
    "exp",
    "extract",
    "first_value",
    "floor",
    "json_array",
    "json_arrayagg",
    "json_exists",
    "json_object",
    "json_objectagg",
    "json_query",
    "json_table",
    "json_table_primitive",
    "json_value",
    "lag",
    "last_value",
    "lead",
    "listagg",
    "ln",
    "log",
    "log10",
    "lower",
    "max",
    "min",
    "mod",
    "nth_value",
    "ntile",
    "nullif",
    "percent_rank",
    "percentile_cont",
    "percentile_disc",
    "position",
    "position_regex",
    "power",
    "rank",
    "regr_avgx",
    "regr_avgy",
    "regr_count",
    "regr_intercept",
    "regr_r2",
    "regr_slope",
    "regr_sxx",
    "regr_sxy",
    "regr_syy",
    "row_number",
    "sin",
    "sinh",
    "sqrt",
    "stddev_pop",
    "stddev_samp",
    "substring",
    "substring_regex",
    "sum",
    "tan",
    "tanh",
    "translate",
    "translate_regex",
    "treat",
    "trim",
    "trim_array",
    "unnest",
    "upper",
    "value_of",
    "var_pop",
    "var_samp",
    "width_bucket"
  ];
  const POSSIBLE_WITHOUT_PARENS = [
    "current_catalog",
    "current_date",
    "current_default_transform_group",
    "current_path",
    "current_role",
    "current_schema",
    "current_transform_group_for_type",
    "current_user",
    "session_user",
    "system_time",
    "system_user",
    "current_time",
    "localtime",
    "current_timestamp",
    "localtimestamp"
  ];
  const COMBOS = [
    "create table",
    "insert into",
    "primary key",
    "foreign key",
    "not null",
    "alter table",
    "add constraint",
    "grouping sets",
    "on overflow",
    "character set",
    "respect nulls",
    "ignore nulls",
    "nulls first",
    "nulls last",
    "depth first",
    "breadth first"
  ];
  const FUNCTIONS = RESERVED_FUNCTIONS;
  const KEYWORDS3 = [
    ...RESERVED_WORDS,
    ...NON_RESERVED_WORDS
  ].filter((keyword) => {
    return !RESERVED_FUNCTIONS.includes(keyword);
  });
  const VARIABLE = {
    scope: "variable",
    match: /@[a-z0-9][a-z0-9_]*/
  };
  const OPERATOR = {
    scope: "operator",
    match: /[-+*/=%^~]|&&?|\|\|?|!=?|<(?:=>?|<|>)?|>[>=]?/,
    relevance: 0
  };
  const FUNCTION_CALL = {
    match: regex.concat(/\b/, regex.either(...FUNCTIONS), /\s*\(/),
    relevance: 0,
    keywords: { built_in: FUNCTIONS }
  };
  function kws_to_regex(list) {
    return regex.concat(
      /\b/,
      regex.either(...list.map((kw) => {
        return kw.replace(/\s+/, "\\s+");
      })),
      /\b/
    );
  }
  const MULTI_WORD_KEYWORDS = {
    scope: "keyword",
    match: kws_to_regex(COMBOS),
    relevance: 0
  };
  function reduceRelevancy(list, {
    exceptions,
    when
  } = {}) {
    const qualifyFn = when;
    exceptions = exceptions || [];
    return list.map((item) => {
      if (item.match(/\|\d+$/) || exceptions.includes(item)) {
        return item;
      } else if (qualifyFn(item)) {
        return `${item}|0`;
      } else {
        return item;
      }
    });
  }
  return {
    name: "SQL",
    case_insensitive: true,
    // does not include {} or HTML tags `</`
    illegal: /[{}]|<\//,
    keywords: {
      $pattern: /\b[\w\.]+/,
      keyword: reduceRelevancy(KEYWORDS3, { when: (x) => x.length < 3 }),
      literal: LITERALS3,
      type: TYPES3,
      built_in: POSSIBLE_WITHOUT_PARENS
    },
    contains: [
      {
        scope: "type",
        match: kws_to_regex(MULTI_WORD_TYPES)
      },
      MULTI_WORD_KEYWORDS,
      FUNCTION_CALL,
      VARIABLE,
      STRING,
      QUOTED_IDENTIFIER,
      hljs.C_NUMBER_MODE,
      hljs.C_BLOCK_COMMENT_MODE,
      COMMENT_MODE,
      OPERATOR
    ]
  };
}

// node_modules/highlight.js/es/languages/swift.js
function source(re) {
  if (!re) return null;
  if (typeof re === "string") return re;
  return re.source;
}
function lookahead(re) {
  return concat("(?=", re, ")");
}
function concat(...args) {
  const joined = args.map((x) => source(x)).join("");
  return joined;
}
function stripOptionsFromArgs(args) {
  const opts = args[args.length - 1];
  if (typeof opts === "object" && opts.constructor === Object) {
    args.splice(args.length - 1, 1);
    return opts;
  } else {
    return {};
  }
}
function either(...args) {
  const opts = stripOptionsFromArgs(args);
  const joined = "(" + (opts.capture ? "" : "?:") + args.map((x) => source(x)).join("|") + ")";
  return joined;
}
var keywordWrapper = (keyword) => concat(
  /\b/,
  keyword,
  /\w$/.test(keyword) ? /\b/ : /\B/
);
var dotKeywords = [
  "Protocol",
  // contextual
  "Type"
  // contextual
].map(keywordWrapper);
var optionalDotKeywords = [
  "init",
  "self"
].map(keywordWrapper);
var keywordTypes = [
  "Any",
  "Self"
];
var keywords = [
  // strings below will be fed into the regular `keywords` engine while regex
  // will result in additional modes being created to scan for those keywords to
  // avoid conflicts with other rules
  "actor",
  "any",
  // contextual
  "associatedtype",
  "async",
  "await",
  /as\?/,
  // operator
  /as!/,
  // operator
  "as",
  // operator
  "borrowing",
  // contextual
  "break",
  "case",
  "catch",
  "class",
  "consume",
  // contextual
  "consuming",
  // contextual
  "continue",
  "convenience",
  // contextual
  "copy",
  // contextual
  "default",
  "defer",
  "deinit",
  "didSet",
  // contextual
  "distributed",
  "do",
  "dynamic",
  // contextual
  "each",
  "else",
  "enum",
  "extension",
  "fallthrough",
  /fileprivate\(set\)/,
  "fileprivate",
  "final",
  // contextual
  "for",
  "func",
  "get",
  // contextual
  "guard",
  "if",
  "import",
  "indirect",
  // contextual
  "infix",
  // contextual
  /init\?/,
  /init!/,
  "inout",
  /internal\(set\)/,
  "internal",
  "in",
  "is",
  // operator
  "isolated",
  // contextual
  "nonisolated",
  // contextual
  "lazy",
  // contextual
  "let",
  "macro",
  "mutating",
  // contextual
  "nonmutating",
  // contextual
  /open\(set\)/,
  // contextual
  "open",
  // contextual
  "operator",
  "optional",
  // contextual
  "override",
  // contextual
  "package",
  "postfix",
  // contextual
  "precedencegroup",
  "prefix",
  // contextual
  /private\(set\)/,
  "private",
  "protocol",
  /public\(set\)/,
  "public",
  "repeat",
  "required",
  // contextual
  "rethrows",
  "return",
  "set",
  // contextual
  "some",
  // contextual
  "static",
  "struct",
  "subscript",
  "super",
  "switch",
  "throws",
  "throw",
  /try\?/,
  // operator
  /try!/,
  // operator
  "try",
  // operator
  "typealias",
  /unowned\(safe\)/,
  // contextual
  /unowned\(unsafe\)/,
  // contextual
  "unowned",
  // contextual
  "var",
  "weak",
  // contextual
  "where",
  "while",
  "willSet"
  // contextual
];
var literals = [
  "false",
  "nil",
  "true"
];
var precedencegroupKeywords = [
  "assignment",
  "associativity",
  "higherThan",
  "left",
  "lowerThan",
  "none",
  "right"
];
var numberSignKeywords = [
  "#colorLiteral",
  "#column",
  "#dsohandle",
  "#else",
  "#elseif",
  "#endif",
  "#error",
  "#file",
  "#fileID",
  "#fileLiteral",
  "#filePath",
  "#function",
  "#if",
  "#imageLiteral",
  "#keyPath",
  "#line",
  "#selector",
  "#sourceLocation",
  "#warning"
];
var builtIns = [
  "abs",
  "all",
  "any",
  "assert",
  "assertionFailure",
  "debugPrint",
  "dump",
  "fatalError",
  "getVaList",
  "isKnownUniquelyReferenced",
  "max",
  "min",
  "numericCast",
  "pointwiseMax",
  "pointwiseMin",
  "precondition",
  "preconditionFailure",
  "print",
  "readLine",
  "repeatElement",
  "sequence",
  "stride",
  "swap",
  "swift_unboxFromSwiftValueWithType",
  "transcode",
  "type",
  "unsafeBitCast",
  "unsafeDowncast",
  "withExtendedLifetime",
  "withUnsafeMutablePointer",
  "withUnsafePointer",
  "withVaList",
  "withoutActuallyEscaping",
  "zip"
];
var operatorHead = either(
  /[/=\-+!*%<>&|^~?]/,
  /[\u00A1-\u00A7]/,
  /[\u00A9\u00AB]/,
  /[\u00AC\u00AE]/,
  /[\u00B0\u00B1]/,
  /[\u00B6\u00BB\u00BF\u00D7\u00F7]/,
  /[\u2016-\u2017]/,
  /[\u2020-\u2027]/,
  /[\u2030-\u203E]/,
  /[\u2041-\u2053]/,
  /[\u2055-\u205E]/,
  /[\u2190-\u23FF]/,
  /[\u2500-\u2775]/,
  /[\u2794-\u2BFF]/,
  /[\u2E00-\u2E7F]/,
  /[\u3001-\u3003]/,
  /[\u3008-\u3020]/,
  /[\u3030]/
);
var operatorCharacter = either(
  operatorHead,
  /[\u0300-\u036F]/,
  /[\u1DC0-\u1DFF]/,
  /[\u20D0-\u20FF]/,
  /[\uFE00-\uFE0F]/,
  /[\uFE20-\uFE2F]/
  // TODO: The following characters are also allowed, but the regex isn't supported yet.
  // /[\u{E0100}-\u{E01EF}]/u
);
var operator = concat(operatorHead, operatorCharacter, "*");
var identifierHead = either(
  /[a-zA-Z_]/,
  /[\u00A8\u00AA\u00AD\u00AF\u00B2-\u00B5\u00B7-\u00BA]/,
  /[\u00BC-\u00BE\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF]/,
  /[\u0100-\u02FF\u0370-\u167F\u1681-\u180D\u180F-\u1DBF]/,
  /[\u1E00-\u1FFF]/,
  /[\u200B-\u200D\u202A-\u202E\u203F-\u2040\u2054\u2060-\u206F]/,
  /[\u2070-\u20CF\u2100-\u218F\u2460-\u24FF\u2776-\u2793]/,
  /[\u2C00-\u2DFF\u2E80-\u2FFF]/,
  /[\u3004-\u3007\u3021-\u302F\u3031-\u303F\u3040-\uD7FF]/,
  /[\uF900-\uFD3D\uFD40-\uFDCF\uFDF0-\uFE1F\uFE30-\uFE44]/,
  /[\uFE47-\uFEFE\uFF00-\uFFFD]/
  // Should be /[\uFE47-\uFFFD]/, but we have to exclude FEFF.
  // The following characters are also allowed, but the regexes aren't supported yet.
  // /[\u{10000}-\u{1FFFD}\u{20000-\u{2FFFD}\u{30000}-\u{3FFFD}\u{40000}-\u{4FFFD}]/u,
  // /[\u{50000}-\u{5FFFD}\u{60000-\u{6FFFD}\u{70000}-\u{7FFFD}\u{80000}-\u{8FFFD}]/u,
  // /[\u{90000}-\u{9FFFD}\u{A0000-\u{AFFFD}\u{B0000}-\u{BFFFD}\u{C0000}-\u{CFFFD}]/u,
  // /[\u{D0000}-\u{DFFFD}\u{E0000-\u{EFFFD}]/u
);
var identifierCharacter = either(
  identifierHead,
  /\d/,
  /[\u0300-\u036F\u1DC0-\u1DFF\u20D0-\u20FF\uFE20-\uFE2F]/
);
var identifier = concat(identifierHead, identifierCharacter, "*");
var typeIdentifier = concat(/[A-Z]/, identifierCharacter, "*");
var keywordAttributes = [
  "attached",
  "autoclosure",
  concat(/convention\(/, either("swift", "block", "c"), /\)/),
  "discardableResult",
  "dynamicCallable",
  "dynamicMemberLookup",
  "escaping",
  "freestanding",
  "frozen",
  "GKInspectable",
  "IBAction",
  "IBDesignable",
  "IBInspectable",
  "IBOutlet",
  "IBSegueAction",
  "inlinable",
  "main",
  "nonobjc",
  "NSApplicationMain",
  "NSCopying",
  "NSManaged",
  concat(/objc\(/, identifier, /\)/),
  "objc",
  "objcMembers",
  "propertyWrapper",
  "requires_stored_property_inits",
  "resultBuilder",
  "Sendable",
  "testable",
  "UIApplicationMain",
  "unchecked",
  "unknown",
  "usableFromInline",
  "warn_unqualified_access"
];
var availabilityKeywords = [
  "iOS",
  "iOSApplicationExtension",
  "macOS",
  "macOSApplicationExtension",
  "macCatalyst",
  "macCatalystApplicationExtension",
  "watchOS",
  "watchOSApplicationExtension",
  "tvOS",
  "tvOSApplicationExtension",
  "swift"
];
function swift(hljs) {
  const WHITESPACE = {
    match: /\s+/,
    relevance: 0
  };
  const BLOCK_COMMENT = hljs.COMMENT(
    "/\\*",
    "\\*/",
    { contains: ["self"] }
  );
  const COMMENTS = [
    hljs.C_LINE_COMMENT_MODE,
    BLOCK_COMMENT
  ];
  const DOT_KEYWORD = {
    match: [
      /\./,
      either(...dotKeywords, ...optionalDotKeywords)
    ],
    className: { 2: "keyword" }
  };
  const KEYWORD_GUARD = {
    // Consume .keyword to prevent highlighting properties and methods as keywords.
    match: concat(/\./, either(...keywords)),
    relevance: 0
  };
  const PLAIN_KEYWORDS = keywords.filter((kw) => typeof kw === "string").concat(["_|0"]);
  const REGEX_KEYWORDS = keywords.filter((kw) => typeof kw !== "string").concat(keywordTypes).map(keywordWrapper);
  const KEYWORD = { variants: [
    {
      className: "keyword",
      match: either(...REGEX_KEYWORDS, ...optionalDotKeywords)
    }
  ] };
  const KEYWORDS3 = {
    $pattern: either(
      /\b\w+/,
      // regular keywords
      /#\w+/
      // number keywords
    ),
    keyword: PLAIN_KEYWORDS.concat(numberSignKeywords),
    literal: literals
  };
  const KEYWORD_MODES = [
    DOT_KEYWORD,
    KEYWORD_GUARD,
    KEYWORD
  ];
  const BUILT_IN_GUARD = {
    // Consume .built_in to prevent highlighting properties and methods.
    match: concat(/\./, either(...builtIns)),
    relevance: 0
  };
  const BUILT_IN = {
    className: "built_in",
    match: concat(/\b/, either(...builtIns), /(?=\()/)
  };
  const BUILT_INS3 = [
    BUILT_IN_GUARD,
    BUILT_IN
  ];
  const OPERATOR_GUARD = {
    // Prevent -> from being highlighting as an operator.
    match: /->/,
    relevance: 0
  };
  const OPERATOR = {
    className: "operator",
    relevance: 0,
    variants: [
      { match: operator },
      {
        // dot-operator: only operators that start with a dot are allowed to use dots as
        // characters (..., ...<, .*, etc). So there rule here is: a dot followed by one or more
        // characters that may also include dots.
        match: `\\.(\\.|${operatorCharacter})+`
      }
    ]
  };
  const OPERATORS = [
    OPERATOR_GUARD,
    OPERATOR
  ];
  const decimalDigits3 = "([0-9]_*)+";
  const hexDigits3 = "([0-9a-fA-F]_*)+";
  const NUMBER = {
    className: "number",
    relevance: 0,
    variants: [
      // decimal floating-point-literal (subsumes decimal-literal)
      { match: `\\b(${decimalDigits3})(\\.(${decimalDigits3}))?([eE][+-]?(${decimalDigits3}))?\\b` },
      // hexadecimal floating-point-literal (subsumes hexadecimal-literal)
      { match: `\\b0x(${hexDigits3})(\\.(${hexDigits3}))?([pP][+-]?(${decimalDigits3}))?\\b` },
      // octal-literal
      { match: /\b0o([0-7]_*)+\b/ },
      // binary-literal
      { match: /\b0b([01]_*)+\b/ }
    ]
  };
  const ESCAPED_CHARACTER = (rawDelimiter = "") => ({
    className: "subst",
    variants: [
      { match: concat(/\\/, rawDelimiter, /[0\\tnr"']/) },
      { match: concat(/\\/, rawDelimiter, /u\{[0-9a-fA-F]{1,8}\}/) }
    ]
  });
  const ESCAPED_NEWLINE = (rawDelimiter = "") => ({
    className: "subst",
    match: concat(/\\/, rawDelimiter, /[\t ]*(?:[\r\n]|\r\n)/)
  });
  const INTERPOLATION = (rawDelimiter = "") => ({
    className: "subst",
    label: "interpol",
    begin: concat(/\\/, rawDelimiter, /\(/),
    end: /\)/
  });
  const MULTILINE_STRING = (rawDelimiter = "") => ({
    begin: concat(rawDelimiter, /"""/),
    end: concat(/"""/, rawDelimiter),
    contains: [
      ESCAPED_CHARACTER(rawDelimiter),
      ESCAPED_NEWLINE(rawDelimiter),
      INTERPOLATION(rawDelimiter)
    ]
  });
  const SINGLE_LINE_STRING = (rawDelimiter = "") => ({
    begin: concat(rawDelimiter, /"/),
    end: concat(/"/, rawDelimiter),
    contains: [
      ESCAPED_CHARACTER(rawDelimiter),
      INTERPOLATION(rawDelimiter)
    ]
  });
  const STRING = {
    className: "string",
    variants: [
      MULTILINE_STRING(),
      MULTILINE_STRING("#"),
      MULTILINE_STRING("##"),
      MULTILINE_STRING("###"),
      SINGLE_LINE_STRING(),
      SINGLE_LINE_STRING("#"),
      SINGLE_LINE_STRING("##"),
      SINGLE_LINE_STRING("###")
    ]
  };
  const REGEXP_CONTENTS = [
    hljs.BACKSLASH_ESCAPE,
    {
      begin: /\[/,
      end: /\]/,
      relevance: 0,
      contains: [hljs.BACKSLASH_ESCAPE]
    }
  ];
  const BARE_REGEXP_LITERAL = {
    begin: /\/[^\s](?=[^/\n]*\/)/,
    end: /\//,
    contains: REGEXP_CONTENTS
  };
  const EXTENDED_REGEXP_LITERAL = (rawDelimiter) => {
    const begin = concat(rawDelimiter, /\//);
    const end = concat(/\//, rawDelimiter);
    return {
      begin,
      end,
      contains: [
        ...REGEXP_CONTENTS,
        {
          scope: "comment",
          begin: `#(?!.*${end})`,
          end: /$/
        }
      ]
    };
  };
  const REGEXP = {
    scope: "regexp",
    variants: [
      EXTENDED_REGEXP_LITERAL("###"),
      EXTENDED_REGEXP_LITERAL("##"),
      EXTENDED_REGEXP_LITERAL("#"),
      BARE_REGEXP_LITERAL
    ]
  };
  const QUOTED_IDENTIFIER = { match: concat(/`/, identifier, /`/) };
  const IMPLICIT_PARAMETER = {
    className: "variable",
    match: /\$\d+/
  };
  const PROPERTY_WRAPPER_PROJECTION = {
    className: "variable",
    match: `\\$${identifierCharacter}+`
  };
  const IDENTIFIERS = [
    QUOTED_IDENTIFIER,
    IMPLICIT_PARAMETER,
    PROPERTY_WRAPPER_PROJECTION
  ];
  const AVAILABLE_ATTRIBUTE = {
    match: /(@|#(un)?)available/,
    scope: "keyword",
    starts: { contains: [
      {
        begin: /\(/,
        end: /\)/,
        keywords: availabilityKeywords,
        contains: [
          ...OPERATORS,
          NUMBER,
          STRING
        ]
      }
    ] }
  };
  const KEYWORD_ATTRIBUTE = {
    scope: "keyword",
    match: concat(/@/, either(...keywordAttributes), lookahead(either(/\(/, /\s+/)))
  };
  const USER_DEFINED_ATTRIBUTE = {
    scope: "meta",
    match: concat(/@/, identifier)
  };
  const ATTRIBUTES4 = [
    AVAILABLE_ATTRIBUTE,
    KEYWORD_ATTRIBUTE,
    USER_DEFINED_ATTRIBUTE
  ];
  const TYPE = {
    match: lookahead(/\b[A-Z]/),
    relevance: 0,
    contains: [
      {
        // Common Apple frameworks, for relevance boost
        className: "type",
        match: concat(/(AV|CA|CF|CG|CI|CL|CM|CN|CT|MK|MP|MTK|MTL|NS|SCN|SK|UI|WK|XC)/, identifierCharacter, "+")
      },
      {
        // Type identifier
        className: "type",
        match: typeIdentifier,
        relevance: 0
      },
      {
        // Optional type
        match: /[?!]+/,
        relevance: 0
      },
      {
        // Variadic parameter
        match: /\.\.\./,
        relevance: 0
      },
      {
        // Protocol composition
        match: concat(/\s+&\s+/, lookahead(typeIdentifier)),
        relevance: 0
      }
    ]
  };
  const GENERIC_ARGUMENTS = {
    begin: /</,
    end: />/,
    keywords: KEYWORDS3,
    contains: [
      ...COMMENTS,
      ...KEYWORD_MODES,
      ...ATTRIBUTES4,
      OPERATOR_GUARD,
      TYPE
    ]
  };
  TYPE.contains.push(GENERIC_ARGUMENTS);
  const TUPLE_ELEMENT_NAME = {
    match: concat(identifier, /\s*:/),
    keywords: "_|0",
    relevance: 0
  };
  const TUPLE = {
    begin: /\(/,
    end: /\)/,
    relevance: 0,
    keywords: KEYWORDS3,
    contains: [
      "self",
      TUPLE_ELEMENT_NAME,
      ...COMMENTS,
      REGEXP,
      ...KEYWORD_MODES,
      ...BUILT_INS3,
      ...OPERATORS,
      NUMBER,
      STRING,
      ...IDENTIFIERS,
      ...ATTRIBUTES4,
      TYPE
    ]
  };
  const GENERIC_PARAMETERS = {
    begin: /</,
    end: />/,
    keywords: "repeat each",
    contains: [
      ...COMMENTS,
      TYPE
    ]
  };
  const FUNCTION_PARAMETER_NAME = {
    begin: either(
      lookahead(concat(identifier, /\s*:/)),
      lookahead(concat(identifier, /\s+/, identifier, /\s*:/))
    ),
    end: /:/,
    relevance: 0,
    contains: [
      {
        className: "keyword",
        match: /\b_\b/
      },
      {
        className: "params",
        match: identifier
      }
    ]
  };
  const FUNCTION_PARAMETERS = {
    begin: /\(/,
    end: /\)/,
    keywords: KEYWORDS3,
    contains: [
      FUNCTION_PARAMETER_NAME,
      ...COMMENTS,
      ...KEYWORD_MODES,
      ...OPERATORS,
      NUMBER,
      STRING,
      ...ATTRIBUTES4,
      TYPE,
      TUPLE
    ],
    endsParent: true,
    illegal: /["']/
  };
  const FUNCTION_OR_MACRO = {
    match: [
      /(func|macro)/,
      /\s+/,
      either(QUOTED_IDENTIFIER.match, identifier, operator)
    ],
    className: {
      1: "keyword",
      3: "title.function"
    },
    contains: [
      GENERIC_PARAMETERS,
      FUNCTION_PARAMETERS,
      WHITESPACE
    ],
    illegal: [
      /\[/,
      /%/
    ]
  };
  const INIT_SUBSCRIPT = {
    match: [
      /\b(?:subscript|init[?!]?)/,
      /\s*(?=[<(])/
    ],
    className: { 1: "keyword" },
    contains: [
      GENERIC_PARAMETERS,
      FUNCTION_PARAMETERS,
      WHITESPACE
    ],
    illegal: /\[|%/
  };
  const OPERATOR_DECLARATION = {
    match: [
      /operator/,
      /\s+/,
      operator
    ],
    className: {
      1: "keyword",
      3: "title"
    }
  };
  const PRECEDENCEGROUP = {
    begin: [
      /precedencegroup/,
      /\s+/,
      typeIdentifier
    ],
    className: {
      1: "keyword",
      3: "title"
    },
    contains: [TYPE],
    keywords: [
      ...precedencegroupKeywords,
      ...literals
    ],
    end: /}/
  };
  const CLASS_FUNC_DECLARATION = {
    match: [
      /class\b/,
      /\s+/,
      /func\b/,
      /\s+/,
      /\b[A-Za-z_][A-Za-z0-9_]*\b/
    ],
    scope: {
      1: "keyword",
      3: "keyword",
      5: "title.function"
    }
  };
  const CLASS_VAR_DECLARATION = {
    match: [
      /class\b/,
      /\s+/,
      /var\b/
    ],
    scope: {
      1: "keyword",
      3: "keyword"
    }
  };
  const TYPE_DECLARATION = {
    begin: [
      /(struct|protocol|class|extension|enum|actor)/,
      /\s+/,
      identifier,
      /\s*/
    ],
    beginScope: {
      1: "keyword",
      3: "title.class"
    },
    keywords: KEYWORDS3,
    contains: [
      GENERIC_PARAMETERS,
      ...KEYWORD_MODES,
      {
        begin: /:/,
        end: /\{/,
        keywords: KEYWORDS3,
        contains: [
          {
            scope: "title.class.inherited",
            match: typeIdentifier
          },
          ...KEYWORD_MODES
        ],
        relevance: 0
      }
    ]
  };
  for (const variant of STRING.variants) {
    const interpolation = variant.contains.find((mode) => mode.label === "interpol");
    interpolation.keywords = KEYWORDS3;
    const submodes = [
      ...KEYWORD_MODES,
      ...BUILT_INS3,
      ...OPERATORS,
      NUMBER,
      STRING,
      ...IDENTIFIERS
    ];
    interpolation.contains = [
      ...submodes,
      {
        begin: /\(/,
        end: /\)/,
        contains: [
          "self",
          ...submodes
        ]
      }
    ];
  }
  return {
    name: "Swift",
    keywords: KEYWORDS3,
    contains: [
      ...COMMENTS,
      FUNCTION_OR_MACRO,
      INIT_SUBSCRIPT,
      CLASS_FUNC_DECLARATION,
      CLASS_VAR_DECLARATION,
      TYPE_DECLARATION,
      OPERATOR_DECLARATION,
      PRECEDENCEGROUP,
      {
        beginKeywords: "import",
        end: /$/,
        contains: [...COMMENTS],
        relevance: 0
      },
      REGEXP,
      ...KEYWORD_MODES,
      ...BUILT_INS3,
      ...OPERATORS,
      NUMBER,
      STRING,
      ...IDENTIFIERS,
      ...ATTRIBUTES4,
      TYPE,
      TUPLE
    ]
  };
}

// node_modules/highlight.js/es/languages/typescript.js
var IDENT_RE2 = "[A-Za-z$_][0-9A-Za-z$_]*";
var KEYWORDS2 = [
  "as",
  // for exports
  "in",
  "of",
  "if",
  "for",
  "while",
  "finally",
  "var",
  "new",
  "function",
  "do",
  "return",
  "void",
  "else",
  "break",
  "catch",
  "instanceof",
  "with",
  "throw",
  "case",
  "default",
  "try",
  "switch",
  "continue",
  "typeof",
  "delete",
  "let",
  "yield",
  "const",
  "class",
  // JS handles these with a special rule
  // "get",
  // "set",
  "debugger",
  "async",
  "await",
  "static",
  "import",
  "from",
  "export",
  "extends",
  // It's reached stage 3, which is "recommended for implementation":
  "using"
];
var LITERALS2 = [
  "true",
  "false",
  "null",
  "undefined",
  "NaN",
  "Infinity"
];
var TYPES2 = [
  // Fundamental objects
  "Object",
  "Function",
  "Boolean",
  "Symbol",
  // numbers and dates
  "Math",
  "Date",
  "Number",
  "BigInt",
  // text
  "String",
  "RegExp",
  // Indexed collections
  "Array",
  "Float32Array",
  "Float64Array",
  "Int8Array",
  "Uint8Array",
  "Uint8ClampedArray",
  "Int16Array",
  "Int32Array",
  "Uint16Array",
  "Uint32Array",
  "BigInt64Array",
  "BigUint64Array",
  // Keyed collections
  "Set",
  "Map",
  "WeakSet",
  "WeakMap",
  // Structured data
  "ArrayBuffer",
  "SharedArrayBuffer",
  "Atomics",
  "DataView",
  "JSON",
  // Control abstraction objects
  "Promise",
  "Generator",
  "GeneratorFunction",
  "AsyncFunction",
  // Reflection
  "Reflect",
  "Proxy",
  // Internationalization
  "Intl",
  // WebAssembly
  "WebAssembly"
];
var ERROR_TYPES2 = [
  "Error",
  "EvalError",
  "InternalError",
  "RangeError",
  "ReferenceError",
  "SyntaxError",
  "TypeError",
  "URIError"
];
var BUILT_IN_GLOBALS2 = [
  "setInterval",
  "setTimeout",
  "clearInterval",
  "clearTimeout",
  "require",
  "exports",
  "eval",
  "isFinite",
  "isNaN",
  "parseFloat",
  "parseInt",
  "decodeURI",
  "decodeURIComponent",
  "encodeURI",
  "encodeURIComponent",
  "escape",
  "unescape"
];
var BUILT_IN_VARIABLES2 = [
  "arguments",
  "this",
  "super",
  "console",
  "window",
  "document",
  "localStorage",
  "sessionStorage",
  "module",
  "global"
  // Node.js
];
var BUILT_INS2 = [].concat(
  BUILT_IN_GLOBALS2,
  TYPES2,
  ERROR_TYPES2
);
function javascript2(hljs) {
  const regex = hljs.regex;
  const hasClosingTag = (match, { after }) => {
    const tag = "</" + match[0].slice(1);
    const pos = match.input.indexOf(tag, after);
    return pos !== -1;
  };
  const IDENT_RE$1 = IDENT_RE2;
  const FRAGMENT = {
    begin: "<>",
    end: "</>"
  };
  const XML_SELF_CLOSING = /<[A-Za-z0-9\\._:-]+\s*\/>/;
  const XML_TAG = {
    begin: /<[A-Za-z0-9\\._:-]+/,
    end: /\/[A-Za-z0-9\\._:-]+>|\/>/,
    /**
     * @param {RegExpMatchArray} match
     * @param {CallbackResponse} response
     */
    isTrulyOpeningTag: (match, response) => {
      const afterMatchIndex = match[0].length + match.index;
      const nextChar = match.input[afterMatchIndex];
      if (
        // HTML should not include another raw `<` inside a tag
        // nested type?
        // `<Array<Array<number>>`, etc.
        nextChar === "<" || // the , gives away that this is not HTML
        // `<T, A extends keyof T, V>`
        nextChar === ","
      ) {
        response.ignoreMatch();
        return;
      }
      if (nextChar === ">") {
        if (!hasClosingTag(match, { after: afterMatchIndex })) {
          response.ignoreMatch();
        }
      }
      let m;
      const afterMatch = match.input.substring(afterMatchIndex);
      if (m = afterMatch.match(/^\s*=/)) {
        response.ignoreMatch();
        return;
      }
      if (m = afterMatch.match(/^\s+extends\s+/)) {
        if (m.index === 0) {
          response.ignoreMatch();
          return;
        }
      }
    }
  };
  const KEYWORDS$1 = {
    $pattern: IDENT_RE2,
    keyword: KEYWORDS2,
    literal: LITERALS2,
    built_in: BUILT_INS2,
    "variable.language": BUILT_IN_VARIABLES2
  };
  const decimalDigits3 = "[0-9](_?[0-9])*";
  const frac3 = `\\.(${decimalDigits3})`;
  const decimalInteger = `0|[1-9](_?[0-9])*|0[0-7]*[89][0-9]*`;
  const NUMBER = {
    className: "number",
    variants: [
      // DecimalLiteral
      { begin: `(\\b(${decimalInteger})((${frac3})|\\.)?|(${frac3}))[eE][+-]?(${decimalDigits3})\\b` },
      { begin: `\\b(${decimalInteger})\\b((${frac3})\\b|\\.)?|(${frac3})\\b` },
      // DecimalBigIntegerLiteral
      { begin: `\\b(0|[1-9](_?[0-9])*)n\\b` },
      // NonDecimalIntegerLiteral
      { begin: "\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*n?\\b" },
      { begin: "\\b0[bB][0-1](_?[0-1])*n?\\b" },
      { begin: "\\b0[oO][0-7](_?[0-7])*n?\\b" },
      // LegacyOctalIntegerLiteral (does not include underscore separators)
      // https://tc39.es/ecma262/#sec-additional-syntax-numeric-literals
      { begin: "\\b0[0-7]+n?\\b" }
    ],
    relevance: 0
  };
  const SUBST = {
    className: "subst",
    begin: "\\$\\{",
    end: "\\}",
    keywords: KEYWORDS$1,
    contains: []
    // defined later
  };
  const HTML_TEMPLATE = {
    begin: ".?html`",
    end: "",
    starts: {
      end: "`",
      returnEnd: false,
      contains: [
        hljs.BACKSLASH_ESCAPE,
        SUBST
      ],
      subLanguage: "xml"
    }
  };
  const CSS_TEMPLATE = {
    begin: ".?css`",
    end: "",
    starts: {
      end: "`",
      returnEnd: false,
      contains: [
        hljs.BACKSLASH_ESCAPE,
        SUBST
      ],
      subLanguage: "css"
    }
  };
  const GRAPHQL_TEMPLATE = {
    begin: ".?gql`",
    end: "",
    starts: {
      end: "`",
      returnEnd: false,
      contains: [
        hljs.BACKSLASH_ESCAPE,
        SUBST
      ],
      subLanguage: "graphql"
    }
  };
  const TEMPLATE_STRING = {
    className: "string",
    begin: "`",
    end: "`",
    contains: [
      hljs.BACKSLASH_ESCAPE,
      SUBST
    ]
  };
  const JSDOC_COMMENT = hljs.COMMENT(
    /\/\*\*(?!\/)/,
    "\\*/",
    {
      relevance: 0,
      contains: [
        {
          begin: "(?=@[A-Za-z]+)",
          relevance: 0,
          contains: [
            {
              className: "doctag",
              begin: "@[A-Za-z]+"
            },
            {
              className: "type",
              begin: "\\{",
              end: "\\}",
              excludeEnd: true,
              excludeBegin: true,
              relevance: 0
            },
            {
              className: "variable",
              begin: IDENT_RE$1 + "(?=\\s*(-)|$)",
              endsParent: true,
              relevance: 0
            },
            // eat spaces (not newlines) so we can find
            // types or variables
            {
              begin: /(?=[^\n])\s/,
              relevance: 0
            }
          ]
        }
      ]
    }
  );
  const COMMENT = {
    className: "comment",
    variants: [
      JSDOC_COMMENT,
      hljs.C_BLOCK_COMMENT_MODE,
      hljs.C_LINE_COMMENT_MODE
    ]
  };
  const SUBST_INTERNALS = [
    hljs.APOS_STRING_MODE,
    hljs.QUOTE_STRING_MODE,
    HTML_TEMPLATE,
    CSS_TEMPLATE,
    GRAPHQL_TEMPLATE,
    TEMPLATE_STRING,
    // Skip numbers when they are part of a variable name
    { match: /\$\d+/ },
    NUMBER
    // This is intentional:
    // See https://github.com/highlightjs/highlight.js/issues/3288
    // hljs.REGEXP_MODE
  ];
  SUBST.contains = SUBST_INTERNALS.concat({
    // we need to pair up {} inside our subst to prevent
    // it from ending too early by matching another }
    begin: /\{/,
    end: /\}/,
    keywords: KEYWORDS$1,
    contains: [
      "self"
    ].concat(SUBST_INTERNALS)
  });
  const SUBST_AND_COMMENTS = [].concat(COMMENT, SUBST.contains);
  const PARAMS_CONTAINS = SUBST_AND_COMMENTS.concat([
    // eat recursive parens in sub expressions
    {
      begin: /(\s*)\(/,
      end: /\)/,
      keywords: KEYWORDS$1,
      contains: ["self"].concat(SUBST_AND_COMMENTS)
    }
  ]);
  const PARAMS = {
    className: "params",
    // convert this to negative lookbehind in v12
    begin: /(\s*)\(/,
    // to match the parms with
    end: /\)/,
    excludeBegin: true,
    excludeEnd: true,
    keywords: KEYWORDS$1,
    contains: PARAMS_CONTAINS
  };
  const CLASS_OR_EXTENDS = {
    variants: [
      // class Car extends vehicle
      {
        match: [
          /class/,
          /\s+/,
          IDENT_RE$1,
          /\s+/,
          /extends/,
          /\s+/,
          regex.concat(IDENT_RE$1, "(", regex.concat(/\./, IDENT_RE$1), ")*")
        ],
        scope: {
          1: "keyword",
          3: "title.class",
          5: "keyword",
          7: "title.class.inherited"
        }
      },
      // class Car
      {
        match: [
          /class/,
          /\s+/,
          IDENT_RE$1
        ],
        scope: {
          1: "keyword",
          3: "title.class"
        }
      }
    ]
  };
  const CLASS_REFERENCE = {
    relevance: 0,
    match: regex.either(
      // Hard coded exceptions
      /\bJSON/,
      // Float32Array, OutT
      /\b[A-Z][a-z]+([A-Z][a-z]*|\d)*/,
      // CSSFactory, CSSFactoryT
      /\b[A-Z]{2,}([A-Z][a-z]+|\d)+([A-Z][a-z]*)*/,
      // FPs, FPsT
      /\b[A-Z]{2,}[a-z]+([A-Z][a-z]+|\d)*([A-Z][a-z]*)*/
      // P
      // single letters are not highlighted
      // BLAH
      // this will be flagged as a UPPER_CASE_CONSTANT instead
    ),
    className: "title.class",
    keywords: {
      _: [
        // se we still get relevance credit for JS library classes
        ...TYPES2,
        ...ERROR_TYPES2
      ]
    }
  };
  const USE_STRICT = {
    label: "use_strict",
    className: "meta",
    relevance: 10,
    begin: /^\s*['"]use (strict|asm)['"]/
  };
  const FUNCTION_DEFINITION = {
    variants: [
      {
        match: [
          /function/,
          /\s+/,
          IDENT_RE$1,
          /(?=\s*\()/
        ]
      },
      // anonymous function
      {
        match: [
          /function/,
          /\s*(?=\()/
        ]
      }
    ],
    className: {
      1: "keyword",
      3: "title.function"
    },
    label: "func.def",
    contains: [PARAMS],
    illegal: /%/
  };
  const UPPER_CASE_CONSTANT = {
    relevance: 0,
    match: /\b[A-Z][A-Z_0-9]+\b/,
    className: "variable.constant"
  };
  function noneOf(list) {
    return regex.concat("(?!", list.join("|"), ")");
  }
  const FUNCTION_CALL = {
    match: regex.concat(
      /\b/,
      noneOf([
        ...BUILT_IN_GLOBALS2,
        "super",
        "import"
      ].map((x) => `${x}\\s*\\(`)),
      IDENT_RE$1,
      regex.lookahead(/\s*\(/)
    ),
    className: "title.function",
    relevance: 0
  };
  const PROPERTY_ACCESS = {
    begin: regex.concat(/\./, regex.lookahead(
      regex.concat(IDENT_RE$1, /(?![0-9A-Za-z$_(])/)
    )),
    end: IDENT_RE$1,
    excludeBegin: true,
    keywords: "prototype",
    className: "property",
    relevance: 0
  };
  const GETTER_OR_SETTER = {
    match: [
      /get|set/,
      /\s+/,
      IDENT_RE$1,
      /(?=\()/
    ],
    className: {
      1: "keyword",
      3: "title.function"
    },
    contains: [
      {
        // eat to avoid empty params
        begin: /\(\)/
      },
      PARAMS
    ]
  };
  const FUNC_LEAD_IN_RE = "(\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)|" + hljs.UNDERSCORE_IDENT_RE + ")\\s*=>";
  const FUNCTION_VARIABLE = {
    match: [
      /const|var|let/,
      /\s+/,
      IDENT_RE$1,
      /\s*/,
      /=\s*/,
      /(async\s*)?/,
      // async is optional
      regex.lookahead(FUNC_LEAD_IN_RE)
    ],
    keywords: "async",
    className: {
      1: "keyword",
      3: "title.function"
    },
    contains: [
      PARAMS
    ]
  };
  return {
    name: "JavaScript",
    aliases: ["js", "jsx", "mjs", "cjs"],
    keywords: KEYWORDS$1,
    // this will be extended by TypeScript
    exports: { PARAMS_CONTAINS, CLASS_REFERENCE },
    illegal: /#(?![$_A-z])/,
    contains: [
      hljs.SHEBANG({
        label: "shebang",
        binary: "node",
        relevance: 5
      }),
      USE_STRICT,
      hljs.APOS_STRING_MODE,
      hljs.QUOTE_STRING_MODE,
      HTML_TEMPLATE,
      CSS_TEMPLATE,
      GRAPHQL_TEMPLATE,
      TEMPLATE_STRING,
      COMMENT,
      // Skip numbers when they are part of a variable name
      { match: /\$\d+/ },
      NUMBER,
      CLASS_REFERENCE,
      {
        scope: "attr",
        match: IDENT_RE$1 + regex.lookahead(":"),
        relevance: 0
      },
      FUNCTION_VARIABLE,
      {
        // "value" container
        begin: "(" + hljs.RE_STARTERS_RE + "|\\b(case|return|throw)\\b)\\s*",
        keywords: "return throw case",
        relevance: 0,
        contains: [
          COMMENT,
          hljs.REGEXP_MODE,
          {
            className: "function",
            // we have to count the parens to make sure we actually have the
            // correct bounding ( ) before the =>.  There could be any number of
            // sub-expressions inside also surrounded by parens.
            begin: FUNC_LEAD_IN_RE,
            returnBegin: true,
            end: "\\s*=>",
            contains: [
              {
                className: "params",
                variants: [
                  {
                    begin: hljs.UNDERSCORE_IDENT_RE,
                    relevance: 0
                  },
                  {
                    className: null,
                    begin: /\(\s*\)/,
                    skip: true
                  },
                  {
                    begin: /(\s*)\(/,
                    end: /\)/,
                    excludeBegin: true,
                    excludeEnd: true,
                    keywords: KEYWORDS$1,
                    contains: PARAMS_CONTAINS
                  }
                ]
              }
            ]
          },
          {
            // could be a comma delimited list of params to a function call
            begin: /,/,
            relevance: 0
          },
          {
            match: /\s+/,
            relevance: 0
          },
          {
            // JSX
            variants: [
              { begin: FRAGMENT.begin, end: FRAGMENT.end },
              { match: XML_SELF_CLOSING },
              {
                begin: XML_TAG.begin,
                // we carefully check the opening tag to see if it truly
                // is a tag and not a false positive
                "on:begin": XML_TAG.isTrulyOpeningTag,
                end: XML_TAG.end
              }
            ],
            subLanguage: "xml",
            contains: [
              {
                begin: XML_TAG.begin,
                end: XML_TAG.end,
                skip: true,
                contains: ["self"]
              }
            ]
          }
        ]
      },
      FUNCTION_DEFINITION,
      {
        // prevent this from getting swallowed up by function
        // since they appear "function like"
        beginKeywords: "while if switch catch for"
      },
      {
        // we have to count the parens to make sure we actually have the correct
        // bounding ( ).  There could be any number of sub-expressions inside
        // also surrounded by parens.
        begin: "\\b(?!function)" + hljs.UNDERSCORE_IDENT_RE + "\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)\\s*\\{",
        // end parens
        returnBegin: true,
        label: "func.def",
        contains: [
          PARAMS,
          hljs.inherit(hljs.TITLE_MODE, { begin: IDENT_RE$1, className: "title.function" })
        ]
      },
      // catch ... so it won't trigger the property rule below
      {
        match: /\.\.\./,
        relevance: 0
      },
      PROPERTY_ACCESS,
      // hack: prevents detection of keywords in some circumstances
      // .keyword()
      // $keyword = x
      {
        match: "\\$" + IDENT_RE$1,
        relevance: 0
      },
      {
        match: [/\bconstructor(?=\s*\()/],
        className: { 1: "title.function" },
        contains: [PARAMS]
      },
      FUNCTION_CALL,
      UPPER_CASE_CONSTANT,
      CLASS_OR_EXTENDS,
      GETTER_OR_SETTER,
      {
        match: /\$[(.]/
        // relevance booster for a pattern common to JS libs: `$(something)` and `$.something`
      }
    ]
  };
}
function typescript(hljs) {
  const regex = hljs.regex;
  const tsLanguage = javascript2(hljs);
  const IDENT_RE$1 = IDENT_RE2;
  const TYPES3 = [
    "any",
    "void",
    "number",
    "boolean",
    "string",
    "object",
    "never",
    "symbol",
    "bigint",
    "unknown"
  ];
  const NAMESPACE = {
    begin: [
      /namespace/,
      /\s+/,
      hljs.IDENT_RE
    ],
    beginScope: {
      1: "keyword",
      3: "title.class"
    }
  };
  const INTERFACE = {
    beginKeywords: "interface",
    end: /\{/,
    excludeEnd: true,
    keywords: {
      keyword: "interface extends",
      built_in: TYPES3
    },
    contains: [tsLanguage.exports.CLASS_REFERENCE]
  };
  const USE_STRICT = {
    className: "meta",
    relevance: 10,
    begin: /^\s*['"]use strict['"]/
  };
  const TS_SPECIFIC_KEYWORDS = [
    "type",
    // "namespace",
    "interface",
    "public",
    "private",
    "protected",
    "implements",
    "declare",
    "abstract",
    "readonly",
    "enum",
    "override",
    "satisfies"
  ];
  const KEYWORDS$1 = {
    $pattern: IDENT_RE2,
    keyword: KEYWORDS2.concat(TS_SPECIFIC_KEYWORDS),
    literal: LITERALS2,
    built_in: BUILT_INS2.concat(TYPES3),
    "variable.language": BUILT_IN_VARIABLES2
  };
  const DECORATOR = {
    className: "meta",
    begin: "@" + IDENT_RE$1
  };
  const swapMode = (mode, label, replacement) => {
    const indx = mode.contains.findIndex((m) => m.label === label);
    if (indx === -1) {
      throw new Error("can not find mode to replace");
    }
    mode.contains.splice(indx, 1, replacement);
  };
  Object.assign(tsLanguage.keywords, KEYWORDS$1);
  tsLanguage.exports.PARAMS_CONTAINS.push(DECORATOR);
  const ATTRIBUTE_HIGHLIGHT = tsLanguage.contains.find((c2) => c2.scope === "attr");
  const OPTIONAL_KEY_OR_ARGUMENT = Object.assign(
    {},
    ATTRIBUTE_HIGHLIGHT,
    { match: regex.concat(IDENT_RE$1, regex.lookahead(/\s*\?:/)) }
  );
  tsLanguage.exports.PARAMS_CONTAINS.push([
    tsLanguage.exports.CLASS_REFERENCE,
    // class reference for highlighting the params types
    ATTRIBUTE_HIGHLIGHT,
    // highlight the params key
    OPTIONAL_KEY_OR_ARGUMENT
    // Added for optional property assignment highlighting
  ]);
  tsLanguage.contains = tsLanguage.contains.concat([
    DECORATOR,
    NAMESPACE,
    INTERFACE,
    OPTIONAL_KEY_OR_ARGUMENT
    // Added for optional property assignment highlighting
  ]);
  swapMode(tsLanguage, "shebang", hljs.SHEBANG());
  swapMode(tsLanguage, "use_strict", USE_STRICT);
  const functionDeclaration = tsLanguage.contains.find((m) => m.label === "func.def");
  functionDeclaration.relevance = 0;
  Object.assign(tsLanguage, {
    name: "TypeScript",
    aliases: [
      "ts",
      "tsx",
      "mts",
      "cts"
    ]
  });
  return tsLanguage;
}

// node_modules/highlight.js/es/languages/vbnet.js
function vbnet(hljs) {
  const regex = hljs.regex;
  const CHARACTER = {
    className: "string",
    begin: /"(""|[^/n])"C\b/
  };
  const STRING = {
    className: "string",
    begin: /"/,
    end: /"/,
    illegal: /\n/,
    contains: [
      {
        // double quote escape
        begin: /""/
      }
    ]
  };
  const MM_DD_YYYY = /\d{1,2}\/\d{1,2}\/\d{4}/;
  const YYYY_MM_DD = /\d{4}-\d{1,2}-\d{1,2}/;
  const TIME_12H = /(\d|1[012])(:\d+){0,2} *(AM|PM)/;
  const TIME_24H = /\d{1,2}(:\d{1,2}){1,2}/;
  const DATE = {
    className: "literal",
    variants: [
      {
        // #YYYY-MM-DD# (ISO-Date) or #M/D/YYYY# (US-Date)
        begin: regex.concat(/# */, regex.either(YYYY_MM_DD, MM_DD_YYYY), / *#/)
      },
      {
        // #H:mm[:ss]# (24h Time)
        begin: regex.concat(/# */, TIME_24H, / *#/)
      },
      {
        // #h[:mm[:ss]] A# (12h Time)
        begin: regex.concat(/# */, TIME_12H, / *#/)
      },
      {
        // date plus time
        begin: regex.concat(
          /# */,
          regex.either(YYYY_MM_DD, MM_DD_YYYY),
          / +/,
          regex.either(TIME_12H, TIME_24H),
          / *#/
        )
      }
    ]
  };
  const NUMBER = {
    className: "number",
    relevance: 0,
    variants: [
      {
        // Float
        begin: /\b\d[\d_]*((\.[\d_]+(E[+-]?[\d_]+)?)|(E[+-]?[\d_]+))[RFD@!#]?/
      },
      {
        // Integer (base 10)
        begin: /\b\d[\d_]*((U?[SIL])|[%&])?/
      },
      {
        // Integer (base 16)
        begin: /&H[\dA-F_]+((U?[SIL])|[%&])?/
      },
      {
        // Integer (base 8)
        begin: /&O[0-7_]+((U?[SIL])|[%&])?/
      },
      {
        // Integer (base 2)
        begin: /&B[01_]+((U?[SIL])|[%&])?/
      }
    ]
  };
  const LABEL = {
    className: "label",
    begin: /^\w+:/
  };
  const DOC_COMMENT = hljs.COMMENT(/'''/, /$/, { contains: [
    {
      className: "doctag",
      begin: /<\/?/,
      end: />/
    }
  ] });
  const COMMENT = hljs.COMMENT(null, /$/, { variants: [
    { begin: /'/ },
    {
      // TODO: Use multi-class for leading spaces
      begin: /([\t ]|^)REM(?=\s)/
    }
  ] });
  const DIRECTIVES = {
    className: "meta",
    // TODO: Use multi-class for indentation once available
    begin: /[\t ]*#(const|disable|else|elseif|enable|end|externalsource|if|region)\b/,
    end: /$/,
    keywords: { keyword: "const disable else elseif enable end externalsource if region then" },
    contains: [COMMENT]
  };
  return {
    name: "Visual Basic .NET",
    aliases: ["vb"],
    case_insensitive: true,
    classNameAliases: { label: "symbol" },
    keywords: {
      keyword: "addhandler alias aggregate ansi as async assembly auto binary by byref byval call case catch class compare const continue custom declare default delegate dim distinct do each equals else elseif end enum erase error event exit explicit finally for friend from function get global goto group handles if implements imports in inherits interface into iterator join key let lib loop me mid module mustinherit mustoverride mybase myclass namespace narrowing new next notinheritable notoverridable of off on operator option optional order overloads overridable overrides paramarray partial preserve private property protected public raiseevent readonly redim removehandler resume return select set shadows shared skip static step stop structure strict sub synclock take text then throw to try unicode until using when where while widening with withevents writeonly yield",
      built_in: (
        // Operators https://docs.microsoft.com/dotnet/visual-basic/language-reference/operators
        "addressof and andalso await directcast gettype getxmlnamespace is isfalse isnot istrue like mod nameof new not or orelse trycast typeof xor cbool cbyte cchar cdate cdbl cdec cint clng cobj csbyte cshort csng cstr cuint culng cushort"
      ),
      type: (
        // Data types https://docs.microsoft.com/dotnet/visual-basic/language-reference/data-types
        "boolean byte char date decimal double integer long object sbyte short single string uinteger ulong ushort"
      ),
      literal: "true false nothing"
    },
    illegal: "//|\\{|\\}|endif|gosub|variant|wend|^\\$ ",
    contains: [
      CHARACTER,
      STRING,
      DATE,
      NUMBER,
      LABEL,
      DOC_COMMENT,
      COMMENT,
      DIRECTIVES
    ]
  };
}

// node_modules/highlight.js/es/languages/wasm.js
function wasm(hljs) {
  hljs.regex;
  const BLOCK_COMMENT = hljs.COMMENT(/\(;/, /;\)/);
  BLOCK_COMMENT.contains.push("self");
  const LINE_COMMENT = hljs.COMMENT(/;;/, /$/);
  const KWS = [
    "anyfunc",
    "block",
    "br",
    "br_if",
    "br_table",
    "call",
    "call_indirect",
    "data",
    "drop",
    "elem",
    "else",
    "end",
    "export",
    "func",
    "global.get",
    "global.set",
    "local.get",
    "local.set",
    "local.tee",
    "get_global",
    "get_local",
    "global",
    "if",
    "import",
    "local",
    "loop",
    "memory",
    "memory.grow",
    "memory.size",
    "module",
    "mut",
    "nop",
    "offset",
    "param",
    "result",
    "return",
    "select",
    "set_global",
    "set_local",
    "start",
    "table",
    "tee_local",
    "then",
    "type",
    "unreachable"
  ];
  const FUNCTION_REFERENCE = {
    begin: [
      /(?:func|call|call_indirect)/,
      /\s+/,
      /\$[^\s)]+/
    ],
    className: {
      1: "keyword",
      3: "title.function"
    }
  };
  const ARGUMENT = {
    className: "variable",
    begin: /\$[\w_]+/
  };
  const PARENS = {
    match: /(\((?!;)|\))+/,
    className: "punctuation",
    relevance: 0
  };
  const NUMBER = {
    className: "number",
    relevance: 0,
    // borrowed from Prism, TODO: split out into variants
    match: /[+-]?\b(?:\d(?:_?\d)*(?:\.\d(?:_?\d)*)?(?:[eE][+-]?\d(?:_?\d)*)?|0x[\da-fA-F](?:_?[\da-fA-F])*(?:\.[\da-fA-F](?:_?[\da-fA-D])*)?(?:[pP][+-]?\d(?:_?\d)*)?)\b|\binf\b|\bnan(?::0x[\da-fA-F](?:_?[\da-fA-D])*)?\b/
  };
  const TYPE = {
    // look-ahead prevents us from gobbling up opcodes
    match: /(i32|i64|f32|f64)(?!\.)/,
    className: "type"
  };
  const MATH_OPERATIONS = {
    className: "keyword",
    // borrowed from Prism, TODO: split out into variants
    match: /\b(f32|f64|i32|i64)(?:\.(?:abs|add|and|ceil|clz|const|convert_[su]\/i(?:32|64)|copysign|ctz|demote\/f64|div(?:_[su])?|eqz?|extend_[su]\/i32|floor|ge(?:_[su])?|gt(?:_[su])?|le(?:_[su])?|load(?:(?:8|16|32)_[su])?|lt(?:_[su])?|max|min|mul|nearest|neg?|or|popcnt|promote\/f32|reinterpret\/[fi](?:32|64)|rem_[su]|rot[lr]|shl|shr_[su]|store(?:8|16|32)?|sqrt|sub|trunc(?:_[su]\/f(?:32|64))?|wrap\/i64|xor))\b/
  };
  const OFFSET_ALIGN = {
    match: [
      /(?:offset|align)/,
      /\s*/,
      /=/
    ],
    className: {
      1: "keyword",
      3: "operator"
    }
  };
  return {
    name: "WebAssembly",
    keywords: {
      $pattern: /[\w.]+/,
      keyword: KWS
    },
    contains: [
      LINE_COMMENT,
      BLOCK_COMMENT,
      OFFSET_ALIGN,
      ARGUMENT,
      PARENS,
      FUNCTION_REFERENCE,
      hljs.QUOTE_STRING_MODE,
      TYPE,
      MATH_OPERATIONS,
      NUMBER
    ]
  };
}

// node_modules/highlight.js/es/languages/xml.js
function xml(hljs) {
  const regex = hljs.regex;
  const TAG_NAME_RE = regex.concat(/[\p{L}_]/u, regex.optional(/[\p{L}0-9_.-]*:/u), /[\p{L}0-9_.-]*/u);
  const XML_IDENT_RE = /[\p{L}0-9._:-]+/u;
  const XML_ENTITIES = {
    className: "symbol",
    begin: /&[a-z]+;|&#[0-9]+;|&#x[a-f0-9]+;/
  };
  const XML_META_KEYWORDS = {
    begin: /\s/,
    contains: [
      {
        className: "keyword",
        begin: /#?[a-z_][a-z1-9_-]+/,
        illegal: /\n/
      }
    ]
  };
  const XML_META_PAR_KEYWORDS = hljs.inherit(XML_META_KEYWORDS, {
    begin: /\(/,
    end: /\)/
  });
  const APOS_META_STRING_MODE = hljs.inherit(hljs.APOS_STRING_MODE, { className: "string" });
  const QUOTE_META_STRING_MODE = hljs.inherit(hljs.QUOTE_STRING_MODE, { className: "string" });
  const TAG_INTERNALS = {
    endsWithParent: true,
    illegal: /</,
    relevance: 0,
    contains: [
      {
        className: "attr",
        begin: XML_IDENT_RE,
        relevance: 0
      },
      {
        begin: /=\s*/,
        relevance: 0,
        contains: [
          {
            className: "string",
            endsParent: true,
            variants: [
              {
                begin: /"/,
                end: /"/,
                contains: [XML_ENTITIES]
              },
              {
                begin: /'/,
                end: /'/,
                contains: [XML_ENTITIES]
              },
              { begin: /[^\s"'=<>`]+/ }
            ]
          }
        ]
      }
    ]
  };
  return {
    name: "HTML, XML",
    aliases: [
      "html",
      "xhtml",
      "rss",
      "atom",
      "xjb",
      "xsd",
      "xsl",
      "plist",
      "wsf",
      "svg"
    ],
    case_insensitive: true,
    unicodeRegex: true,
    contains: [
      {
        className: "meta",
        begin: /<![a-z]/,
        end: />/,
        relevance: 10,
        contains: [
          XML_META_KEYWORDS,
          QUOTE_META_STRING_MODE,
          APOS_META_STRING_MODE,
          XML_META_PAR_KEYWORDS,
          {
            begin: /\[/,
            end: /\]/,
            contains: [
              {
                className: "meta",
                begin: /<![a-z]/,
                end: />/,
                contains: [
                  XML_META_KEYWORDS,
                  XML_META_PAR_KEYWORDS,
                  QUOTE_META_STRING_MODE,
                  APOS_META_STRING_MODE
                ]
              }
            ]
          }
        ]
      },
      hljs.COMMENT(
        /<!--/,
        /-->/,
        { relevance: 10 }
      ),
      {
        begin: /<!\[CDATA\[/,
        end: /\]\]>/,
        relevance: 10
      },
      XML_ENTITIES,
      // xml processing instructions
      {
        className: "meta",
        end: /\?>/,
        variants: [
          {
            begin: /<\?xml/,
            relevance: 10,
            contains: [
              QUOTE_META_STRING_MODE
            ]
          },
          {
            begin: /<\?[a-z][a-z0-9]+/
          }
        ]
      },
      {
        className: "tag",
        /*
        The lookahead pattern (?=...) ensures that 'begin' only matches
        '<style' as a single word, followed by a whitespace or an
        ending bracket.
        */
        begin: /<style(?=\s|>)/,
        end: />/,
        keywords: { name: "style" },
        contains: [TAG_INTERNALS],
        starts: {
          end: /<\/style>/,
          returnEnd: true,
          subLanguage: [
            "css",
            "xml"
          ]
        }
      },
      {
        className: "tag",
        // See the comment in the <style tag about the lookahead pattern
        begin: /<script(?=\s|>)/,
        end: />/,
        keywords: { name: "script" },
        contains: [TAG_INTERNALS],
        starts: {
          end: /<\/script>/,
          returnEnd: true,
          subLanguage: [
            "javascript",
            "handlebars",
            "xml"
          ]
        }
      },
      // we need this for now for jSX
      {
        className: "tag",
        begin: /<>|<\/>/
      },
      // open tag
      {
        className: "tag",
        begin: regex.concat(
          /</,
          regex.lookahead(regex.concat(
            TAG_NAME_RE,
            // <tag/>
            // <tag>
            // <tag ...
            regex.either(/\/>/, />/, /\s/)
          ))
        ),
        end: /\/?>/,
        contains: [
          {
            className: "name",
            begin: TAG_NAME_RE,
            relevance: 0,
            starts: TAG_INTERNALS
          }
        ]
      },
      // close tag
      {
        className: "tag",
        begin: regex.concat(
          /<\//,
          regex.lookahead(regex.concat(
            TAG_NAME_RE,
            />/
          ))
        ),
        contains: [
          {
            className: "name",
            begin: TAG_NAME_RE,
            relevance: 0
          },
          {
            begin: />/,
            relevance: 0,
            endsParent: true
          }
        ]
      }
    ]
  };
}

// node_modules/highlight.js/es/languages/yaml.js
function yaml(hljs) {
  const LITERALS3 = "true false yes no null";
  const URI_CHARACTERS = "[\\w#;/?:@&=+$,.~*'()[\\]]+";
  const KEY = {
    className: "attr",
    variants: [
      // added brackets support and special char support
      { begin: /[\w*@][\w*@ :()\./-]*:(?=[ \t]|$)/ },
      {
        // double quoted keys - with brackets and special char support
        begin: /"[\w*@][\w*@ :()\./-]*":(?=[ \t]|$)/
      },
      {
        // single quoted keys - with brackets and special char support
        begin: /'[\w*@][\w*@ :()\./-]*':(?=[ \t]|$)/
      }
    ]
  };
  const TEMPLATE_VARIABLES = {
    className: "template-variable",
    variants: [
      {
        // jinja templates Ansible
        begin: /\{\{/,
        end: /\}\}/
      },
      {
        // Ruby i18n
        begin: /%\{/,
        end: /\}/
      }
    ]
  };
  const SINGLE_QUOTE_STRING = {
    className: "string",
    relevance: 0,
    begin: /'/,
    end: /'/,
    contains: [
      {
        match: /''/,
        scope: "char.escape",
        relevance: 0
      }
    ]
  };
  const STRING = {
    className: "string",
    relevance: 0,
    variants: [
      {
        begin: /"/,
        end: /"/
      },
      { begin: /\S+/ }
    ],
    contains: [
      hljs.BACKSLASH_ESCAPE,
      TEMPLATE_VARIABLES
    ]
  };
  const CONTAINER_STRING = hljs.inherit(STRING, { variants: [
    {
      begin: /'/,
      end: /'/,
      contains: [
        {
          begin: /''/,
          relevance: 0
        }
      ]
    },
    {
      begin: /"/,
      end: /"/
    },
    { begin: /[^\s,{}[\]]+/ }
  ] });
  const DATE_RE = "[0-9]{4}(-[0-9][0-9]){0,2}";
  const TIME_RE = "([Tt \\t][0-9][0-9]?(:[0-9][0-9]){2})?";
  const FRACTION_RE = "(\\.[0-9]*)?";
  const ZONE_RE = "([ \\t])*(Z|[-+][0-9][0-9]?(:[0-9][0-9])?)?";
  const TIMESTAMP = {
    className: "number",
    begin: "\\b" + DATE_RE + TIME_RE + FRACTION_RE + ZONE_RE + "\\b"
  };
  const VALUE_CONTAINER = {
    end: ",",
    endsWithParent: true,
    excludeEnd: true,
    keywords: LITERALS3,
    relevance: 0
  };
  const OBJECT = {
    begin: /\{/,
    end: /\}/,
    contains: [VALUE_CONTAINER],
    illegal: "\\n",
    relevance: 0
  };
  const ARRAY = {
    begin: "\\[",
    end: "\\]",
    contains: [VALUE_CONTAINER],
    illegal: "\\n",
    relevance: 0
  };
  const MODES4 = [
    KEY,
    {
      className: "meta",
      begin: "^---\\s*$",
      relevance: 10
    },
    {
      // multi line string
      // Blocks start with a | or > followed by a newline
      //
      // Indentation of subsequent lines must be the same to
      // be considered part of the block
      className: "string",
      begin: "[\\|>]([1-9]?[+-])?[ ]*\\n( +)[^ ][^\\n]*\\n(\\2[^\\n]+\\n?)*"
    },
    {
      // Ruby/Rails erb
      begin: "<%[%=-]?",
      end: "[%-]?%>",
      subLanguage: "ruby",
      excludeBegin: true,
      excludeEnd: true,
      relevance: 0
    },
    {
      // named tags
      className: "type",
      begin: "!\\w+!" + URI_CHARACTERS
    },
    // https://yaml.org/spec/1.2/spec.html#id2784064
    {
      // verbatim tags
      className: "type",
      begin: "!<" + URI_CHARACTERS + ">"
    },
    {
      // primary tags
      className: "type",
      begin: "!" + URI_CHARACTERS
    },
    {
      // secondary tags
      className: "type",
      begin: "!!" + URI_CHARACTERS
    },
    {
      // fragment id &ref
      className: "meta",
      begin: "&" + hljs.UNDERSCORE_IDENT_RE + "$"
    },
    {
      // fragment reference *ref
      className: "meta",
      begin: "\\*" + hljs.UNDERSCORE_IDENT_RE + "$"
    },
    {
      // array listing
      className: "bullet",
      // TODO: remove |$ hack when we have proper look-ahead support
      begin: "-(?=[ ]|$)",
      relevance: 0
    },
    hljs.HASH_COMMENT_MODE,
    {
      beginKeywords: LITERALS3,
      keywords: { literal: LITERALS3 }
    },
    TIMESTAMP,
    // numbers are any valid C-style number that
    // sit isolated from other words
    {
      className: "number",
      begin: hljs.C_NUMBER_RE + "\\b",
      relevance: 0
    },
    OBJECT,
    ARRAY,
    SINGLE_QUOTE_STRING,
    STRING
  ];
  const VALUE_MODES = [...MODES4];
  VALUE_MODES.pop();
  VALUE_MODES.push(CONTAINER_STRING);
  VALUE_CONTAINER.contains = VALUE_MODES;
  return {
    name: "YAML",
    case_insensitive: true,
    aliases: ["yml"],
    contains: MODES4
  };
}

// node_modules/lowlight/lib/common.js
var grammars = {
  arduino,
  bash,
  c,
  cpp,
  csharp,
  css,
  diff,
  go,
  graphql,
  ini,
  java,
  javascript,
  json,
  kotlin,
  less,
  lua,
  makefile,
  markdown,
  objectivec,
  perl,
  php,
  "php-template": phpTemplate,
  plaintext,
  python,
  "python-repl": pythonRepl,
  r,
  ruby,
  rust,
  scss,
  shell,
  sql,
  swift,
  typescript,
  vbnet,
  wasm,
  xml,
  yaml
};

// node_modules/devlop/lib/default.js
function ok() {
}

// node_modules/highlight.js/es/core.js
var import_core = __toESM(require_core(), 1);
var core_default = import_core.default;

// node_modules/lowlight/lib/index.js
var emptyOptions = {};
var defaultPrefix = "hljs-";
function createLowlight(grammars2) {
  const high = core_default.newInstance();
  if (grammars2) {
    register(grammars2);
  }
  return {
    highlight,
    highlightAuto,
    listLanguages,
    register,
    registerAlias,
    registered
  };
  function highlight(language, value, options) {
    ok(typeof language === "string", "expected `string` as `name`");
    ok(typeof value === "string", "expected `string` as `value`");
    const settings = options || emptyOptions;
    const prefix = typeof settings.prefix === "string" ? settings.prefix : defaultPrefix;
    if (!high.getLanguage(language)) {
      throw new Error("Unknown language: `" + language + "` is not registered");
    }
    high.configure({ __emitter: HastEmitter, classPrefix: prefix });
    const result = (
      /** @type {HighlightResult & {_emitter: HastEmitter}} */
      high.highlight(value, { ignoreIllegals: true, language })
    );
    if (result.errorRaised) {
      throw new Error("Could not highlight with `Highlight.js`", {
        cause: result.errorRaised
      });
    }
    const root = result._emitter.root;
    const data = (
      /** @type {RootData} */
      root.data
    );
    data.language = result.language;
    data.relevance = result.relevance;
    return root;
  }
  function highlightAuto(value, options) {
    ok(typeof value === "string", "expected `string` as `value`");
    const settings = options || emptyOptions;
    const subset = settings.subset || listLanguages();
    let index = -1;
    let relevance = 0;
    let result;
    while (++index < subset.length) {
      const name = subset[index];
      if (!high.getLanguage(name)) continue;
      const current = highlight(name, value, options);
      if (current.data && current.data.relevance !== void 0 && current.data.relevance > relevance) {
        relevance = current.data.relevance;
        result = current;
      }
    }
    return result || {
      type: "root",
      children: [],
      data: { language: void 0, relevance }
    };
  }
  function listLanguages() {
    return high.listLanguages();
  }
  function register(grammarsOrName, grammar) {
    if (typeof grammarsOrName === "string") {
      ok(grammar !== void 0, "expected `grammar`");
      high.registerLanguage(grammarsOrName, grammar);
    } else {
      let name;
      for (name in grammarsOrName) {
        if (Object.hasOwn(grammarsOrName, name)) {
          high.registerLanguage(name, grammarsOrName[name]);
        }
      }
    }
  }
  function registerAlias(aliasesOrName, alias) {
    if (typeof aliasesOrName === "string") {
      ok(alias !== void 0);
      high.registerAliases(
        // Note: copy needed because hljs doesn’t accept readonly arrays yet.
        typeof alias === "string" ? alias : [...alias],
        { languageName: aliasesOrName }
      );
    } else {
      let key;
      for (key in aliasesOrName) {
        if (Object.hasOwn(aliasesOrName, key)) {
          const aliases = aliasesOrName[key];
          high.registerAliases(
            // Note: copy needed because hljs doesn’t accept readonly arrays yet.
            typeof aliases === "string" ? aliases : [...aliases],
            { languageName: key }
          );
        }
      }
    }
  }
  function registered(aliasOrName) {
    return Boolean(high.getLanguage(aliasOrName));
  }
}
var HastEmitter = class {
  /**
   * @param {Readonly<HljsOptions>} options
   *   Configuration.
   * @returns
   *   Instance.
   */
  constructor(options) {
    this.options = options;
    this.root = {
      type: "root",
      children: [],
      data: { language: void 0, relevance: 0 }
    };
    this.stack = [this.root];
  }
  /**
   * @param {string} value
   *   Text to add.
   * @returns {undefined}
   *   Nothing.
   *
   */
  addText(value) {
    if (value === "") return;
    const current = this.stack[this.stack.length - 1];
    const tail = current.children[current.children.length - 1];
    if (tail && tail.type === "text") {
      tail.value += value;
    } else {
      current.children.push({ type: "text", value });
    }
  }
  /**
   *
   * @param {unknown} rawName
   *   Name to add.
   * @returns {undefined}
   *   Nothing.
   */
  startScope(rawName) {
    this.openNode(String(rawName));
  }
  /**
   * @returns {undefined}
   *   Nothing.
   */
  endScope() {
    this.closeNode();
  }
  /**
   * @param {HastEmitter} other
   *   Other emitter.
   * @param {string} name
   *   Name of the sublanguage.
   * @returns {undefined}
   *   Nothing.
   */
  __addSublanguage(other, name) {
    const current = this.stack[this.stack.length - 1];
    const results = (
      /** @type {Array<ElementContent>} */
      other.root.children
    );
    if (name) {
      current.children.push({
        type: "element",
        tagName: "span",
        properties: { className: [name] },
        children: results
      });
    } else {
      current.children.push(...results);
    }
  }
  /**
   * @param {string} name
   *   Name to add.
   * @returns {undefined}
   *   Nothing.
   */
  openNode(name) {
    const self = this;
    const className = name.split(".").map(function(d, i) {
      return i ? d + "_".repeat(i) : self.options.classPrefix + d;
    });
    const current = this.stack[this.stack.length - 1];
    const child = {
      type: "element",
      tagName: "span",
      properties: { className },
      children: []
    };
    current.children.push(child);
    this.stack.push(child);
  }
  /**
   * @returns {undefined}
   *   Nothing.
   */
  closeNode() {
    this.stack.pop();
  }
  /**
   * @returns {undefined}
   *   Nothing.
   */
  finalize() {
  }
  /**
   * @returns {string}
   *   Nothing.
   */
  toHTML() {
    return "";
  }
};

// packages/cli/src/ui/components/shared/MaxSizedBox.tsx
var import_react5 = __toESM(require_react(), 1);

// packages/cli/src/ui/contexts/OverflowContext.tsx
var import_react4 = __toESM(require_react(), 1);
var import_jsx_runtime4 = __toESM(require_jsx_runtime(), 1);
var OverflowStateContext = (0, import_react4.createContext)(
  void 0
);
var OverflowActionsContext = (0, import_react4.createContext)(
  void 0
);
var useOverflowState = () => (0, import_react4.useContext)(OverflowStateContext);
var useOverflowActions = () => (0, import_react4.useContext)(OverflowActionsContext);
var OverflowProvider = ({
  children
}) => {
  const [overflowingIds, setOverflowingIds] = (0, import_react4.useState)(/* @__PURE__ */ new Set());
  const idsRef = (0, import_react4.useRef)(/* @__PURE__ */ new Set());
  const timeoutRef = (0, import_react4.useRef)(null);
  const syncState = (0, import_react4.useCallback)(() => {
    if (timeoutRef.current) return;
    timeoutRef.current = setTimeout(() => {
      timeoutRef.current = null;
      setOverflowingIds((prevIds) => {
        if (prevIds.size === idsRef.current.size && [...prevIds].every((id) => idsRef.current.has(id))) {
          return prevIds;
        }
        return new Set(idsRef.current);
      });
    }, 0);
  }, []);
  (0, import_react4.useEffect)(
    () => () => {
      if (timeoutRef.current) {
        clearTimeout(timeoutRef.current);
      }
    },
    []
  );
  const addOverflowingId = (0, import_react4.useCallback)(
    (id) => {
      if (!idsRef.current.has(id)) {
        idsRef.current.add(id);
        syncState();
      }
    },
    [syncState]
  );
  const removeOverflowingId = (0, import_react4.useCallback)(
    (id) => {
      if (idsRef.current.has(id)) {
        idsRef.current.delete(id);
        syncState();
      }
    },
    [syncState]
  );
  const reset = (0, import_react4.useCallback)(() => {
    if (idsRef.current.size > 0) {
      idsRef.current.clear();
      syncState();
    }
  }, [syncState]);
  const stateValue = (0, import_react4.useMemo)(
    () => ({
      overflowingIds
    }),
    [overflowingIds]
  );
  const actionsValue = (0, import_react4.useMemo)(
    () => ({
      addOverflowingId,
      removeOverflowingId,
      reset
    }),
    [addOverflowingId, removeOverflowingId, reset]
  );
  return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(OverflowStateContext.Provider, { value: stateValue, children: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(OverflowActionsContext.Provider, { value: actionsValue, children }) });
};

// packages/cli/src/ui/utils/isNarrowWidth.ts
function isNarrowWidth(width) {
  return width < 80;
}

// packages/cli/src/ui/key/keybindingUtils.ts
import process3 from "node:process";
var KEY_NAME_MAP = {
  enter: "Enter",
  escape: "Esc",
  backspace: "Backspace",
  delete: "Delete",
  up: "Up",
  down: "Down",
  left: "Left",
  right: "Right",
  pageup: "Page Up",
  pagedown: "Page Down",
  home: "Home",
  end: "End",
  tab: "Tab",
  space: "Space"
};
var MODIFIER_MAPS = {
  darwin: {
    ctrl: "Ctrl",
    alt: "Option",
    shift: "Shift",
    cmd: "Cmd"
  },
  win32: {
    ctrl: "Ctrl",
    alt: "Alt",
    shift: "Shift",
    cmd: "Win"
  },
  linux: {
    ctrl: "Ctrl",
    alt: "Alt",
    shift: "Shift",
    cmd: "Super"
  },
  default: {
    ctrl: "Ctrl",
    alt: "Alt",
    shift: "Shift",
    cmd: "Cmd/Win"
  }
};
function formatKeyBinding(binding, platform) {
  const activePlatform = platform ?? (process3.env["FORCE_GENERIC_KEYBINDING_HINTS"] ? "default" : process3.platform);
  const modMap = MODIFIER_MAPS[activePlatform] || MODIFIER_MAPS["default"];
  const parts = [];
  if (binding.ctrl) parts.push(modMap.ctrl);
  if (binding.alt) parts.push(modMap.alt);
  if (binding.shift) parts.push(modMap.shift);
  if (binding.cmd) parts.push(modMap.cmd);
  const keyName = KEY_NAME_MAP[binding.name] || binding.name.toUpperCase();
  parts.push(keyName);
  return parts.join("+");
}
function formatCommand(command, config = defaultKeyBindingConfig, platform) {
  const bindings = config.get(command);
  if (!bindings || bindings.length === 0) {
    return "";
  }
  return formatKeyBinding(bindings[0], platform);
}

// packages/cli/src/ui/components/shared/MaxSizedBox.tsx
var import_jsx_runtime5 = __toESM(require_jsx_runtime(), 1);
var MINIMUM_MAX_HEIGHT = 2;
var MaxSizedBox = ({
  children,
  maxWidth,
  maxHeight,
  overflowDirection = "top",
  additionalHiddenLinesCount = 0,
  paddingX = 0
}) => {
  const id = (0, import_react5.useId)();
  const { addOverflowingId, removeOverflowingId } = useOverflowActions() || {};
  const observerRef = (0, import_react5.useRef)(null);
  (0, import_react5.useEffect)(
    () => () => {
      observerRef.current?.disconnect();
    },
    []
  );
  const [contentHeight, setContentHeight] = (0, import_react5.useState)(0);
  const onRefChange = (0, import_react5.useCallback)(
    (node) => {
      if (observerRef.current) {
        observerRef.current.disconnect();
        observerRef.current = null;
      }
      if (node && maxHeight !== void 0) {
        const observer = new ResizeObserver((entries) => {
          const entry = entries[0];
          if (entry) {
            setContentHeight(Math.round(entry.contentRect.height));
          }
        });
        observer.observe(node);
        observerRef.current = observer;
      }
    },
    [maxHeight]
  );
  const effectiveMaxHeight = maxHeight !== void 0 ? Math.max(Math.round(maxHeight), MINIMUM_MAX_HEIGHT) : void 0;
  const isOverflowing = effectiveMaxHeight !== void 0 && contentHeight > effectiveMaxHeight || additionalHiddenLinesCount > 0;
  const visibleContentHeight = isOverflowing && effectiveMaxHeight !== void 0 ? effectiveMaxHeight - 1 : effectiveMaxHeight;
  const hiddenLinesCount = visibleContentHeight !== void 0 ? Math.max(0, contentHeight - visibleContentHeight) : 0;
  const totalHiddenLines = hiddenLinesCount + additionalHiddenLinesCount;
  const isNarrow = maxWidth !== void 0 && isNarrowWidth(maxWidth);
  const showMoreKey = formatCommand("app.showMoreLines" /* SHOW_MORE_LINES */);
  (0, import_react5.useEffect)(() => {
    if (totalHiddenLines > 0) {
      addOverflowingId?.(id);
    } else {
      removeOverflowingId?.(id);
    }
  }, [id, totalHiddenLines, addOverflowingId, removeOverflowingId]);
  (0, import_react5.useEffect)(
    () => () => {
      removeOverflowingId?.(id);
    },
    [id, removeOverflowingId]
  );
  if (effectiveMaxHeight === void 0 && totalHiddenLines === 0) {
    return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(Box_default, { flexDirection: "column", width: maxWidth, children });
  }
  const offset = hiddenLinesCount > 0 && overflowDirection === "top" ? -hiddenLinesCount : 0;
  return /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(
    Box_default,
    {
      flexDirection: "column",
      width: maxWidth,
      maxHeight: effectiveMaxHeight,
      flexShrink: 0,
      children: [
        totalHiddenLines > 0 && overflowDirection === "top" && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(Box_default, { paddingX, children: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(Text, { color: theme.text.secondary, wrap: "truncate", children: isNarrow ? `... ${totalHiddenLines} hidden (${showMoreKey}) ...` : `... first ${totalHiddenLines} line${totalHiddenLines === 1 ? "" : "s"} hidden (${showMoreKey} to show) ...` }) }),
        /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
          Box_default,
          {
            flexDirection: "column",
            overflow: "hidden",
            flexGrow: 0,
            maxHeight: isOverflowing ? visibleContentHeight : void 0,
            children: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
              Box_default,
              {
                flexDirection: "column",
                ref: onRefChange,
                flexShrink: 0,
                marginTop: offset,
                children
              }
            )
          }
        ),
        totalHiddenLines > 0 && overflowDirection === "bottom" && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(Box_default, { paddingX, children: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(Text, { color: theme.text.secondary, wrap: "truncate", children: isNarrow ? `... ${totalHiddenLines} hidden (${showMoreKey}) ...` : `... last ${totalHiddenLines} line${totalHiddenLines === 1 ? "" : "s"} hidden (${showMoreKey} to show) ...` }) })
      ]
    }
  );
};

// packages/cli/src/ui/utils/CodeColorizer.tsx
var import_jsx_runtime6 = __toESM(require_jsx_runtime(), 1);
var lowlight = createLowlight(grammars);
function renderHastNode(node, theme2, inheritedColor) {
  if (node.type === "text") {
    const color = inheritedColor || theme2.defaultColor;
    return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text, { color, children: node.value });
  }
  if (node.type === "element") {
    const nodeClasses = (
      // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
      node.properties?.["className"] || []
    );
    let elementColor = void 0;
    for (let i = nodeClasses.length - 1; i >= 0; i--) {
      const color = theme2.getInkColor(nodeClasses[i]);
      if (color) {
        elementColor = color;
        break;
      }
    }
    const colorToPassDown = elementColor || inheritedColor;
    const children = node.children?.map(
      (child, index) => /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(import_react6.default.Fragment, { children: renderHastNode(child, theme2, colorToPassDown) }, index)
    );
    return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(import_react6.default.Fragment, { children });
  }
  if (node.type === "root") {
    if (!node.children || node.children.length === 0) {
      return null;
    }
    return node.children?.map((child, index) => /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(import_react6.default.Fragment, { children: renderHastNode(child, theme2, inheritedColor) }, index));
  }
  return null;
}
function highlightAndRenderLine(line, language, theme2) {
  try {
    const strippedLine = stripAnsi(line);
    const getHighlightedLine = () => !language || !lowlight.registered(language) ? lowlight.highlightAuto(strippedLine) : lowlight.highlight(language, strippedLine);
    const renderedNode = renderHastNode(getHighlightedLine(), theme2, void 0);
    return renderedNode !== null ? renderedNode : strippedLine;
  } catch {
    return stripAnsi(line);
  }
}
function colorizeLine(line, language, theme2, disableColor = false) {
  if (disableColor) {
    return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text, { children: line });
  }
  const activeTheme = theme2 || themeManager.getActiveTheme();
  return highlightAndRenderLine(line, language, activeTheme);
}
function colorizeCode({
  code,
  language = null,
  availableHeight,
  maxWidth,
  theme: theme2 = null,
  settings,
  hideLineNumbers = false,
  disableColor = false,
  returnLines = false,
  paddingX = 0
}) {
  const codeToHighlight = code.replace(/\n$/, "");
  const activeTheme = theme2 || themeManager.getActiveTheme();
  const showLineNumbers = hideLineNumbers ? false : settings.merged.ui.showLineNumbers;
  const useMaxSizedBox = (!settings.merged.ui.useAlternateBuffer || availableHeight !== void 0) && !returnLines;
  let hiddenLinesCount = 0;
  let finalLines = codeToHighlight.split(/\r?\n/);
  try {
    if (availableHeight !== void 0 && useMaxSizedBox) {
      availableHeight = Math.max(availableHeight, MINIMUM_MAX_HEIGHT);
      if (finalLines.length > availableHeight) {
        const sliceIndex = finalLines.length - availableHeight;
        hiddenLinesCount = sliceIndex;
        finalLines = finalLines.slice(sliceIndex);
      }
    }
    const padWidth = String(finalLines.length + hiddenLinesCount).length;
    const renderedLines = finalLines.map((line, index) => {
      const contentToRender = disableColor ? line : highlightAndRenderLine(line, language, activeTheme);
      return /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(Box_default, { minHeight: 1, children: [
        showLineNumbers && /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
          Box_default,
          {
            minWidth: padWidth + 1,
            flexShrink: 0,
            paddingRight: 1,
            alignItems: "flex-start",
            justifyContent: "flex-end",
            children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text, { color: disableColor ? void 0 : activeTheme.colors.Gray, children: `${index + 1 + hiddenLinesCount}` })
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
          Text,
          {
            color: disableColor ? void 0 : activeTheme.defaultColor,
            wrap: "wrap",
            children: contentToRender
          }
        )
      ] }, index);
    });
    if (returnLines) {
      return renderedLines;
    }
    if (useMaxSizedBox) {
      return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
        MaxSizedBox,
        {
          paddingX,
          maxHeight: availableHeight,
          maxWidth,
          additionalHiddenLinesCount: hiddenLinesCount,
          overflowDirection: "top",
          children: renderedLines
        }
      );
    }
    return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Box_default, { flexDirection: "column", width: maxWidth, children: renderedLines });
  } catch (error) {
    debugLogger.warn(
      `[colorizeCode] Error highlighting code for language "${language}":`,
      error
    );
    const padWidth = String(finalLines.length + hiddenLinesCount).length;
    const fallbackLines = finalLines.map((line, index) => /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(Box_default, { minHeight: 1, children: [
      showLineNumbers && /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
        Box_default,
        {
          minWidth: padWidth + 1,
          flexShrink: 0,
          paddingRight: 1,
          alignItems: "flex-start",
          justifyContent: "flex-end",
          children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text, { color: disableColor ? void 0 : activeTheme.defaultColor, children: `${index + 1 + hiddenLinesCount}` })
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text, { color: disableColor ? void 0 : activeTheme.colors.Gray, children: stripAnsi(line) })
    ] }, index));
    if (returnLines) {
      return fallbackLines;
    }
    if (useMaxSizedBox) {
      return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
        MaxSizedBox,
        {
          paddingX,
          maxHeight: availableHeight,
          maxWidth,
          additionalHiddenLinesCount: hiddenLinesCount,
          overflowDirection: "top",
          children: fallbackLines
        }
      );
    }
    return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Box_default, { flexDirection: "column", width: maxWidth, children: fallbackLines });
  }
}

// packages/cli/src/ui/utils/TableRenderer.tsx
var import_react7 = __toESM(require_react(), 1);

// packages/cli/src/ui/utils/markdownParsingUtils.ts
var import_chalk = __toESM(require_source(), 1);
var BOLD_MARKER_LENGTH = 2;
var ITALIC_MARKER_LENGTH = 1;
var STRIKETHROUGH_MARKER_LENGTH = 2;
var INLINE_CODE_MARKER_LENGTH = 1;
var UNDERLINE_TAG_START_LENGTH = 3;
var UNDERLINE_TAG_END_LENGTH = 4;
var ansiColorize = (str, color) => {
  if (!color) return str;
  const resolved = resolveColor(color);
  if (!resolved) return str;
  if (resolved.startsWith("#")) {
    return import_chalk.default.hex(resolved)(str);
  }
  const mappedHex = INK_NAME_TO_HEX_MAP[resolved];
  if (mappedHex) {
    return import_chalk.default.hex(mappedHex)(str);
  }
  if (INK_SUPPORTED_NAMES.has(resolved)) {
    switch (resolved) {
      case "black":
        return import_chalk.default.black(str);
      case "red":
        return import_chalk.default.red(str);
      case "green":
        return import_chalk.default.green(str);
      case "yellow":
        return import_chalk.default.yellow(str);
      case "blue":
        return import_chalk.default.blue(str);
      case "magenta":
        return import_chalk.default.magenta(str);
      case "cyan":
        return import_chalk.default.cyan(str);
      case "white":
        return import_chalk.default.white(str);
      case "gray":
      case "grey":
        return import_chalk.default.gray(str);
      default:
        return str;
    }
  }
  return str;
};
var parseMarkdownToANSI = (text, defaultColor) => {
  const baseColor = defaultColor ?? theme.text.primary;
  if (!/[*_~`<[https?:]/.test(text)) {
    return ansiColorize(text, baseColor);
  }
  let result = "";
  const inlineRegex = /(\*\*\*.*?\*\*\*|\*\*.*?\*\*|\*.*?\*|_.*?_|~~.*?~~|\[.*?\]\(.*?\)|`+.+?`+|<u>.*?<\/u>|https?:\/\/\S+)/g;
  let lastIndex = 0;
  let match;
  while ((match = inlineRegex.exec(text)) !== null) {
    if (match.index > lastIndex) {
      result += ansiColorize(text.slice(lastIndex, match.index), baseColor);
    }
    const fullMatch = match[0];
    let styledPart = "";
    try {
      if (fullMatch.endsWith("***") && fullMatch.startsWith("***") && fullMatch.length > (BOLD_MARKER_LENGTH + ITALIC_MARKER_LENGTH) * 2) {
        styledPart = import_chalk.default.bold(
          import_chalk.default.italic(
            parseMarkdownToANSI(
              fullMatch.slice(
                BOLD_MARKER_LENGTH + ITALIC_MARKER_LENGTH,
                -BOLD_MARKER_LENGTH - ITALIC_MARKER_LENGTH
              ),
              baseColor
            )
          )
        );
      } else if (fullMatch.endsWith("**") && fullMatch.startsWith("**") && fullMatch.length > BOLD_MARKER_LENGTH * 2) {
        styledPart = import_chalk.default.bold(
          parseMarkdownToANSI(
            fullMatch.slice(BOLD_MARKER_LENGTH, -BOLD_MARKER_LENGTH),
            baseColor
          )
        );
      } else if (fullMatch.length > ITALIC_MARKER_LENGTH * 2 && (fullMatch.startsWith("*") && fullMatch.endsWith("*") || fullMatch.startsWith("_") && fullMatch.endsWith("_")) && !/\w/.test(text.substring(match.index - 1, match.index)) && !/\w/.test(
        text.substring(inlineRegex.lastIndex, inlineRegex.lastIndex + 1)
      ) && !/\S[./\\]/.test(text.substring(match.index - 2, match.index)) && !/[./\\]\S/.test(
        text.substring(inlineRegex.lastIndex, inlineRegex.lastIndex + 2)
      )) {
        styledPart = import_chalk.default.italic(
          parseMarkdownToANSI(
            fullMatch.slice(ITALIC_MARKER_LENGTH, -ITALIC_MARKER_LENGTH),
            baseColor
          )
        );
      } else if (fullMatch.startsWith("~~") && fullMatch.endsWith("~~") && fullMatch.length > STRIKETHROUGH_MARKER_LENGTH * 2) {
        styledPart = import_chalk.default.strikethrough(
          parseMarkdownToANSI(
            fullMatch.slice(
              STRIKETHROUGH_MARKER_LENGTH,
              -STRIKETHROUGH_MARKER_LENGTH
            ),
            baseColor
          )
        );
      } else if (fullMatch.startsWith("`") && fullMatch.endsWith("`") && fullMatch.length > INLINE_CODE_MARKER_LENGTH) {
        const codeMatch = fullMatch.match(/^(`+)(.+?)\1$/s);
        if (codeMatch && codeMatch[2]) {
          styledPart = ansiColorize(codeMatch[2], theme.text.accent);
        }
      } else if (fullMatch.startsWith("[") && fullMatch.includes("](") && fullMatch.endsWith(")")) {
        const linkMatch = fullMatch.match(/\[(.*?)\]\((.*?)\)/);
        if (linkMatch) {
          const linkText = linkMatch[1];
          const url2 = linkMatch[2];
          styledPart = parseMarkdownToANSI(linkText, baseColor) + ansiColorize(" (", baseColor) + ansiColorize(url2, theme.text.link) + ansiColorize(")", baseColor);
        }
      } else if (fullMatch.startsWith("<u>") && fullMatch.endsWith("</u>") && fullMatch.length > UNDERLINE_TAG_START_LENGTH + UNDERLINE_TAG_END_LENGTH - 1) {
        styledPart = import_chalk.default.underline(
          parseMarkdownToANSI(
            fullMatch.slice(
              UNDERLINE_TAG_START_LENGTH,
              -UNDERLINE_TAG_END_LENGTH
            ),
            baseColor
          )
        );
      } else if (fullMatch.match(/^https?:\/\//)) {
        styledPart = ansiColorize(fullMatch, theme.text.link);
      }
    } catch (e) {
      debugLogger.warn("Error parsing inline markdown part:", fullMatch, e);
      styledPart = "";
    }
    result += styledPart || ansiColorize(fullMatch, baseColor);
    lastIndex = inlineRegex.lastIndex;
  }
  if (lastIndex < text.length) {
    result += ansiColorize(text.slice(lastIndex), baseColor);
  }
  return result;
};

// packages/cli/src/ui/utils/TableRenderer.tsx
var import_jsx_runtime7 = __toESM(require_jsx_runtime(), 1);
var MIN_COLUMN_WIDTH = 5;
var COLUMN_PADDING = 2;
var TABLE_MARGIN = 2;
var parseMarkdownToStyledLine = (text, defaultColor) => {
  const ansi = parseMarkdownToANSI(text, defaultColor);
  return toStyledCharacters(ansi);
};
var calculateWidths = (styledLine) => {
  const contentWidth = styledCharsWidth(styledLine);
  const words = wordBreakStyledChars(styledLine);
  const maxWordWidth = widestLineFromStyledChars(words);
  return { contentWidth, maxWordWidth };
};
var TableRenderer = ({
  headers,
  rows,
  terminalWidth
}) => {
  const styledHeaders = (0, import_react7.useMemo)(
    () => headers.map(
      (header) => parseMarkdownToStyledLine(
        stripUnsafeCharacters(header),
        theme.text.link
      )
    ),
    [headers]
  );
  const styledRows = (0, import_react7.useMemo)(
    () => rows.map(
      (row) => row.map(
        (cell) => parseMarkdownToStyledLine(
          stripUnsafeCharacters(cell),
          theme.text.primary
        )
      )
    ),
    [rows]
  );
  const { wrappedHeaders, wrappedRows, adjustedWidths } = (0, import_react7.useMemo)(() => {
    const numColumns = styledRows.reduce(
      (max, row) => Math.max(max, row.length),
      styledHeaders.length
    );
    const constraints = Array.from({ length: numColumns }).map(
      (_, colIndex) => {
        const headerStyledLine = styledHeaders[colIndex] || StyledLine.empty(0);
        let { contentWidth: maxContentWidth, maxWordWidth } = calculateWidths(headerStyledLine);
        styledRows.forEach((row) => {
          const cellStyledLine = row[colIndex] || StyledLine.empty(0);
          const { contentWidth: cellWidth, maxWordWidth: cellWordWidth } = calculateWidths(cellStyledLine);
          maxContentWidth = Math.max(maxContentWidth, cellWidth);
          maxWordWidth = Math.max(maxWordWidth, cellWordWidth);
        });
        const minWidth = maxWordWidth;
        const maxWidth = Math.max(minWidth, maxContentWidth);
        return { minWidth, maxWidth };
      }
    );
    const fixedOverhead = numColumns + 1 + numColumns * COLUMN_PADDING;
    const availableWidth = Math.max(
      0,
      terminalWidth - fixedOverhead - TABLE_MARGIN
    );
    const totalMinWidth = constraints.reduce((sum, c2) => sum + c2.minWidth, 0);
    let finalContentWidths;
    if (totalMinWidth > availableWidth) {
      const shortColumns = constraints.filter(
        (c2) => c2.maxWidth <= MIN_COLUMN_WIDTH
      );
      const totalShortColumnWidth = shortColumns.reduce(
        (sum, c2) => sum + c2.minWidth,
        0
      );
      const finalTotalShortColumnWidth = totalShortColumnWidth >= availableWidth ? 0 : totalShortColumnWidth;
      const scale = (availableWidth - finalTotalShortColumnWidth) / (totalMinWidth - finalTotalShortColumnWidth) || 0;
      finalContentWidths = constraints.map((c2) => {
        if (c2.maxWidth <= MIN_COLUMN_WIDTH && finalTotalShortColumnWidth > 0) {
          return c2.minWidth;
        }
        return Math.floor(c2.minWidth * scale);
      });
    } else {
      const surplus = availableWidth - totalMinWidth;
      const totalGrowthNeed = constraints.reduce(
        (sum, c2) => sum + (c2.maxWidth - c2.minWidth),
        0
      );
      if (totalGrowthNeed === 0) {
        finalContentWidths = constraints.map((c2) => c2.minWidth);
      } else {
        finalContentWidths = constraints.map((c2) => {
          const growthNeed = c2.maxWidth - c2.minWidth;
          const share = growthNeed / totalGrowthNeed;
          const extra = Math.floor(surplus * share);
          return Math.min(c2.maxWidth, c2.minWidth + extra);
        });
      }
    }
    const actualColumnWidths = new Array(numColumns).fill(0);
    const wrapAndProcessRow = (row) => {
      const rowResult = [];
      for (let colIndex = 0; colIndex < numColumns; colIndex++) {
        const cellStyledLine = row[colIndex] || StyledLine.empty(0);
        const allocatedWidth = finalContentWidths[colIndex];
        const contentWidth = Math.max(1, allocatedWidth);
        const wrappedStyledLines = wrapStyledChars(
          cellStyledLine,
          contentWidth
        );
        const maxLineWidth = widestLineFromStyledChars(wrappedStyledLines);
        actualColumnWidths[colIndex] = Math.max(
          actualColumnWidths[colIndex],
          maxLineWidth
        );
        const lines = wrappedStyledLines.map((line) => ({
          text: styledLineToString(line),
          width: styledCharsWidth(line)
        }));
        rowResult.push(lines);
      }
      return rowResult;
    };
    const wrappedHeaders2 = wrapAndProcessRow(styledHeaders);
    const wrappedRows2 = styledRows.map((row) => wrapAndProcessRow(row));
    const adjustedWidths2 = actualColumnWidths.map(
      (w) => (
        // eslint-disable-next-line @typescript-eslint/no-unsafe-return
        w + COLUMN_PADDING
      )
    );
    return { wrappedHeaders: wrappedHeaders2, wrappedRows: wrappedRows2, adjustedWidths: adjustedWidths2 };
  }, [styledHeaders, styledRows, terminalWidth]);
  const renderCell = (content, width, isHeader = false) => {
    const contentWidth = Math.max(0, width - COLUMN_PADDING);
    const displayWidth = content.width;
    const paddingNeeded = Math.max(0, contentWidth - displayWidth);
    return /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(Text, { children: [
      isHeader ? /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(Text, { bold: true, color: theme.text.link, children: content.text }) : /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(Text, { children: content.text }),
      " ".repeat(paddingNeeded)
    ] });
  };
  const renderBorder = (type) => {
    const chars = {
      top: { left: "\u250C", middle: "\u252C", right: "\u2510", horizontal: "\u2500" },
      middle: { left: "\u251C", middle: "\u253C", right: "\u2524", horizontal: "\u2500" },
      bottom: { left: "\u2514", middle: "\u2534", right: "\u2518", horizontal: "\u2500" }
    };
    const char = chars[type];
    const borderParts = adjustedWidths.map((w) => char.horizontal.repeat(w));
    const border = char.left + borderParts.join(char.middle) + char.right;
    return /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(Text, { color: theme.border.default, children: border });
  };
  const renderVisualRow = (cells, isHeader = false) => {
    const renderedCells = cells.map((cell, index) => {
      const width = adjustedWidths[index] || 0;
      return renderCell(cell, width, isHeader);
    });
    return /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(Box_default, { flexDirection: "row", children: [
      /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(Text, { color: theme.border.default, children: "\u2502" }),
      renderedCells.map((cell, index) => /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(import_react7.default.Fragment, { children: [
        /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(Box_default, { paddingX: 1, children: cell }),
        index < renderedCells.length - 1 && /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(Text, { color: theme.border.default, children: "\u2502" })
      ] }, index)),
      /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(Text, { color: theme.border.default, children: "\u2502" })
    ] });
  };
  const renderDataRow = (wrappedCells, rowIndex, isHeader = false) => {
    const key = rowIndex === -1 ? "header" : `${rowIndex}`;
    const maxHeight = Math.max(...wrappedCells.map((lines) => lines.length), 1);
    const visualRows = [];
    for (let i = 0; i < maxHeight; i++) {
      const visualRowCells = wrappedCells.map(
        (lines) => lines[i] || { text: "", width: 0 }
      );
      visualRows.push(
        /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(import_react7.default.Fragment, { children: renderVisualRow(visualRowCells, isHeader) }, `${key}-${i}`)
      );
    }
    return /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(import_react7.default.Fragment, { children: visualRows }, rowIndex);
  };
  return /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(Box_default, { flexDirection: "column", children: [
    renderBorder("top"),
    renderDataRow(wrappedHeaders, -1, true),
    renderBorder("middle"),
    wrappedRows.map((row, index) => renderDataRow(row, index)),
    renderBorder("bottom")
  ] });
};

// packages/cli/src/ui/utils/InlineMarkdownRenderer.tsx
var import_react8 = __toESM(require_react(), 1);
var import_jsx_runtime8 = __toESM(require_jsx_runtime(), 1);
var RenderInlineInternal = ({
  text: rawText,
  defaultColor
}) => {
  const text = stripUnsafeCharacters(rawText);
  const ansiText = parseMarkdownToANSI(text, defaultColor);
  return /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(Text, { children: ansiText });
};
var RenderInline = import_react8.default.memo(RenderInlineInternal);

// packages/cli/src/ui/utils/MarkdownDisplay.tsx
var import_jsx_runtime9 = __toESM(require_jsx_runtime(), 1);
var EMPTY_LINE_HEIGHT = 1;
var CODE_BLOCK_PREFIX_PADDING = 1;
var LIST_ITEM_PREFIX_PADDING = 1;
var LIST_ITEM_TEXT_FLEX_GROW = 1;
var MarkdownDisplayInternal = ({
  text,
  isPending,
  availableTerminalHeight,
  terminalWidth,
  renderMarkdown = true
}) => {
  const settings = useSettings();
  const isAlternateBuffer = useAlternateBuffer();
  const responseColor = theme.text.response ?? theme.text.primary;
  if (!text) return /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(import_jsx_runtime9.Fragment, {});
  if (!renderMarkdown) {
    const colorizedMarkdown = colorizeCode({
      code: text,
      language: "markdown",
      availableHeight: isAlternateBuffer ? void 0 : availableTerminalHeight,
      maxWidth: terminalWidth - CODE_BLOCK_PREFIX_PADDING,
      settings,
      hideLineNumbers: true
    });
    return /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(Box_default, { paddingLeft: CODE_BLOCK_PREFIX_PADDING, flexDirection: "column", children: colorizedMarkdown });
  }
  const lines = text.split(/\r?\n/);
  const headerRegex = /^ *(#{1,4}) +(.*)/;
  const codeFenceRegex = /^ *(`{3,}|~{3,}) *(\w*?) *$/;
  const ulItemRegex = /^([ \t]*)([-*+]) +(.*)/;
  const olItemRegex = /^([ \t]*)(\d+)\. +(.*)/;
  const hrRegex = /^ *([-*_] *){3,} *$/;
  const tableRowRegex = /^\s*\|(.+)\|\s*$/;
  const tableSeparatorRegex = /^\s*\|?\s*(:?-+:?)\s*(\|\s*(:?-+:?)\s*)+\|?\s*$/;
  const contentBlocks = [];
  let inCodeBlock = false;
  let lastLineEmpty = true;
  let codeBlockContent = [];
  let codeBlockLang = null;
  let codeBlockFence = "";
  let inTable = false;
  let tableRows = [];
  let tableHeaders = [];
  function addContentBlock(block) {
    if (block) {
      contentBlocks.push(block);
      lastLineEmpty = false;
    }
  }
  lines.forEach((line, index) => {
    const key = `line-${index}`;
    if (inCodeBlock) {
      const fenceMatch = line.match(codeFenceRegex);
      if (fenceMatch && fenceMatch[1].startsWith(codeBlockFence[0]) && fenceMatch[1].length >= codeBlockFence.length) {
        addContentBlock(
          /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
            RenderCodeBlock,
            {
              content: codeBlockContent,
              lang: codeBlockLang,
              isPending,
              availableTerminalHeight: isAlternateBuffer ? void 0 : availableTerminalHeight,
              terminalWidth
            },
            key
          )
        );
        inCodeBlock = false;
        codeBlockContent = [];
        codeBlockLang = null;
        codeBlockFence = "";
      } else {
        codeBlockContent.push(line);
      }
      return;
    }
    const codeFenceMatch = line.match(codeFenceRegex);
    const headerMatch = line.match(headerRegex);
    const ulMatch = line.match(ulItemRegex);
    const olMatch = line.match(olItemRegex);
    const hrMatch = line.match(hrRegex);
    const tableRowMatch = line.match(tableRowRegex);
    const tableSeparatorMatch = line.match(tableSeparatorRegex);
    if (codeFenceMatch) {
      inCodeBlock = true;
      codeBlockFence = codeFenceMatch[1];
      codeBlockLang = codeFenceMatch[2] || null;
    } else if (tableRowMatch && !inTable) {
      if (index + 1 < lines.length && lines[index + 1].match(tableSeparatorRegex)) {
        inTable = true;
        tableHeaders = tableRowMatch[1].split("|").map((cell) => cell.trim());
        tableRows = [];
      } else {
        addContentBlock(
          /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(Text, { wrap: "wrap", color: responseColor, children: /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(RenderInline, { text: line, defaultColor: responseColor }) }) }, key)
        );
      }
    } else if (inTable && tableSeparatorMatch) {
    } else if (inTable && tableRowMatch) {
      const cells = tableRowMatch[1].split("|").map((cell) => cell.trim());
      while (cells.length < tableHeaders.length) {
        cells.push("");
      }
      if (cells.length > tableHeaders.length) {
        cells.length = tableHeaders.length;
      }
      tableRows.push(cells);
    } else if (inTable && !tableRowMatch) {
      if (tableHeaders.length > 0 && tableRows.length > 0) {
        addContentBlock(
          /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
            RenderTable,
            {
              headers: tableHeaders,
              rows: tableRows,
              terminalWidth
            },
            `table-${contentBlocks.length}`
          )
        );
      }
      inTable = false;
      tableRows = [];
      tableHeaders = [];
      if (line.trim().length > 0) {
        addContentBlock(
          /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(Text, { wrap: "wrap", color: responseColor, children: /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(RenderInline, { text: line, defaultColor: responseColor }) }) }, key)
        );
      }
    } else if (hrMatch) {
      addContentBlock(
        /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(Text, { dimColor: true, children: "---" }) }, key)
      );
    } else if (headerMatch) {
      const level = headerMatch[1].length;
      const headerText = headerMatch[2];
      let headerNode = null;
      switch (level) {
        case 1:
          headerNode = /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(Text, { bold: true, color: theme.text.link, children: /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(RenderInline, { text: headerText, defaultColor: theme.text.link }) });
          break;
        case 2:
          headerNode = /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(Text, { bold: true, color: theme.text.link, children: /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(RenderInline, { text: headerText, defaultColor: theme.text.link }) });
          break;
        case 3:
          headerNode = /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(Text, { bold: true, color: responseColor, children: /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(RenderInline, { text: headerText, defaultColor: responseColor }) });
          break;
        case 4:
          headerNode = /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(Text, { italic: true, color: theme.text.secondary, children: /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
            RenderInline,
            {
              text: headerText,
              defaultColor: theme.text.secondary
            }
          ) });
          break;
        default:
          headerNode = /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(Text, { color: responseColor, children: /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(RenderInline, { text: headerText, defaultColor: responseColor }) });
          break;
      }
      if (headerNode) addContentBlock(/* @__PURE__ */ (0, import_jsx_runtime9.jsx)(Box_default, { children: headerNode }, key));
    } else if (ulMatch) {
      const leadingWhitespace = ulMatch[1];
      const marker = ulMatch[2];
      const itemText = ulMatch[3];
      addContentBlock(
        /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
          RenderListItem,
          {
            itemText,
            type: "ul",
            marker,
            leadingWhitespace
          },
          key
        )
      );
    } else if (olMatch) {
      const leadingWhitespace = olMatch[1];
      const marker = olMatch[2];
      const itemText = olMatch[3];
      addContentBlock(
        /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
          RenderListItem,
          {
            itemText,
            type: "ol",
            marker,
            leadingWhitespace
          },
          key
        )
      );
    } else {
      if (line.trim().length === 0 && !inCodeBlock) {
        if (!lastLineEmpty) {
          contentBlocks.push(
            /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(Box_default, { height: EMPTY_LINE_HEIGHT }, `spacer-${index}`)
          );
          lastLineEmpty = true;
        }
      } else {
        addContentBlock(
          /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(Text, { wrap: "wrap", color: responseColor, children: /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(RenderInline, { text: line, defaultColor: responseColor }) }) }, key)
        );
      }
    }
  });
  if (inCodeBlock) {
    addContentBlock(
      /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
        RenderCodeBlock,
        {
          content: codeBlockContent,
          lang: codeBlockLang,
          isPending,
          availableTerminalHeight: isAlternateBuffer ? void 0 : availableTerminalHeight,
          terminalWidth
        },
        "line-eof"
      )
    );
  }
  if (inTable && tableHeaders.length > 0 && tableRows.length > 0) {
    addContentBlock(
      /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
        RenderTable,
        {
          headers: tableHeaders,
          rows: tableRows,
          terminalWidth
        },
        `table-${contentBlocks.length}`
      )
    );
  }
  return /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(import_jsx_runtime9.Fragment, { children: contentBlocks });
};
var RenderCodeBlockInternal = ({
  content,
  lang,
  isPending,
  availableTerminalHeight,
  terminalWidth
}) => {
  const settings = useSettings();
  const isAlternateBuffer = useAlternateBuffer();
  const MIN_LINES_FOR_MESSAGE = 1;
  const RESERVED_LINES = 2;
  if (!isAlternateBuffer && isPending && availableTerminalHeight !== void 0) {
    const MAX_CODE_LINES_WHEN_PENDING = Math.max(
      0,
      availableTerminalHeight - RESERVED_LINES
    );
    if (content.length > MAX_CODE_LINES_WHEN_PENDING) {
      if (MAX_CODE_LINES_WHEN_PENDING < MIN_LINES_FOR_MESSAGE) {
        return /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(Box_default, { paddingLeft: CODE_BLOCK_PREFIX_PADDING, children: /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(Text, { color: theme.text.secondary, children: "... code is being written ..." }) });
      }
      const truncatedContent = content.slice(0, MAX_CODE_LINES_WHEN_PENDING);
      const colorizedTruncatedCode = colorizeCode({
        code: truncatedContent.join("\n"),
        language: lang,
        availableHeight: availableTerminalHeight,
        maxWidth: terminalWidth - CODE_BLOCK_PREFIX_PADDING,
        settings
      });
      return /* @__PURE__ */ (0, import_jsx_runtime9.jsxs)(Box_default, { paddingLeft: CODE_BLOCK_PREFIX_PADDING, flexDirection: "column", children: [
        colorizedTruncatedCode,
        /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(Text, { color: theme.text.secondary, children: "... generating more ..." })
      ] });
    }
  }
  const fullContent = content.join("\n");
  const colorizedCode = colorizeCode({
    code: fullContent,
    language: lang,
    availableHeight: isAlternateBuffer ? void 0 : availableTerminalHeight,
    maxWidth: terminalWidth - CODE_BLOCK_PREFIX_PADDING,
    settings
  });
  return /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
    Box_default,
    {
      paddingLeft: CODE_BLOCK_PREFIX_PADDING,
      flexDirection: "column",
      width: terminalWidth,
      flexShrink: 0,
      children: colorizedCode
    }
  );
};
var RenderCodeBlock = import_react9.default.memo(RenderCodeBlockInternal);
var RenderListItemInternal = ({
  itemText,
  type,
  marker,
  leadingWhitespace = ""
}) => {
  const prefix = type === "ol" ? `${marker}. ` : `${marker} `;
  const prefixWidth = prefix.length;
  const indentation = leadingWhitespace.length;
  const listResponseColor = theme.text.response ?? theme.text.primary;
  return /* @__PURE__ */ (0, import_jsx_runtime9.jsxs)(
    Box_default,
    {
      paddingLeft: indentation + LIST_ITEM_PREFIX_PADDING,
      flexDirection: "row",
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(Box_default, { width: prefixWidth, flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(Text, { color: listResponseColor, children: prefix }) }),
        /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(Box_default, { flexGrow: LIST_ITEM_TEXT_FLEX_GROW, children: /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(Text, { wrap: "wrap", color: listResponseColor, children: /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(RenderInline, { text: itemText, defaultColor: listResponseColor }) }) })
      ]
    }
  );
};
var RenderListItem = import_react9.default.memo(RenderListItemInternal);
var RenderTableInternal = ({
  headers,
  rows,
  terminalWidth
}) => /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(TableRenderer, { headers, rows, terminalWidth });
var RenderTable = import_react9.default.memo(RenderTableInternal);
var MarkdownDisplay = import_react9.default.memo(MarkdownDisplayInternal);

// packages/cli/src/ui/components/messages/GeminiMessage.tsx
var import_jsx_runtime10 = __toESM(require_jsx_runtime(), 1);
var GeminiMessage = ({
  text,
  isPending,
  availableTerminalHeight,
  terminalWidth
}) => {
  const { renderMarkdown } = useUIState();
  const prefix = "\u2726 ";
  const prefixWidth = prefix.length;
  return /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)(Box_default, { flexDirection: "row", children: [
    /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(Box_default, { width: prefixWidth, children: /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(Text, { color: theme.text.accent, "aria-label": SCREEN_READER_MODEL_PREFIX, children: prefix }) }),
    /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(Box_default, { flexGrow: 1, flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
      MarkdownDisplay,
      {
        text,
        isPending,
        availableTerminalHeight: availableTerminalHeight === void 0 ? void 0 : Math.max(availableTerminalHeight - 1, 1),
        terminalWidth: Math.max(terminalWidth - prefixWidth, 0),
        renderMarkdown
      }
    ) })
  ] });
};

// packages/cli/src/ui/components/messages/InfoMessage.tsx
var import_jsx_runtime11 = __toESM(require_jsx_runtime(), 1);
var InfoMessage = ({
  text,
  secondaryText,
  source: source2,
  icon,
  color,
  marginBottom
}) => {
  color ??= theme.status.warning;
  const prefix = icon ?? "\u2139 ";
  const prefixWidth = prefix.length;
  return /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)(Box_default, { flexDirection: "row", marginTop: 1, marginBottom: marginBottom ?? 0, children: [
    /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(Box_default, { width: prefixWidth, children: /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(Text, { color, children: prefix }) }),
    /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(Box_default, { flexGrow: 1, flexDirection: "column", children: text.split("\n").map((line, index) => /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)(Text, { wrap: "wrap", children: [
      /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(RenderInline, { text: line, defaultColor: color }),
      index === text.split("\n").length - 1 && secondaryText && /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)(Text, { color: theme.text.secondary, children: [
        " ",
        secondaryText
      ] }),
      index === text.split("\n").length - 1 && source2 && /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)(Text, { color: theme.text.secondary, children: [
        " [",
        source2,
        "]"
      ] })
    ] }, index)) })
  ] });
};

// packages/cli/src/ui/components/messages/ErrorMessage.tsx
var import_jsx_runtime12 = __toESM(require_jsx_runtime(), 1);
var ErrorMessage = ({ text }) => {
  const prefix = "\u2715 ";
  const prefixWidth = prefix.length;
  return /* @__PURE__ */ (0, import_jsx_runtime12.jsxs)(Box_default, { flexDirection: "row", marginBottom: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(Box_default, { width: prefixWidth, children: /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(Text, { color: theme.status.error, children: prefix }) }),
    /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(Box_default, { flexGrow: 1, children: /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(Text, { wrap: "wrap", color: theme.status.error, children: text }) })
  ] });
};

// packages/cli/src/ui/components/messages/ToolGroupMessage.tsx
var import_react34 = __toESM(require_react(), 1);

// packages/cli/src/ui/components/StickyHeader.tsx
var import_jsx_runtime13 = __toESM(require_jsx_runtime(), 1);
var StickyHeader = ({
  children,
  width,
  isFirst,
  borderColor,
  borderDimColor,
  containerRef
}) => /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(
  Box_default,
  {
    ref: containerRef,
    sticky: true,
    minHeight: 1,
    flexShrink: 0,
    width,
    stickyChildren: /* @__PURE__ */ (0, import_jsx_runtime13.jsxs)(
      Box_default,
      {
        borderStyle: "round",
        flexDirection: "column",
        width,
        opaque: true,
        borderColor,
        borderDimColor,
        borderBottom: false,
        borderTop: isFirst,
        paddingTop: isFirst ? 0 : 1,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(Box_default, { paddingX: 1, children }),
          /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(
            Box_default,
            {
              width: width - 2,
              borderColor: theme.ui.dark,
              borderStyle: "single",
              borderTop: false,
              borderBottom: true,
              borderLeft: false,
              borderRight: false
            }
          )
        ]
      }
    ),
    children: /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(
      Box_default,
      {
        borderStyle: "round",
        width,
        borderColor,
        borderDimColor,
        borderBottom: false,
        borderTop: isFirst,
        borderLeft: true,
        borderRight: true,
        paddingX: 1,
        paddingBottom: 1,
        paddingTop: isFirst ? 0 : 1,
        children
      }
    )
  }
);

// packages/cli/src/ui/components/messages/ToolResultDisplay.tsx
var import_react22 = __toESM(require_react(), 1);

// packages/cli/src/ui/components/messages/DiffRenderer.tsx
var import_react10 = __toESM(require_react(), 1);

// packages/cli/src/ui/utils/fileUtils.ts
import * as path from "node:path";
function getFileExtension(filename) {
  if (!filename) return null;
  const ext = path.extname(filename);
  return ext ? ext.slice(1) : null;
}

// packages/cli/src/ui/components/messages/DiffRenderer.tsx
var import_jsx_runtime14 = __toESM(require_jsx_runtime(), 1);
function parseDiffWithLineNumbers(diffContent) {
  const lines = diffContent.split(/\r?\n/);
  const result = [];
  let currentOldLine = 0;
  let currentNewLine = 0;
  let inHunk = false;
  const hunkHeaderRegex = /^@@ -(\d+),?\d* \+(\d+),?\d* @@/;
  for (const line of lines) {
    const hunkMatch = line.match(hunkHeaderRegex);
    if (hunkMatch) {
      currentOldLine = parseInt(hunkMatch[1], 10);
      currentOldLine = parseInt(hunkMatch[1], 10);
      currentNewLine = parseInt(hunkMatch[2], 10);
      inHunk = true;
      result.push({ type: "hunk", content: line });
      currentOldLine--;
      currentNewLine--;
      continue;
    }
    if (!inHunk) {
      if (line.startsWith("--- ")) {
        continue;
      }
      continue;
    }
    if (line.startsWith("+")) {
      currentNewLine++;
      result.push({
        type: "add",
        newLine: currentNewLine,
        content: line.substring(1)
      });
    } else if (line.startsWith("-")) {
      currentOldLine++;
      result.push({
        type: "del",
        oldLine: currentOldLine,
        content: line.substring(1)
      });
    } else if (line.startsWith(" ")) {
      currentOldLine++;
      currentNewLine++;
      result.push({
        type: "context",
        oldLine: currentOldLine,
        newLine: currentNewLine,
        content: line.substring(1)
      });
    } else if (line.startsWith("\\")) {
      result.push({ type: "other", content: line });
    }
  }
  return result;
}
var DEFAULT_TAB_WIDTH = 4;
var DiffRenderer = ({
  diffContent,
  filename,
  tabWidth = DEFAULT_TAB_WIDTH,
  availableTerminalHeight,
  terminalWidth,
  theme: theme2,
  disableColor = false,
  paddingX = 0
}) => {
  const settings = useSettings();
  const screenReaderEnabled = use_is_screen_reader_enabled_default();
  const parsedLines = (0, import_react10.useMemo)(() => {
    if (!diffContent || typeof diffContent !== "string") {
      return [];
    }
    return parseDiffWithLineNumbers(diffContent);
  }, [diffContent]);
  const isNewFileResult = (0, import_react10.useMemo)(() => isNewFile(parsedLines), [parsedLines]);
  const renderedOutput = (0, import_react10.useMemo)(() => {
    if (!diffContent || typeof diffContent !== "string") {
      return /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(Text, { color: theme.status.warning, children: "No diff content." });
    }
    if (parsedLines.length === 0) {
      return /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(Box_default, { padding: 1, children: /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(Text, { dimColor: true, children: "No changes detected." }) });
    }
    if (screenReaderEnabled) {
      return /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(Box_default, { flexDirection: "column", children: parsedLines.map((line, index) => /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(Text, { children: [
        line.type,
        ": ",
        line.content
      ] }, index)) });
    }
    if (isNewFileResult) {
      const addedContent = parsedLines.filter((line) => line.type === "add").map((line) => line.content).join("\n");
      const fileExtension = getFileExtension(filename);
      const language = fileExtension ? getLanguageFromExtension(fileExtension) : null;
      return colorizeCode({
        code: addedContent,
        language,
        availableHeight: availableTerminalHeight,
        maxWidth: terminalWidth,
        theme: theme2,
        settings,
        disableColor,
        paddingX
      });
    } else {
      const key = filename ? `diff-box-${filename}` : void 0;
      return /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(
        MaxSizedBox,
        {
          paddingX,
          maxHeight: availableTerminalHeight,
          maxWidth: terminalWidth,
          children: renderDiffLines({
            parsedLines,
            filename,
            tabWidth,
            terminalWidth,
            disableColor
          })
        },
        key
      );
    }
  }, [
    diffContent,
    parsedLines,
    screenReaderEnabled,
    isNewFileResult,
    filename,
    availableTerminalHeight,
    terminalWidth,
    theme2,
    settings,
    tabWidth,
    disableColor,
    paddingX
  ]);
  return renderedOutput;
};
var isNewFile = (parsedLines) => {
  if (parsedLines.length === 0) return false;
  return parsedLines.every(
    (line) => line.type === "add" || line.type === "hunk" || line.type === "other" || line.content.startsWith("diff --git") || line.content.startsWith("new file mode")
  );
};
var renderDiffLines = ({
  parsedLines,
  filename,
  tabWidth = DEFAULT_TAB_WIDTH,
  terminalWidth,
  disableColor = false
}) => {
  const normalizedLines = parsedLines.map((line) => ({
    ...line,
    content: line.content.replace(/\t/g, " ".repeat(tabWidth))
  }));
  const displayableLines = normalizedLines.filter(
    (l) => l.type !== "hunk" && l.type !== "other"
  );
  if (displayableLines.length === 0) {
    return [
      /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(Box_default, { padding: 1, children: /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(Text, { dimColor: true, children: "No changes detected." }) }, "no-changes")
    ];
  }
  const maxLineNumber = Math.max(
    0,
    ...displayableLines.map((l) => l.oldLine ?? 0),
    ...displayableLines.map((l) => l.newLine ?? 0)
  );
  const gutterWidth = Math.max(1, maxLineNumber.toString().length);
  const fileExtension = getFileExtension(filename);
  const language = fileExtension ? getLanguageFromExtension(fileExtension) : null;
  let baseIndentation = Infinity;
  for (const line of displayableLines) {
    if (line.content.trim() === "") continue;
    const firstCharIndex = line.content.search(/\S/);
    const currentIndent = firstCharIndex === -1 ? 0 : firstCharIndex;
    baseIndentation = Math.min(baseIndentation, currentIndent);
  }
  if (!isFinite(baseIndentation)) {
    baseIndentation = 0;
  }
  let lastLineNumber = null;
  const MAX_CONTEXT_LINES_WITHOUT_GAP = 5;
  const content = displayableLines.reduce(
    (acc, line, index) => {
      let relevantLineNumberForGapCalc = null;
      if (line.type === "add" || line.type === "context") {
        relevantLineNumberForGapCalc = line.newLine ?? null;
      } else if (line.type === "del") {
        relevantLineNumberForGapCalc = line.oldLine ?? null;
      }
      if (lastLineNumber !== null && relevantLineNumberForGapCalc !== null && relevantLineNumberForGapCalc > lastLineNumber + MAX_CONTEXT_LINES_WITHOUT_GAP + 1) {
        acc.push(
          /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(
            Box_default,
            {
              borderStyle: "double",
              borderLeft: false,
              borderRight: false,
              borderBottom: false,
              width: terminalWidth,
              borderColor: theme.text.secondary
            }
          ) }, `gap-${index}`)
        );
      }
      const lineKey = `diff-line-${index}`;
      let gutterNumStr = "";
      let prefixSymbol = " ";
      switch (line.type) {
        case "add":
          gutterNumStr = (line.newLine ?? "").toString();
          prefixSymbol = "+";
          lastLineNumber = line.newLine ?? null;
          break;
        case "del":
          gutterNumStr = (line.oldLine ?? "").toString();
          prefixSymbol = "-";
          if (line.oldLine !== void 0) {
            lastLineNumber = line.oldLine;
          }
          break;
        case "context":
          gutterNumStr = (line.newLine ?? "").toString();
          prefixSymbol = " ";
          lastLineNumber = line.newLine ?? null;
          break;
        default:
          return acc;
      }
      const displayContent = line.content.substring(baseIndentation);
      const backgroundColor = disableColor ? void 0 : line.type === "add" ? theme.background.diff.added : line.type === "del" ? theme.background.diff.removed : void 0;
      const gutterColor = disableColor ? void 0 : theme.text.secondary;
      const symbolColor = disableColor ? void 0 : line.type === "add" ? theme.status.success : line.type === "del" ? theme.status.error : void 0;
      acc.push(
        /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(Box_default, { flexDirection: "row", children: [
          /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(
            Box_default,
            {
              width: gutterWidth + 1,
              paddingRight: 1,
              flexShrink: 0,
              backgroundColor,
              justifyContent: "flex-end",
              children: /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(Text, { color: gutterColor, children: gutterNumStr })
            }
          ),
          line.type === "context" ? /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(import_jsx_runtime14.Fragment, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(Text, { children: [
              prefixSymbol,
              " "
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(Text, { wrap: "wrap", children: colorizeLine(
              displayContent,
              language,
              void 0,
              disableColor
            ) })
          ] }) : /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(Text, { backgroundColor, wrap: "wrap", children: [
            /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(Text, { color: symbolColor, children: prefixSymbol }),
            " ",
            colorizeLine(displayContent, language, void 0, disableColor)
          ] })
        ] }, lineKey)
      );
      return acc;
    },
    []
  );
  return content;
};
var getLanguageFromExtension = (extension) => {
  const languageMap = {
    js: "javascript",
    ts: "typescript",
    py: "python",
    json: "json",
    css: "css",
    html: "html",
    sh: "bash",
    md: "markdown",
    yaml: "yaml",
    yml: "yaml",
    txt: "plaintext",
    java: "java",
    c: "c",
    cpp: "cpp",
    rb: "ruby"
  };
  return languageMap[extension] || null;
};

// packages/cli/src/ui/components/AnsiOutput.tsx
var import_jsx_runtime15 = __toESM(require_jsx_runtime(), 1);
var DEFAULT_HEIGHT = 24;
var AnsiOutputText = ({
  data,
  availableTerminalHeight,
  width,
  maxLines,
  disableTruncation
}) => {
  const availableHeightLimit = availableTerminalHeight && availableTerminalHeight > 0 ? availableTerminalHeight : void 0;
  const numLinesRetained = availableHeightLimit !== void 0 && maxLines !== void 0 ? Math.min(availableHeightLimit, maxLines) : availableHeightLimit ?? maxLines ?? DEFAULT_HEIGHT;
  const lastLines = Array.isArray(data) ? disableTruncation ? data : numLinesRetained === 0 ? [] : data.slice(-numLinesRetained) : [];
  return /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(Box_default, { flexDirection: "column", width, flexShrink: 0, overflow: "hidden", children: lastLines.map((line, lineIndex) => /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(Box_default, { height: 1, overflow: "hidden", children: /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(AnsiLineText, { line }) }, lineIndex)) });
};
var AnsiLineText = ({ line }) => /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(Text, { children: line.length > 0 ? line.map((token, tokenIndex) => /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(
  Text,
  {
    color: token.fg,
    backgroundColor: token.bg,
    inverse: token.inverse,
    dimColor: token.dim,
    bold: token.bold,
    italic: token.italic,
    underline: token.underline,
    children: token.text
  },
  tokenIndex
)) : null });

// packages/cli/src/ui/components/shared/SlicingMaxSizedBox.tsx
var import_react11 = __toESM(require_react(), 1);
var import_jsx_runtime16 = __toESM(require_jsx_runtime(), 1);
var MAXIMUM_RESULT_DISPLAY_CHARACTERS = 2e4;
function SlicingMaxSizedBox({
  data,
  maxLines,
  isAlternateBuffer,
  children,
  ...boxProps
}) {
  const { truncatedData, hiddenLinesCount } = (0, import_react11.useMemo)(() => {
    let hiddenLines = 0;
    const overflowDirection = boxProps.overflowDirection ?? "top";
    if (typeof data === "string" && !isAlternateBuffer) {
      let text = data;
      if (text.length > MAXIMUM_RESULT_DISPLAY_CHARACTERS) {
        if (overflowDirection === "bottom") {
          text = text.slice(0, MAXIMUM_RESULT_DISPLAY_CHARACTERS) + "...";
        } else {
          text = "..." + text.slice(-MAXIMUM_RESULT_DISPLAY_CHARACTERS);
        }
      }
      if (maxLines !== void 0) {
        const hasTrailingNewline = text.endsWith("\n");
        const contentText = hasTrailingNewline ? text.slice(0, -1) : text;
        const lines = contentText.split("\n");
        if (lines.length > maxLines) {
          const targetLines = Math.max(1, maxLines - 1);
          hiddenLines = lines.length - targetLines;
          if (overflowDirection === "bottom") {
            text = lines.slice(0, targetLines).join("\n") + (hasTrailingNewline ? "\n" : "");
          } else {
            text = lines.slice(-targetLines).join("\n") + (hasTrailingNewline ? "\n" : "");
          }
        }
      }
      return {
        truncatedData: text,
        hiddenLinesCount: hiddenLines
      };
    }
    if (Array.isArray(data) && !isAlternateBuffer && maxLines !== void 0) {
      if (data.length > maxLines) {
        const targetLines = Math.max(1, maxLines - 1);
        const hiddenCount = data.length - targetLines;
        return {
          truncatedData: overflowDirection === "bottom" ? data.slice(0, targetLines) : data.slice(-targetLines),
          hiddenLinesCount: hiddenCount
        };
      }
    }
    return { truncatedData: data, hiddenLinesCount: 0 };
  }, [data, isAlternateBuffer, maxLines, boxProps.overflowDirection]);
  return /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(
    MaxSizedBox,
    {
      ...boxProps,
      additionalHiddenLinesCount: (boxProps.additionalHiddenLinesCount ?? 0) + hiddenLinesCount,
      children: children(truncatedData)
    }
  );
}

// packages/cli/src/utils/jsonoutput.ts
function checkInput(input) {
  if (input === null || input === void 0) {
    return false;
  }
  const trimmed = input.trim();
  if (!trimmed) {
    return false;
  }
  if (!/^(?:\[|\{)/.test(trimmed)) {
    return false;
  }
  if (stripAnsi(trimmed) !== trimmed) return false;
  return true;
}
function tryParseJSON(input) {
  if (!checkInput(input)) return null;
  const trimmed = input.trim();
  try {
    const parsed = JSON.parse(trimmed);
    if (parsed === null || typeof parsed !== "object") {
      return null;
    }
    if (Array.isArray(parsed) && parsed.length === 0) {
      return null;
    }
    if (!Array.isArray(parsed) && Object.keys(parsed).length === 0) return null;
    return parsed;
  } catch {
    return null;
  }
}

// packages/cli/src/ui/components/shared/Scrollable.tsx
var import_react17 = __toESM(require_react(), 1);

// packages/cli/src/ui/contexts/ScrollProvider.tsx
var import_react14 = __toESM(require_react(), 1);

// packages/cli/src/ui/hooks/useMouse.ts
var import_react13 = __toESM(require_react(), 1);

// packages/cli/src/ui/contexts/MouseContext.tsx
var import_react12 = __toESM(require_react(), 1);
var import_jsx_runtime17 = __toESM(require_jsx_runtime(), 1);
var MAX_MOUSE_BUFFER_SIZE = 4096;
var MouseContext = (0, import_react12.createContext)(void 0);
function useMouseContext() {
  const context = (0, import_react12.useContext)(MouseContext);
  if (!context) {
    throw new Error("useMouseContext must be used within a MouseProvider");
  }
  return context;
}
function useMouse(handler, { isActive = true } = {}) {
  const { subscribe: subscribe2, unsubscribe } = useMouseContext();
  (0, import_react12.useEffect)(() => {
    if (!isActive) {
      return;
    }
    subscribe2(handler);
    return () => unsubscribe(handler);
  }, [isActive, handler, subscribe2, unsubscribe]);
}
function MouseProvider({
  children,
  mouseEventsEnabled
}) {
  const { settings } = useSettingsStore();
  const debugKeystrokeLogging = settings.merged.general.debugKeystrokeLogging;
  const { stdin } = use_stdin_default();
  const subscribers = (0, import_react12.useRef)(/* @__PURE__ */ new Set()).current;
  const lastClickRef = (0, import_react12.useRef)(null);
  const subscribe2 = (0, import_react12.useCallback)(
    (handler) => {
      subscribers.add(handler);
    },
    [subscribers]
  );
  const unsubscribe = (0, import_react12.useCallback)(
    (handler) => {
      subscribers.delete(handler);
    },
    [subscribers]
  );
  (0, import_react12.useEffect)(() => {
    if (!mouseEventsEnabled) {
      return;
    }
    let mouseBuffer = "";
    const broadcast = (event) => {
      let handled = false;
      for (const handler of subscribers) {
        if (handler(event) === true) {
          handled = true;
        }
      }
      if (event.name === "left-press") {
        const now = Date.now();
        const lastClick = lastClickRef.current;
        if (lastClick && now - lastClick.time < DOUBLE_CLICK_THRESHOLD_MS && Math.abs(event.col - lastClick.col) <= DOUBLE_CLICK_DISTANCE_TOLERANCE && Math.abs(event.row - lastClick.row) <= DOUBLE_CLICK_DISTANCE_TOLERANCE) {
          const doubleClickEvent = {
            ...event,
            name: "double-click"
          };
          for (const handler of subscribers) {
            handler(doubleClickEvent);
          }
          lastClickRef.current = null;
        } else {
          lastClickRef.current = { time: now, col: event.col, row: event.row };
        }
      }
      if (!handled && event.name === "move" && event.col >= 0 && event.row >= 0 && event.button === "left") {
        appEvents.emit("selection-warning" /* SelectionWarning */);
      }
    };
    const handleData = (data) => {
      mouseBuffer += typeof data === "string" ? data : data.toString("utf-8");
      if (mouseBuffer.length > MAX_MOUSE_BUFFER_SIZE) {
        mouseBuffer = mouseBuffer.slice(-MAX_MOUSE_BUFFER_SIZE);
      }
      while (mouseBuffer.length > 0) {
        const parsed = parseMouseEvent(mouseBuffer);
        if (parsed) {
          if (debugKeystrokeLogging) {
            debugLogger.log(
              "[DEBUG] Mouse event parsed:",
              JSON.stringify(parsed.event)
            );
          }
          broadcast(parsed.event);
          mouseBuffer = mouseBuffer.slice(parsed.length);
          continue;
        }
        if (isIncompleteMouseSequence(mouseBuffer)) {
          break;
        }
        const nextEsc = mouseBuffer.indexOf(ESC, 1);
        if (nextEsc !== -1) {
          mouseBuffer = mouseBuffer.slice(nextEsc);
        } else {
          mouseBuffer = "";
          break;
        }
      }
    };
    stdin.on("data", handleData);
    return () => {
      stdin.removeListener("data", handleData);
    };
  }, [stdin, mouseEventsEnabled, subscribers, debugKeystrokeLogging]);
  const contextValue = (0, import_react12.useMemo)(
    () => ({ subscribe: subscribe2, unsubscribe }),
    [subscribe2, unsubscribe]
  );
  return /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(MouseContext.Provider, { value: contextValue, children });
}

// packages/cli/src/ui/hooks/useMouse.ts
function useMouse2(onMouseEvent, { isActive }) {
  const { subscribe: subscribe2, unsubscribe } = useMouseContext();
  (0, import_react13.useEffect)(() => {
    if (!isActive) {
      return;
    }
    subscribe2(onMouseEvent);
    return () => {
      unsubscribe(onMouseEvent);
    };
  }, [isActive, onMouseEvent, subscribe2, unsubscribe]);
}

// packages/cli/src/ui/contexts/ScrollProvider.tsx
var import_jsx_runtime18 = __toESM(require_jsx_runtime(), 1);
var ScrollContext = (0, import_react14.createContext)(null);
var findScrollableCandidates = (mouseEvent, scrollables) => {
  const candidates = [];
  for (const entry of scrollables.values()) {
    if (!entry.ref.current) {
      continue;
    }
    const boundingBox = getBoundingBox(entry.ref.current);
    if (!boundingBox) continue;
    const { x, y, width, height } = boundingBox;
    const isInside = mouseEvent.col >= x && mouseEvent.col < x + width + 1 && // Intentionally add one to width to include scrollbar.
    mouseEvent.row >= y && mouseEvent.row < y + height;
    if (isInside) {
      candidates.push({ ...entry, area: width * height });
    }
  }
  candidates.sort((a, b) => a.area - b.area);
  return candidates;
};
var ScrollProvider = ({
  children
}) => {
  const [scrollables, setScrollables] = (0, import_react14.useState)(
    /* @__PURE__ */ new Map()
  );
  const register = (0, import_react14.useCallback)((entry) => {
    setScrollables((prev) => new Map(prev).set(entry.id, entry));
  }, []);
  const unregister = (0, import_react14.useCallback)((id) => {
    setScrollables((prev) => {
      const next = new Map(prev);
      next.delete(id);
      return next;
    });
  }, []);
  const scrollablesRef = (0, import_react14.useRef)(scrollables);
  (0, import_react14.useEffect)(() => {
    scrollablesRef.current = scrollables;
  }, [scrollables]);
  const pendingScrollsRef = (0, import_react14.useRef)(/* @__PURE__ */ new Map());
  const flushScheduledRef = (0, import_react14.useRef)(false);
  const dragStateRef = (0, import_react14.useRef)({
    active: false,
    id: null,
    offset: 0
  });
  const scheduleFlush = (0, import_react14.useCallback)(() => {
    if (!flushScheduledRef.current) {
      flushScheduledRef.current = true;
      setTimeout(() => {
        flushScheduledRef.current = false;
        for (const [id, delta] of pendingScrollsRef.current.entries()) {
          const entry = scrollablesRef.current.get(id);
          if (entry) {
            entry.scrollBy(delta);
          }
        }
        pendingScrollsRef.current.clear();
      }, 0);
    }
  }, []);
  const scrollMomentumRef = (0, import_react14.useRef)({
    count: 0,
    lastTime: 0
  });
  const handleScroll = (direction, mouseEvent) => {
    let multiplier = 1;
    const now = Date.now();
    if (!terminalCapabilityManager.isGhosttyTerminal()) {
      const timeSinceLastScroll = now - scrollMomentumRef.current.lastTime;
      if (timeSinceLastScroll < 50) {
        scrollMomentumRef.current.count += 1;
        multiplier = Math.min(
          3,
          1 + Math.max(0, scrollMomentumRef.current.count - 5) * 0.1
        );
      } else {
        scrollMomentumRef.current.count = 0;
      }
    }
    scrollMomentumRef.current.lastTime = now;
    const delta = (direction === "up" ? -1 : 1) * multiplier;
    const candidates = findScrollableCandidates(
      mouseEvent,
      scrollablesRef.current
    );
    for (const candidate of candidates) {
      const { scrollTop, scrollHeight, innerHeight } = candidate.getScrollState();
      const pendingDelta = pendingScrollsRef.current.get(candidate.id) || 0;
      const effectiveScrollTop = scrollTop + pendingDelta;
      const canScrollUp = effectiveScrollTop > 1e-3;
      const canScrollDown = effectiveScrollTop < scrollHeight - innerHeight - 1e-3;
      const totalDelta = Math.round(pendingDelta + delta);
      if (direction === "up" && canScrollUp) {
        pendingScrollsRef.current.set(candidate.id, totalDelta);
        scheduleFlush();
        return true;
      }
      if (direction === "down" && canScrollDown) {
        pendingScrollsRef.current.set(candidate.id, totalDelta);
        scheduleFlush();
        return true;
      }
    }
    return false;
  };
  const handleLeftPress = (mouseEvent) => {
    for (const entry of scrollablesRef.current.values()) {
      if (!entry.ref.current || !entry.hasFocus()) {
        continue;
      }
      const boundingBox = getBoundingBox(entry.ref.current);
      if (!boundingBox) continue;
      const { x, y, width, height } = boundingBox;
      if (mouseEvent.col === x + width && mouseEvent.row >= y && mouseEvent.row < y + height) {
        const { scrollTop, scrollHeight, innerHeight } = entry.getScrollState();
        if (scrollHeight <= innerHeight) continue;
        const thumbHeight = Math.max(
          1,
          Math.floor(innerHeight / scrollHeight * innerHeight)
        );
        const maxScrollTop = scrollHeight - innerHeight;
        const maxThumbY = innerHeight - thumbHeight;
        if (maxThumbY <= 0) continue;
        const currentThumbY = Math.round(
          scrollTop / maxScrollTop * maxThumbY
        );
        const absoluteThumbTop = y + currentThumbY;
        const absoluteThumbBottom = absoluteThumbTop + thumbHeight;
        const isTop = mouseEvent.row === y;
        const isBottom = mouseEvent.row === y + height - 1;
        const hitTop = isTop ? absoluteThumbTop : absoluteThumbTop - 1;
        const hitBottom = isBottom ? absoluteThumbBottom : absoluteThumbBottom + 1;
        const isThumbClick = mouseEvent.row >= hitTop && mouseEvent.row < hitBottom;
        let offset = 0;
        const relativeMouseY = mouseEvent.row - y;
        if (isThumbClick) {
          offset = relativeMouseY - currentThumbY;
        } else {
          const targetThumbY = Math.max(
            0,
            Math.min(maxThumbY, relativeMouseY - Math.floor(thumbHeight / 2))
          );
          const newScrollTop = Math.round(
            targetThumbY / maxThumbY * maxScrollTop
          );
          if (entry.scrollTo) {
            entry.scrollTo(newScrollTop);
          } else {
            entry.scrollBy(newScrollTop - scrollTop);
          }
          offset = relativeMouseY - targetThumbY;
        }
        dragStateRef.current = {
          active: true,
          id: entry.id,
          offset
        };
        return true;
      }
    }
    const candidates = findScrollableCandidates(
      mouseEvent,
      scrollablesRef.current
    );
    if (candidates.length > 0) {
      candidates[0].flashScrollbar();
      return false;
    }
    return false;
  };
  const handleMove = (mouseEvent) => {
    const state = dragStateRef.current;
    if (!state.active || !state.id) return false;
    const entry = scrollablesRef.current.get(state.id);
    if (!entry || !entry.ref.current) {
      state.active = false;
      return false;
    }
    const boundingBox = getBoundingBox(entry.ref.current);
    if (!boundingBox) return false;
    const { y } = boundingBox;
    const { scrollTop, scrollHeight, innerHeight } = entry.getScrollState();
    const thumbHeight = Math.max(
      1,
      Math.floor(innerHeight / scrollHeight * innerHeight)
    );
    const maxScrollTop = scrollHeight - innerHeight;
    const maxThumbY = innerHeight - thumbHeight;
    if (maxThumbY <= 0) return false;
    const relativeMouseY = mouseEvent.row - y;
    const targetThumbY = Math.max(
      0,
      Math.min(maxThumbY, relativeMouseY - state.offset)
    );
    const targetScrollTop = Math.round(
      targetThumbY / maxThumbY * maxScrollTop
    );
    if (entry.scrollTo) {
      entry.scrollTo(targetScrollTop, 0);
    } else {
      entry.scrollBy(targetScrollTop - scrollTop);
    }
    return true;
  };
  const handleLeftRelease = () => {
    if (dragStateRef.current.active) {
      dragStateRef.current = {
        active: false,
        id: null,
        offset: 0
      };
      return true;
    }
    return false;
  };
  useMouse2(
    (event) => {
      if (event.name === "scroll-up") {
        return handleScroll("up", event);
      } else if (event.name === "scroll-down") {
        return handleScroll("down", event);
      } else if (event.name === "left-press") {
        return handleLeftPress(event);
      } else if (event.name === "move") {
        return handleMove(event);
      } else if (event.name === "left-release") {
        return handleLeftRelease();
      }
      return false;
    },
    { isActive: true }
  );
  const contextValue = (0, import_react14.useMemo)(
    () => ({ register, unregister }),
    [register, unregister]
  );
  return /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(ScrollContext.Provider, { value: contextValue, children });
};
var nextId = 0;
var useScrollable = (entry, isActive) => {
  const context = (0, import_react14.useContext)(ScrollContext);
  if (!context) {
    throw new Error("useScrollable must be used within a ScrollProvider");
  }
  const [id] = (0, import_react14.useState)(() => `scrollable-${nextId++}`);
  (0, import_react14.useEffect)(() => {
    if (isActive) {
      context.register({ ...entry, id });
      return () => {
        context.unregister(id);
      };
    }
    return;
  }, [context, entry, id, isActive]);
};

// packages/cli/src/ui/hooks/useAnimatedScrollbar.ts
var import_react15 = __toESM(require_react(), 1);
function useAnimatedScrollbar(isFocused, scrollBy) {
  const [scrollbarColor, setScrollbarColor] = (0, import_react15.useState)(theme.ui.dark);
  const colorRef = (0, import_react15.useRef)(scrollbarColor);
  colorRef.current = scrollbarColor;
  const animationFrame = (0, import_react15.useRef)(null);
  const timeout2 = (0, import_react15.useRef)(null);
  const isAnimatingRef = (0, import_react15.useRef)(false);
  const cleanup = (0, import_react15.useCallback)(() => {
    if (isAnimatingRef.current) {
      debugState.debugNumAnimatedComponents--;
      isAnimatingRef.current = false;
    }
    if (animationFrame.current) {
      clearInterval(animationFrame.current);
      animationFrame.current = null;
    }
    if (timeout2.current) {
      clearTimeout(timeout2.current);
      timeout2.current = null;
    }
  }, []);
  const flashScrollbar = (0, import_react15.useCallback)(() => {
    cleanup();
    debugState.debugNumAnimatedComponents++;
    isAnimatingRef.current = true;
    const isTest = typeof process !== "undefined" && false;
    const fadeInDuration = isTest ? 0 : 200;
    const visibleDuration = isTest ? 0 : 1e3;
    const fadeOutDuration = isTest ? 0 : 300;
    const focusedColor = theme.text.secondary;
    const unfocusedColor = theme.ui.dark;
    const startColor = colorRef.current;
    if (!focusedColor || !unfocusedColor) {
      return;
    }
    if (isTest) {
      setScrollbarColor(unfocusedColor);
      cleanup();
      return;
    }
    let start = Date.now();
    const animateFadeIn = () => {
      if (!isAnimatingRef.current) return;
      const elapsed = Date.now() - start;
      const progress = Math.max(0, Math.min(elapsed / fadeInDuration, 1));
      setScrollbarColor(interpolateColor(startColor, focusedColor, progress));
      if (progress === 1) {
        if (animationFrame.current) {
          clearInterval(animationFrame.current);
          animationFrame.current = null;
        }
        timeout2.current = setTimeout(() => {
          start = Date.now();
          const animateFadeOut = () => {
            if (!isAnimatingRef.current) return;
            const elapsed2 = Date.now() - start;
            const progress2 = Math.max(
              0,
              Math.min(elapsed2 / fadeOutDuration, 1)
            );
            setScrollbarColor(
              interpolateColor(focusedColor, unfocusedColor, progress2)
            );
            if (progress2 === 1) {
              cleanup();
            }
          };
          animationFrame.current = setInterval(animateFadeOut, 33);
        }, visibleDuration);
      }
    };
    animationFrame.current = setInterval(animateFadeIn, 33);
  }, [cleanup]);
  const wasFocused = (0, import_react15.useRef)(isFocused);
  (0, import_react15.useLayoutEffect)(() => {
    if (isFocused && !wasFocused.current) {
      flashScrollbar();
    } else if (!isFocused && wasFocused.current) {
      cleanup();
      setScrollbarColor(theme.ui.dark);
    }
    wasFocused.current = isFocused;
    return cleanup;
  }, [isFocused, flashScrollbar, cleanup]);
  const scrollByWithAnimation = (0, import_react15.useCallback)(
    (delta) => {
      scrollBy(delta);
      flashScrollbar();
    },
    [scrollBy, flashScrollbar]
  );
  return { scrollbarColor, flashScrollbar, scrollByWithAnimation };
}

// packages/cli/src/ui/hooks/useBatchedScroll.ts
var import_react16 = __toESM(require_react(), 1);
function useBatchedScroll(currentScrollTop) {
  const pendingScrollTopRef = (0, import_react16.useRef)(null);
  const currentScrollTopRef = (0, import_react16.useRef)(currentScrollTop);
  (0, import_react16.useLayoutEffect)(() => {
    currentScrollTopRef.current = currentScrollTop;
    pendingScrollTopRef.current = null;
  });
  const getScrollTop = (0, import_react16.useCallback)(
    () => pendingScrollTopRef.current ?? currentScrollTopRef.current,
    []
  );
  const setPendingScrollTop = (0, import_react16.useCallback)((newScrollTop) => {
    pendingScrollTopRef.current = newScrollTop;
  }, []);
  return { getScrollTop, setPendingScrollTop };
}

// packages/cli/src/ui/components/shared/Scrollable.tsx
var import_jsx_runtime19 = __toESM(require_jsx_runtime(), 1);
var Scrollable = ({
  children,
  width,
  height,
  maxWidth,
  maxHeight,
  hasFocus,
  scrollToBottom,
  flexGrow,
  reportOverflow = false,
  overflowToBackbuffer,
  scrollbar = true,
  stableScrollback
}) => {
  const keyMatchers = useKeyMatchers();
  const [scrollTop, setScrollTop] = (0, import_react17.useState)(0);
  const viewportRef = (0, import_react17.useRef)(null);
  const contentRef = (0, import_react17.useRef)(null);
  const overflowActions = useOverflowActions();
  const id = (0, import_react17.useId)();
  const [size, setSize] = (0, import_react17.useState)({
    innerHeight: typeof height === "number" ? height : 0,
    scrollHeight: 0
  });
  const sizeRef = (0, import_react17.useRef)(size);
  const scrollTopRef = (0, import_react17.useRef)(scrollTop);
  (0, import_react17.useLayoutEffect)(() => {
    sizeRef.current = size;
  }, [size]);
  (0, import_react17.useLayoutEffect)(() => {
    scrollTopRef.current = scrollTop;
  }, [scrollTop]);
  (0, import_react17.useEffect)(() => {
    if (reportOverflow && size.scrollHeight > size.innerHeight) {
      overflowActions?.addOverflowingId?.(id);
    } else {
      overflowActions?.removeOverflowingId?.(id);
    }
  }, [
    reportOverflow,
    size.scrollHeight,
    size.innerHeight,
    id,
    overflowActions
  ]);
  (0, import_react17.useEffect)(
    () => () => {
      overflowActions?.removeOverflowingId?.(id);
    },
    [id, overflowActions]
  );
  const viewportObserverRef = (0, import_react17.useRef)(null);
  const contentObserverRef = (0, import_react17.useRef)(null);
  (0, import_react17.useEffect)(
    () => () => {
      viewportObserverRef.current?.disconnect();
      contentObserverRef.current?.disconnect();
    },
    []
  );
  const viewportRefCallback = (0, import_react17.useCallback)((node) => {
    viewportObserverRef.current?.disconnect();
    viewportRef.current = node;
    if (node) {
      const observer = new ResizeObserver((entries) => {
        const entry = entries[0];
        if (entry) {
          const innerHeight = Math.round(entry.contentRect.height);
          setSize((prev) => {
            const scrollHeight = prev.scrollHeight;
            const isAtBottom = scrollHeight > prev.innerHeight && scrollTopRef.current >= scrollHeight - prev.innerHeight - 1;
            if (isAtBottom) {
              setScrollTop(Number.MAX_SAFE_INTEGER);
            }
            return { ...prev, innerHeight };
          });
        }
      });
      observer.observe(node);
      viewportObserverRef.current = observer;
    }
  }, []);
  const contentRefCallback = (0, import_react17.useCallback)(
    (node) => {
      contentObserverRef.current?.disconnect();
      contentRef.current = node;
      if (node) {
        const observer = new ResizeObserver((entries) => {
          const entry = entries[0];
          if (entry) {
            const scrollHeight = Math.round(entry.contentRect.height);
            setSize((prev) => {
              const innerHeight = prev.innerHeight;
              const isAtBottom = prev.scrollHeight > innerHeight && scrollTopRef.current >= prev.scrollHeight - innerHeight - 1;
              if (isAtBottom || scrollToBottom && scrollHeight > prev.scrollHeight) {
                setScrollTop(Number.MAX_SAFE_INTEGER);
              }
              return { ...prev, scrollHeight };
            });
          }
        });
        observer.observe(node);
        contentObserverRef.current = observer;
      }
    },
    [scrollToBottom]
  );
  const { getScrollTop, setPendingScrollTop } = useBatchedScroll(scrollTop);
  const scrollBy = (0, import_react17.useCallback)(
    (delta) => {
      const { scrollHeight, innerHeight } = sizeRef.current;
      const maxScroll = Math.max(0, scrollHeight - innerHeight);
      const current = Math.min(getScrollTop(), maxScroll);
      let next = Math.max(0, current + delta);
      if (next >= maxScroll) {
        next = Number.MAX_SAFE_INTEGER;
      }
      setPendingScrollTop(next);
      setScrollTop(next);
    },
    [getScrollTop, setPendingScrollTop]
  );
  const { scrollbarColor, flashScrollbar, scrollByWithAnimation } = useAnimatedScrollbar(hasFocus, scrollBy);
  useKeypress(
    (key) => {
      const { scrollHeight, innerHeight } = sizeRef.current;
      const scrollTop2 = getScrollTop();
      const maxScroll = Math.max(0, scrollHeight - innerHeight);
      const actualScrollTop = Math.min(scrollTop2, maxScroll);
      if (actualScrollTop > 0) {
        if (keyMatchers["scroll.pageUp" /* PAGE_UP */](key)) {
          scrollByWithAnimation(-innerHeight);
          return true;
        }
        if (keyMatchers["scroll.up" /* SCROLL_UP */](key)) {
          scrollByWithAnimation(-1);
          return true;
        }
      }
      if (actualScrollTop < maxScroll) {
        if (keyMatchers["scroll.pageDown" /* PAGE_DOWN */](key)) {
          scrollByWithAnimation(innerHeight);
          return true;
        }
        if (keyMatchers["scroll.down" /* SCROLL_DOWN */](key)) {
          scrollByWithAnimation(1);
          return true;
        }
      }
      return false;
    },
    { isActive: hasFocus }
  );
  const getScrollState = (0, import_react17.useCallback)(() => {
    const maxScroll = Math.max(0, size.scrollHeight - size.innerHeight);
    return {
      scrollTop: Math.min(getScrollTop(), maxScroll),
      scrollHeight: size.scrollHeight,
      innerHeight: size.innerHeight
    };
  }, [getScrollTop, size.scrollHeight, size.innerHeight]);
  const hasFocusCallback = (0, import_react17.useCallback)(() => hasFocus, [hasFocus]);
  const scrollableEntry = (0, import_react17.useMemo)(
    () => ({
      // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
      ref: viewportRef,
      getScrollState,
      scrollBy: scrollByWithAnimation,
      hasFocus: hasFocusCallback,
      flashScrollbar
    }),
    [getScrollState, scrollByWithAnimation, hasFocusCallback, flashScrollbar]
  );
  useScrollable(scrollableEntry, true);
  return /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(
    Box_default,
    {
      ref: viewportRefCallback,
      maxHeight,
      width: width ?? maxWidth,
      height,
      flexDirection: "column",
      overflowY: "scroll",
      overflowX: "hidden",
      scrollTop,
      flexGrow,
      scrollbarThumbColor: scrollbarColor,
      overflowToBackbuffer,
      scrollbar,
      stableScrollback,
      children: /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(
        Box_default,
        {
          ref: contentRefCallback,
          flexShrink: 0,
          paddingRight: 1,
          flexDirection: "column",
          children
        }
      )
    }
  );
};

// packages/cli/src/ui/components/shared/ScrollableList.tsx
var import_react19 = __toESM(require_react(), 1);

// packages/cli/src/ui/components/shared/VirtualizedList.tsx
var import_react18 = __toESM(require_react(), 1);
var import_jsx_runtime20 = __toESM(require_jsx_runtime(), 1);
var SCROLL_TO_ITEM_END = Number.MAX_SAFE_INTEGER;
function findLastIndex(array, predicate) {
  for (let i = array.length - 1; i >= 0; i--) {
    if (predicate(array[i], i, array)) {
      return i;
    }
  }
  return -1;
}
var VirtualizedListItem = (0, import_react18.memo)(
  ({
    content,
    shouldBeStatic,
    width,
    containerWidth,
    itemKey,
    index,
    onSetRef
  }) => {
    const itemRef = (0, import_react18.useCallback)(
      (el) => {
        onSetRef(index, el);
      },
      [index, onSetRef]
    );
    return /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(Box_default, { width: "100%", flexDirection: "column", flexShrink: 0, ref: itemRef, children: shouldBeStatic ? /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(
      StaticRender,
      {
        width: typeof width === "number" ? width : containerWidth,
        children: content
      },
      itemKey + "-static-" + (typeof width === "number" ? width : containerWidth)
    ) : content });
  }
);
VirtualizedListItem.displayName = "VirtualizedListItem";
function VirtualizedList(props, ref) {
  const {
    data,
    renderItem,
    estimatedItemHeight,
    keyExtractor,
    initialScrollIndex,
    initialScrollOffsetInIndex,
    renderStatic,
    isStatic,
    isStaticItem,
    width,
    overflowToBackbuffer,
    scrollbar = true,
    stableScrollback,
    copyModeEnabled = false,
    fixedItemHeight = false
  } = props;
  const dataRef = (0, import_react18.useRef)(data);
  (0, import_react18.useLayoutEffect)(() => {
    dataRef.current = data;
  }, [data]);
  const [scrollAnchor, setScrollAnchor] = (0, import_react18.useState)(() => {
    const scrollToEnd = initialScrollIndex === SCROLL_TO_ITEM_END || typeof initialScrollIndex === "number" && initialScrollIndex >= data.length - 1 && initialScrollOffsetInIndex === SCROLL_TO_ITEM_END;
    if (scrollToEnd) {
      return {
        index: data.length > 0 ? data.length - 1 : 0,
        offset: SCROLL_TO_ITEM_END
      };
    }
    if (typeof initialScrollIndex === "number") {
      return {
        index: Math.max(0, Math.min(data.length - 1, initialScrollIndex)),
        offset: initialScrollOffsetInIndex ?? 0
      };
    }
    if (typeof props.targetScrollIndex === "number") {
      return {
        index: props.targetScrollIndex,
        offset: 0
      };
    }
    return { index: 0, offset: 0 };
  });
  const [isStickingToBottom, setIsStickingToBottom] = (0, import_react18.useState)(() => {
    const scrollToEnd = initialScrollIndex === SCROLL_TO_ITEM_END || typeof initialScrollIndex === "number" && initialScrollIndex >= data.length - 1 && initialScrollOffsetInIndex === SCROLL_TO_ITEM_END;
    return scrollToEnd;
  });
  const containerRef = (0, import_react18.useRef)(null);
  const [containerHeight, setContainerHeight] = (0, import_react18.useState)(0);
  const [containerWidth, setContainerWidth] = (0, import_react18.useState)(0);
  const itemRefs = (0, import_react18.useRef)([]);
  const [heights, setHeights] = (0, import_react18.useState)({});
  const isInitialScrollSet = (0, import_react18.useRef)(false);
  const containerObserverRef = (0, import_react18.useRef)(null);
  const nodeToKeyRef = (0, import_react18.useRef)(/* @__PURE__ */ new WeakMap());
  const onSetRef = (0, import_react18.useCallback)((index, el) => {
    itemRefs.current[index] = el;
  }, []);
  const containerRefCallback = (0, import_react18.useCallback)((node) => {
    containerObserverRef.current?.disconnect();
    containerRef.current = node;
    if (node) {
      const observer = new ResizeObserver((entries) => {
        const entry = entries[0];
        if (entry) {
          const newHeight = Math.round(entry.contentRect.height);
          const newWidth = Math.round(entry.contentRect.width);
          setContainerHeight((prev) => prev !== newHeight ? newHeight : prev);
          setContainerWidth((prev) => prev !== newWidth ? newWidth : prev);
        }
      });
      observer.observe(node);
      containerObserverRef.current = observer;
    }
  }, []);
  const itemsObserver = (0, import_react18.useMemo)(
    () => new ResizeObserver((entries) => {
      setHeights((prev) => {
        let next = null;
        for (const entry of entries) {
          const key = nodeToKeyRef.current.get(entry.target);
          if (key !== void 0) {
            const height = Math.round(entry.contentRect.height);
            if (prev[key] !== height) {
              if (!next) {
                next = { ...prev };
              }
              next[key] = height;
            }
          }
        }
        return next ?? prev;
      });
    }),
    []
  );
  (0, import_react18.useLayoutEffect)(
    () => () => {
      containerObserverRef.current?.disconnect();
      itemsObserver.disconnect();
    },
    [itemsObserver]
  );
  const { totalHeight, offsets } = (0, import_react18.useMemo)(() => {
    const offsets2 = [0];
    let totalHeight2 = 0;
    for (let i = 0; i < data.length; i++) {
      const key = keyExtractor(data[i], i);
      const height = heights[key] ?? estimatedItemHeight(i);
      totalHeight2 += height;
      offsets2.push(totalHeight2);
    }
    return { totalHeight: totalHeight2, offsets: offsets2 };
  }, [heights, data, estimatedItemHeight, keyExtractor]);
  const scrollableContainerHeight = props.containerHeight ?? containerHeight;
  const getAnchorForScrollTop = (0, import_react18.useCallback)(
    (scrollTop2, offsets2) => {
      const index = findLastIndex(offsets2, (offset) => offset <= scrollTop2);
      if (index === -1) {
        return { index: 0, offset: 0 };
      }
      return { index, offset: scrollTop2 - offsets2[index] };
    },
    []
  );
  const [prevTargetScrollIndex, setPrevTargetScrollIndex] = (0, import_react18.useState)(
    props.targetScrollIndex
  );
  const prevOffsetsLength = (0, import_react18.useRef)(offsets.length);
  if (props.targetScrollIndex !== void 0 && props.targetScrollIndex !== prevTargetScrollIndex && offsets.length > 1 || props.targetScrollIndex !== void 0 && prevOffsetsLength.current <= 1 && offsets.length > 1) {
    if (props.targetScrollIndex !== prevTargetScrollIndex) {
      setPrevTargetScrollIndex(props.targetScrollIndex);
    }
    prevOffsetsLength.current = offsets.length;
    setIsStickingToBottom(false);
    setScrollAnchor({ index: props.targetScrollIndex, offset: 0 });
  } else {
    prevOffsetsLength.current = offsets.length;
  }
  const actualScrollTop = (0, import_react18.useMemo)(() => {
    const offset = offsets[scrollAnchor.index];
    if (typeof offset !== "number") {
      return 0;
    }
    if (scrollAnchor.offset === SCROLL_TO_ITEM_END) {
      const item = data[scrollAnchor.index];
      const key = item ? keyExtractor(item, scrollAnchor.index) : "";
      const itemHeight = heights[key] ?? 0;
      return offset + itemHeight - scrollableContainerHeight;
    }
    return offset + scrollAnchor.offset;
  }, [
    scrollAnchor,
    offsets,
    heights,
    scrollableContainerHeight,
    data,
    keyExtractor
  ]);
  const scrollTop = isStickingToBottom ? Number.MAX_SAFE_INTEGER : actualScrollTop;
  const prevDataLength = (0, import_react18.useRef)(data.length);
  const prevTotalHeight = (0, import_react18.useRef)(totalHeight);
  const prevScrollTop = (0, import_react18.useRef)(actualScrollTop);
  const prevContainerHeight = (0, import_react18.useRef)(scrollableContainerHeight);
  (0, import_react18.useLayoutEffect)(() => {
    const contentPreviouslyFit = prevTotalHeight.current <= prevContainerHeight.current;
    const wasScrolledToBottomPixels = prevScrollTop.current >= prevTotalHeight.current - prevContainerHeight.current - 1;
    const wasAtBottom = contentPreviouslyFit || wasScrolledToBottomPixels;
    if (wasAtBottom && actualScrollTop >= prevScrollTop.current) {
      if (!isStickingToBottom) {
        setIsStickingToBottom(true);
      }
    }
    const listGrew = data.length > prevDataLength.current;
    const containerChanged = prevContainerHeight.current !== scrollableContainerHeight;
    const shouldAutoScroll = props.targetScrollIndex === void 0;
    if (shouldAutoScroll && (listGrew && (isStickingToBottom || wasAtBottom) || isStickingToBottom && containerChanged)) {
      const newIndex = data.length > 0 ? data.length - 1 : 0;
      if (scrollAnchor.index !== newIndex || scrollAnchor.offset !== SCROLL_TO_ITEM_END) {
        setScrollAnchor({
          index: newIndex,
          offset: SCROLL_TO_ITEM_END
        });
      }
      if (!isStickingToBottom) {
        setIsStickingToBottom(true);
      }
    } else if ((scrollAnchor.index >= data.length || actualScrollTop > totalHeight - scrollableContainerHeight) && data.length > 0) {
      const newScrollTop = Math.max(0, totalHeight - scrollableContainerHeight);
      const newAnchor = getAnchorForScrollTop(newScrollTop, offsets);
      if (scrollAnchor.index !== newAnchor.index || scrollAnchor.offset !== newAnchor.offset) {
        setScrollAnchor(newAnchor);
      }
    } else if (data.length === 0) {
      if (scrollAnchor.index !== 0 || scrollAnchor.offset !== 0) {
        setScrollAnchor({ index: 0, offset: 0 });
      }
    }
    prevDataLength.current = data.length;
    prevTotalHeight.current = totalHeight;
    prevScrollTop.current = actualScrollTop;
    prevContainerHeight.current = scrollableContainerHeight;
  }, [
    data.length,
    totalHeight,
    actualScrollTop,
    scrollableContainerHeight,
    scrollAnchor.index,
    scrollAnchor.offset,
    getAnchorForScrollTop,
    offsets,
    isStickingToBottom,
    props.targetScrollIndex
  ]);
  (0, import_react18.useLayoutEffect)(() => {
    if (isInitialScrollSet.current || offsets.length <= 1 || totalHeight <= 0 || scrollableContainerHeight <= 0) {
      return;
    }
    if (props.targetScrollIndex !== void 0) {
      isInitialScrollSet.current = true;
      return;
    }
    if (typeof initialScrollIndex === "number") {
      const scrollToEnd = initialScrollIndex === SCROLL_TO_ITEM_END || initialScrollIndex >= data.length - 1 && initialScrollOffsetInIndex === SCROLL_TO_ITEM_END;
      if (scrollToEnd) {
        setScrollAnchor({
          index: data.length - 1,
          offset: SCROLL_TO_ITEM_END
        });
        setIsStickingToBottom(true);
        isInitialScrollSet.current = true;
        return;
      }
      const index = Math.max(0, Math.min(data.length - 1, initialScrollIndex));
      const offset = initialScrollOffsetInIndex ?? 0;
      const newScrollTop = (offsets[index] ?? 0) + offset;
      const clampedScrollTop = Math.max(
        0,
        Math.min(totalHeight - scrollableContainerHeight, newScrollTop)
      );
      setScrollAnchor(getAnchorForScrollTop(clampedScrollTop, offsets));
      isInitialScrollSet.current = true;
    }
  }, [
    initialScrollIndex,
    initialScrollOffsetInIndex,
    offsets,
    totalHeight,
    scrollableContainerHeight,
    getAnchorForScrollTop,
    data.length,
    heights,
    props.targetScrollIndex
  ]);
  const startIndex = Math.max(
    0,
    findLastIndex(offsets, (offset) => offset <= actualScrollTop) - 1
  );
  const viewHeightForEndIndex = scrollableContainerHeight > 0 ? scrollableContainerHeight : 50;
  const endIndexOffset = offsets.findIndex(
    (offset) => offset > actualScrollTop + viewHeightForEndIndex
  );
  const endIndex = endIndexOffset === -1 ? data.length - 1 : Math.min(data.length - 1, endIndexOffset);
  const topSpacerHeight = renderStatic === true || overflowToBackbuffer === true ? 0 : offsets[startIndex] ?? 0;
  const bottomSpacerHeight = renderStatic ? 0 : totalHeight - (offsets[endIndex + 1] ?? totalHeight);
  const observedNodes = (0, import_react18.useRef)(/* @__PURE__ */ new Set());
  (0, import_react18.useLayoutEffect)(() => {
    const currentNodes = /* @__PURE__ */ new Set();
    const observeStart = renderStatic || overflowToBackbuffer ? 0 : startIndex;
    const observeEnd = renderStatic ? data.length - 1 : endIndex;
    for (let i = observeStart; i <= observeEnd; i++) {
      const node = itemRefs.current[i];
      const item = data[i];
      if (node && item) {
        currentNodes.add(node);
        const key = keyExtractor(item, i);
        nodeToKeyRef.current.set(node, key);
        if (!isStatic && !fixedItemHeight && !observedNodes.current.has(node)) {
          itemsObserver.observe(node);
        }
      }
    }
    for (const node of observedNodes.current) {
      if (!currentNodes.has(node)) {
        if (!isStatic && !fixedItemHeight) {
          itemsObserver.unobserve(node);
        }
        nodeToKeyRef.current.delete(node);
      }
    }
    observedNodes.current = currentNodes;
  });
  const renderRangeStart = renderStatic || overflowToBackbuffer ? 0 : startIndex;
  const renderRangeEnd = renderStatic ? data.length - 1 : endIndex;
  const isReady = containerHeight > 0 || false || width !== void 0 && typeof width === "number";
  const renderedItems = (0, import_react18.useMemo)(() => {
    if (!isReady) {
      return [];
    }
    const items = [];
    for (let i = renderRangeStart; i <= renderRangeEnd; i++) {
      const item = data[i];
      if (item) {
        const isOutsideViewport = i < startIndex || i > endIndex;
        const shouldBeStatic = renderStatic === true && isOutsideViewport || isStaticItem?.(item, i) === true;
        const content = renderItem({ item, index: i });
        const key = keyExtractor(item, i);
        items.push(
          /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(
            VirtualizedListItem,
            {
              itemKey: key,
              content,
              shouldBeStatic,
              width,
              containerWidth,
              index: i,
              onSetRef
            },
            key
          )
        );
      }
    }
    return items;
  }, [
    isReady,
    renderRangeStart,
    renderRangeEnd,
    data,
    startIndex,
    endIndex,
    renderStatic,
    isStaticItem,
    renderItem,
    keyExtractor,
    width,
    containerWidth,
    onSetRef
  ]);
  const { getScrollTop, setPendingScrollTop } = useBatchedScroll(scrollTop);
  (0, import_react18.useImperativeHandle)(
    ref,
    () => ({
      scrollBy: (delta) => {
        if (delta < 0) {
          setIsStickingToBottom(false);
        }
        const currentScrollTop = getScrollTop();
        const maxScroll = Math.max(0, totalHeight - scrollableContainerHeight);
        const actualCurrent = Math.min(currentScrollTop, maxScroll);
        let newScrollTop = Math.max(0, actualCurrent + delta);
        if (newScrollTop >= maxScroll) {
          setIsStickingToBottom(true);
          newScrollTop = Number.MAX_SAFE_INTEGER;
        }
        setPendingScrollTop(newScrollTop);
        setScrollAnchor(
          getAnchorForScrollTop(Math.min(newScrollTop, maxScroll), offsets)
        );
      },
      scrollTo: (offset) => {
        const maxScroll = Math.max(0, totalHeight - scrollableContainerHeight);
        if (offset >= maxScroll || offset === SCROLL_TO_ITEM_END) {
          setIsStickingToBottom(true);
          setPendingScrollTop(Number.MAX_SAFE_INTEGER);
          if (data.length > 0) {
            setScrollAnchor({
              index: data.length - 1,
              offset: SCROLL_TO_ITEM_END
            });
          }
        } else {
          setIsStickingToBottom(false);
          const newScrollTop = Math.max(0, offset);
          setPendingScrollTop(newScrollTop);
          setScrollAnchor(getAnchorForScrollTop(newScrollTop, offsets));
        }
      },
      scrollToEnd: () => {
        setIsStickingToBottom(true);
        setPendingScrollTop(Number.MAX_SAFE_INTEGER);
        if (data.length > 0) {
          setScrollAnchor({
            index: data.length - 1,
            offset: SCROLL_TO_ITEM_END
          });
        }
      },
      scrollToIndex: ({
        index,
        viewOffset = 0,
        viewPosition = 0
      }) => {
        setIsStickingToBottom(false);
        const offset = offsets[index];
        if (offset !== void 0) {
          const maxScroll = Math.max(
            0,
            totalHeight - scrollableContainerHeight
          );
          const newScrollTop = Math.max(
            0,
            Math.min(
              maxScroll,
              offset - viewPosition * scrollableContainerHeight + viewOffset
            )
          );
          setPendingScrollTop(newScrollTop);
          setScrollAnchor(getAnchorForScrollTop(newScrollTop, offsets));
        }
      },
      scrollToItem: ({
        item,
        viewOffset = 0,
        viewPosition = 0
      }) => {
        setIsStickingToBottom(false);
        const index = data.indexOf(item);
        if (index !== -1) {
          const offset = offsets[index];
          if (offset !== void 0) {
            const maxScroll = Math.max(
              0,
              totalHeight - scrollableContainerHeight
            );
            const newScrollTop = Math.max(
              0,
              Math.min(
                maxScroll,
                offset - viewPosition * scrollableContainerHeight + viewOffset
              )
            );
            setPendingScrollTop(newScrollTop);
            setScrollAnchor(getAnchorForScrollTop(newScrollTop, offsets));
          }
        }
      },
      getScrollIndex: () => scrollAnchor.index,
      getScrollState: () => {
        const maxScroll = Math.max(0, totalHeight - scrollableContainerHeight);
        return {
          scrollTop: Math.min(getScrollTop(), maxScroll),
          scrollHeight: totalHeight,
          innerHeight: scrollableContainerHeight
        };
      }
    }),
    [
      offsets,
      scrollAnchor,
      totalHeight,
      getAnchorForScrollTop,
      data,
      scrollableContainerHeight,
      getScrollTop,
      setPendingScrollTop
    ]
  );
  return /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(
    Box_default,
    {
      ref: containerRefCallback,
      overflowY: copyModeEnabled ? "hidden" : "scroll",
      overflowX: "hidden",
      scrollTop: copyModeEnabled ? 0 : scrollTop,
      scrollbarThumbColor: props.scrollbarThumbColor ?? theme.text.secondary,
      backgroundColor: props.backgroundColor,
      width: "100%",
      height: "100%",
      flexDirection: "column",
      paddingRight: copyModeEnabled ? 0 : 1,
      overflowToBackbuffer,
      scrollbar,
      stableScrollback,
      children: /* @__PURE__ */ (0, import_jsx_runtime20.jsxs)(
        Box_default,
        {
          flexShrink: 0,
          width: "100%",
          flexDirection: "column",
          marginTop: copyModeEnabled ? -actualScrollTop : 0,
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(Box_default, { height: topSpacerHeight, flexShrink: 0 }),
            renderedItems,
            /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(Box_default, { height: bottomSpacerHeight, flexShrink: 0 })
          ]
        }
      )
    }
  );
}
var VirtualizedListWithForwardRef = (0, import_react18.forwardRef)(VirtualizedList);
VirtualizedList.displayName = "VirtualizedList";

// packages/cli/src/ui/components/shared/ScrollableList.tsx
var import_jsx_runtime21 = __toESM(require_jsx_runtime(), 1);
var ANIMATION_FRAME_DURATION_MS = 33;
function ScrollableList(props, ref) {
  const keyMatchers = useKeyMatchers();
  const { hasFocus, width, scrollbar = true, stableScrollback } = props;
  const virtualizedListRef = (0, import_react19.useRef)(null);
  const containerRef = (0, import_react19.useRef)(null);
  (0, import_react19.useImperativeHandle)(
    ref,
    () => ({
      scrollBy: (delta) => virtualizedListRef.current?.scrollBy(delta),
      scrollTo: (offset) => virtualizedListRef.current?.scrollTo(offset),
      scrollToEnd: () => virtualizedListRef.current?.scrollToEnd(),
      scrollToIndex: (params) => virtualizedListRef.current?.scrollToIndex(params),
      scrollToItem: (params) => virtualizedListRef.current?.scrollToItem(params),
      getScrollIndex: () => virtualizedListRef.current?.getScrollIndex() ?? 0,
      getScrollState: () => virtualizedListRef.current?.getScrollState() ?? {
        scrollTop: 0,
        scrollHeight: 0,
        innerHeight: 0
      }
    }),
    []
  );
  const getScrollState = (0, import_react19.useCallback)(
    () => virtualizedListRef.current?.getScrollState() ?? {
      scrollTop: 0,
      scrollHeight: 0,
      innerHeight: 0
    },
    []
  );
  const scrollBy = (0, import_react19.useCallback)((delta) => {
    virtualizedListRef.current?.scrollBy(delta);
  }, []);
  const { scrollbarColor, flashScrollbar, scrollByWithAnimation } = useAnimatedScrollbar(hasFocus, scrollBy);
  const smoothScrollState = (0, import_react19.useRef)({ active: false, start: 0, from: 0, to: 0, duration: 0, timer: null });
  const stopSmoothScroll = (0, import_react19.useCallback)(() => {
    if (smoothScrollState.current.timer) {
      clearInterval(smoothScrollState.current.timer);
      smoothScrollState.current.timer = null;
    }
    smoothScrollState.current.active = false;
  }, []);
  (0, import_react19.useLayoutEffect)(() => stopSmoothScroll, [stopSmoothScroll]);
  const smoothScrollTo = (0, import_react19.useCallback)(
    (targetScrollTop, duration = false ? 0 : 200) => {
      stopSmoothScroll();
      const scrollState = virtualizedListRef.current?.getScrollState() ?? {
        scrollTop: 0,
        scrollHeight: 0,
        innerHeight: 0
      };
      const {
        scrollTop: rawStartScrollTop,
        scrollHeight,
        innerHeight
      } = scrollState;
      const maxScrollTop = Math.max(0, scrollHeight - innerHeight);
      const startScrollTop = Math.min(rawStartScrollTop, maxScrollTop);
      let effectiveTarget = targetScrollTop;
      if (targetScrollTop === SCROLL_TO_ITEM_END || targetScrollTop >= maxScrollTop) {
        effectiveTarget = maxScrollTop;
      }
      const clampedTarget = Math.max(
        0,
        Math.min(maxScrollTop, effectiveTarget)
      );
      if (duration === 0) {
        if (targetScrollTop === SCROLL_TO_ITEM_END || targetScrollTop >= maxScrollTop) {
          virtualizedListRef.current?.scrollTo(Number.MAX_SAFE_INTEGER);
        } else {
          virtualizedListRef.current?.scrollTo(Math.round(clampedTarget));
        }
        flashScrollbar();
        return;
      }
      smoothScrollState.current = {
        active: true,
        start: Date.now(),
        from: startScrollTop,
        to: clampedTarget,
        duration,
        timer: setInterval(() => {
          const now = Date.now();
          const elapsed = now - smoothScrollState.current.start;
          const progress = Math.min(elapsed / duration, 1);
          const t = progress;
          const ease = t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t;
          const current = smoothScrollState.current.from + (smoothScrollState.current.to - smoothScrollState.current.from) * ease;
          if (progress >= 1) {
            if (targetScrollTop === SCROLL_TO_ITEM_END || targetScrollTop >= maxScrollTop) {
              virtualizedListRef.current?.scrollTo(Number.MAX_SAFE_INTEGER);
            } else {
              virtualizedListRef.current?.scrollTo(Math.round(current));
            }
            stopSmoothScroll();
            flashScrollbar();
          } else {
            virtualizedListRef.current?.scrollTo(Math.round(current));
          }
        }, ANIMATION_FRAME_DURATION_MS)
      };
    },
    [stopSmoothScroll, flashScrollbar]
  );
  useKeypress(
    (key) => {
      if (keyMatchers["scroll.up" /* SCROLL_UP */](key)) {
        stopSmoothScroll();
        scrollByWithAnimation(-1);
        return true;
      } else if (keyMatchers["scroll.down" /* SCROLL_DOWN */](key)) {
        stopSmoothScroll();
        scrollByWithAnimation(1);
        return true;
      } else if (keyMatchers["scroll.pageUp" /* PAGE_UP */](key) || keyMatchers["scroll.pageDown" /* PAGE_DOWN */](key)) {
        const direction = keyMatchers["scroll.pageUp" /* PAGE_UP */](key) ? -1 : 1;
        const scrollState = getScrollState();
        const maxScroll = Math.max(
          0,
          scrollState.scrollHeight - scrollState.innerHeight
        );
        const current = smoothScrollState.current.active ? smoothScrollState.current.to : Math.min(scrollState.scrollTop, maxScroll);
        const innerHeight = scrollState.innerHeight;
        smoothScrollTo(current + direction * innerHeight);
        return true;
      } else if (keyMatchers["scroll.home" /* SCROLL_HOME */](key)) {
        smoothScrollTo(0);
        return true;
      } else if (keyMatchers["scroll.end" /* SCROLL_END */](key)) {
        smoothScrollTo(SCROLL_TO_ITEM_END);
        return true;
      }
      return false;
    },
    { isActive: hasFocus }
  );
  const hasFocusCallback = (0, import_react19.useCallback)(() => hasFocus, [hasFocus]);
  const scrollableEntry = (0, import_react19.useMemo)(
    () => ({
      // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
      ref: containerRef,
      getScrollState,
      scrollBy: scrollByWithAnimation,
      scrollTo: smoothScrollTo,
      hasFocus: hasFocusCallback,
      flashScrollbar
    }),
    [
      getScrollState,
      hasFocusCallback,
      flashScrollbar,
      scrollByWithAnimation,
      smoothScrollTo
    ]
  );
  useScrollable(scrollableEntry, true);
  return /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(Box_default, { ref: containerRef, flexGrow: 1, flexDirection: "column", width, children: /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(
    VirtualizedListWithForwardRef,
    {
      ref: virtualizedListRef,
      ...props,
      scrollbar,
      scrollbarThumbColor: scrollbarColor,
      stableScrollback
    }
  ) });
}
var ScrollableListWithForwardRef = (0, import_react19.forwardRef)(ScrollableList);

// packages/cli/src/ui/utils/toolLayoutUtils.ts
var TOOL_RESULT_STATIC_HEIGHT = 1;
var TOOL_RESULT_ASB_RESERVED_LINE_COUNT = 6;
var TOOL_RESULT_STANDARD_RESERVED_LINE_COUNT = 4;
var TOOL_RESULT_MIN_LINES_SHOWN = 2;
var SHELL_CONTENT_OVERHEAD = TOOL_RESULT_STATIC_HEIGHT + TOOL_RESULT_STANDARD_RESERVED_LINE_COUNT;
function calculateToolContentMaxLines(options) {
  const { availableTerminalHeight, isAlternateBuffer, maxLinesLimit } = options;
  const reservedLines = isAlternateBuffer ? TOOL_RESULT_ASB_RESERVED_LINE_COUNT : TOOL_RESULT_STANDARD_RESERVED_LINE_COUNT;
  let contentHeight = availableTerminalHeight !== void 0 ? Math.max(
    availableTerminalHeight - TOOL_RESULT_STATIC_HEIGHT - reservedLines,
    TOOL_RESULT_MIN_LINES_SHOWN + 1
  ) : void 0;
  if (maxLinesLimit !== void 0) {
    contentHeight = contentHeight !== void 0 ? Math.min(contentHeight, maxLinesLimit) : maxLinesLimit;
  }
  return contentHeight;
}
function calculateShellMaxLines(options) {
  const {
    status,
    isAlternateBuffer,
    isThisShellFocused: isThisShellFocused2,
    availableTerminalHeight,
    constrainHeight,
    isExpandable
  } = options;
  if (!constrainHeight && isExpandable) {
    return void 0;
  }
  if (availableTerminalHeight === void 0) {
    return isAlternateBuffer ? ACTIVE_SHELL_MAX_LINES - SHELL_CONTENT_OVERHEAD : void 0;
  }
  const maxLinesBasedOnHeight = Math.max(
    1,
    availableTerminalHeight - TOOL_RESULT_STANDARD_RESERVED_LINE_COUNT
  );
  if (isAlternateBuffer && isThisShellFocused2 && !constrainHeight) {
    return maxLinesBasedOnHeight;
  }
  const isExecuting = status === CoreToolCallStatus.Executing;
  const shellMaxLinesLimit = isExecuting ? ACTIVE_SHELL_MAX_LINES - SHELL_CONTENT_OVERHEAD : COMPLETED_SHELL_MAX_LINES - SHELL_CONTENT_OVERHEAD;
  return Math.min(maxLinesBasedOnHeight, shellMaxLinesLimit);
}

// packages/cli/src/ui/components/messages/ToolShared.tsx
var import_react21 = __toESM(require_react(), 1);

// packages/cli/src/ui/hooks/useInactivityTimer.ts
var import_react20 = __toESM(require_react(), 1);
var useInactivityTimer = (isActive, trigger, delayMs = 5e3) => {
  const [isInactive, setIsInactive] = (0, import_react20.useState)(false);
  (0, import_react20.useEffect)(() => {
    if (!isActive) {
      setIsInactive(false);
      return;
    }
    setIsInactive(false);
    const timer = setTimeout(() => {
      setIsInactive(true);
    }, delayMs);
    return () => clearTimeout(timer);
  }, [isActive, trigger, delayMs]);
  return isInactive;
};

// packages/cli/src/ui/components/messages/ToolShared.tsx
var import_jsx_runtime22 = __toESM(require_jsx_runtime(), 1);
var STATUS_INDICATOR_WIDTH = 3;
function isShellTool(name) {
  return name === SHELL_COMMAND_NAME || name === SHELL_NAME || name === SHELL_TOOL_NAME;
}
function isThisShellFocusable(name, status, config) {
  return !!(isShellTool(name) && status === CoreToolCallStatus.Executing && config?.getEnableInteractiveShell());
}
function isThisShellFocused(name, status, ptyId, activeShellPtyId, embeddedShellFocused) {
  return !!(isShellTool(name) && status === CoreToolCallStatus.Executing && ptyId === activeShellPtyId && embeddedShellFocused);
}
function useFocusHint(isThisShellFocusable2, isThisShellFocused2, resultDisplay) {
  const [userHasFocused, setUserHasFocused] = (0, import_react21.useState)(false);
  const resetKey = typeof resultDisplay === "string" ? resultDisplay.length : Array.isArray(resultDisplay) ? resultDisplay.length : !!resultDisplay;
  const showFocusHint = useInactivityTimer(
    isThisShellFocusable2,
    resetKey,
    SHELL_FOCUS_HINT_DELAY_MS
  );
  (0, import_react21.useEffect)(() => {
    if (isThisShellFocused2) {
      setUserHasFocused(true);
    }
  }, [isThisShellFocused2]);
  const shouldShowFocusHint = isThisShellFocusable2 && (showFocusHint || userHasFocused);
  return { shouldShowFocusHint };
}
var FocusHint = ({ shouldShowFocusHint, isThisShellFocused: isThisShellFocused2 }) => {
  if (!shouldShowFocusHint) {
    return null;
  }
  return /* @__PURE__ */ (0, import_jsx_runtime22.jsx)(Box_default, { marginLeft: 1, flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime22.jsx)(Text, { color: isThisShellFocused2 ? theme.ui.focus : theme.ui.active, children: isThisShellFocused2 ? `(${formatCommand("app.unfocusShellInput" /* UNFOCUS_SHELL_INPUT */)} to unfocus)` : `(${formatCommand("app.focusShellInput" /* FOCUS_SHELL_INPUT */)} to focus)` }) });
};
var ToolStatusIndicator = ({
  status: coreStatus,
  name,
  isFocused
}) => {
  const status = mapCoreStatusToDisplayStatus(coreStatus);
  const isShell = isShellTool(name);
  const statusColor = isFocused ? theme.ui.focus : isShell ? theme.ui.active : theme.status.warning;
  return /* @__PURE__ */ (0, import_jsx_runtime22.jsxs)(Box_default, { minWidth: STATUS_INDICATOR_WIDTH, children: [
    status === "Pending" /* Pending */ && /* @__PURE__ */ (0, import_jsx_runtime22.jsx)(Text, { color: theme.status.success, children: TOOL_STATUS.PENDING }),
    status === "Executing" /* Executing */ && /* @__PURE__ */ (0, import_jsx_runtime22.jsx)(Text, { color: statusColor, children: /* @__PURE__ */ (0, import_jsx_runtime22.jsx)(CliSpinner, { type: "toggle" }) }),
    status === "Success" /* Success */ && /* @__PURE__ */ (0, import_jsx_runtime22.jsx)(Text, { color: theme.status.success, "aria-label": "Success:", children: TOOL_STATUS.SUCCESS }),
    status === "Confirming" /* Confirming */ && /* @__PURE__ */ (0, import_jsx_runtime22.jsx)(Text, { color: statusColor, "aria-label": "Confirming:", children: TOOL_STATUS.CONFIRMING }),
    status === "Canceled" /* Canceled */ && /* @__PURE__ */ (0, import_jsx_runtime22.jsx)(Text, { color: statusColor, "aria-label": "Canceled:", bold: true, children: TOOL_STATUS.CANCELED }),
    status === "Error" /* Error */ && /* @__PURE__ */ (0, import_jsx_runtime22.jsx)(Text, { color: theme.status.error, "aria-label": "Error:", bold: true, children: TOOL_STATUS.ERROR })
  ] });
};
var ToolInfo = ({
  name,
  description,
  status: coreStatus,
  emphasis,
  progressMessage: _progressMessage,
  originalRequestName
}) => {
  const status = mapCoreStatusToDisplayStatus(coreStatus);
  const nameColor = import_react21.default.useMemo(() => {
    switch (emphasis) {
      case "high":
        return theme.text.primary;
      case "medium":
        return theme.text.primary;
      case "low":
        return theme.text.secondary;
      default: {
        const exhaustiveCheck = emphasis;
        return exhaustiveCheck;
      }
    }
  }, [emphasis]);
  const isCompletedAskUser = isCompletedAskUserTool(name, status);
  return /* @__PURE__ */ (0, import_jsx_runtime22.jsx)(Box_default, { overflow: "hidden", height: 1, flexGrow: 1, flexShrink: 1, children: /* @__PURE__ */ (0, import_jsx_runtime22.jsxs)(Text, { strikethrough: status === "Canceled" /* Canceled */, wrap: "truncate", children: [
    /* @__PURE__ */ (0, import_jsx_runtime22.jsx)(Text, { color: nameColor, bold: true, children: name }),
    originalRequestName && originalRequestName !== name && /* @__PURE__ */ (0, import_jsx_runtime22.jsxs)(Text, { color: theme.text.secondary, italic: true, children: [
      " ",
      "(redirection from ",
      originalRequestName,
      ")"
    ] }),
    !isCompletedAskUser && /* @__PURE__ */ (0, import_jsx_runtime22.jsxs)(import_jsx_runtime22.Fragment, { children: [
      " ",
      /* @__PURE__ */ (0, import_jsx_runtime22.jsx)(Text, { color: theme.text.secondary, children: description })
    ] })
  ] }) });
};
var McpProgressIndicator = ({
  progress,
  total,
  message,
  barWidth
}) => {
  const percentage = total && total > 0 ? Math.min(100, Math.round(progress / total * 100)) : null;
  let rawFilled;
  if (total && total > 0) {
    rawFilled = Math.round(progress / total * barWidth);
  } else {
    rawFilled = Math.floor(progress) % (barWidth + 1);
  }
  const filled = Math.max(
    0,
    Math.min(Number.isFinite(rawFilled) ? rawFilled : 0, barWidth)
  );
  const empty = Math.max(0, barWidth - filled);
  const progressBar = "\u2588".repeat(filled) + "\u2591".repeat(empty);
  return /* @__PURE__ */ (0, import_jsx_runtime22.jsxs)(Box_default, { flexDirection: "column", children: [
    /* @__PURE__ */ (0, import_jsx_runtime22.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime22.jsxs)(Text, { color: theme.text.accent, children: [
      progressBar,
      " ",
      percentage !== null ? `${percentage}%` : `${progress}`
    ] }) }),
    message && /* @__PURE__ */ (0, import_jsx_runtime22.jsx)(Text, { color: theme.text.secondary, wrap: "truncate", children: message })
  ] });
};
var TrailingIndicator = () => /* @__PURE__ */ (0, import_jsx_runtime22.jsxs)(Text, { color: theme.text.primary, wrap: "truncate", children: [
  " ",
  "\u2190"
] });

// packages/cli/src/ui/components/messages/SubagentProgressDisplay.tsx
var import_jsx_runtime23 = __toESM(require_jsx_runtime(), 1);
var formatToolArgs = (args) => {
  if (!args) return "";
  try {
    const parsed = JSON.parse(args);
    if (typeof parsed !== "object" || parsed === null) {
      return args;
    }
    if ("description" in parsed && typeof parsed.description === "string" && parsed.description) {
      return parsed.description;
    }
    if ("command" in parsed && typeof parsed.command === "string")
      return parsed.command;
    if ("file_path" in parsed && typeof parsed.file_path === "string")
      return parsed.file_path;
    if ("dir_path" in parsed && typeof parsed.dir_path === "string")
      return parsed.dir_path;
    if ("query" in parsed && typeof parsed.query === "string")
      return parsed.query;
    if ("url" in parsed && typeof parsed.url === "string") return parsed.url;
    if ("target" in parsed && typeof parsed.target === "string")
      return parsed.target;
    return args;
  } catch {
    return args;
  }
};
var SubagentProgressDisplay = ({ progress, terminalWidth, historyOverrides }) => {
  let headerText;
  let headerColor = theme.text.secondary;
  if (progress.state === "cancelled") {
    headerText = `Subagent ${progress.agentName} was cancelled.`;
    headerColor = theme.status.warning;
  } else if (progress.state === "error") {
    headerText = `Subagent ${progress.agentName} failed.`;
    headerColor = theme.status.error;
  } else if (progress.state === "completed") {
    headerText = `Subagent ${progress.agentName} completed.`;
    headerColor = theme.status.success;
  } else {
    headerText = `Running subagent ${progress.agentName}...`;
    headerColor = theme.text.primary;
  }
  return /* @__PURE__ */ (0, import_jsx_runtime23.jsxs)(Box_default, { flexDirection: "column", paddingY: 0, children: [
    headerText && /* @__PURE__ */ (0, import_jsx_runtime23.jsx)(Box_default, { marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime23.jsx)(Text, { color: headerColor, italic: true, children: headerText }) }),
    /* @__PURE__ */ (0, import_jsx_runtime23.jsx)(Box_default, { flexDirection: "column", marginLeft: 0, gap: 0, children: (historyOverrides ?? progress.recentActivity).map(
      (item) => {
        if (item.type === "thought") {
          const isCancellation = item.content === "Request cancelled.";
          const icon = isCancellation ? "\u2139 " : "\u{1F4AD}";
          const color = isCancellation ? theme.status.warning : theme.text.secondary;
          return /* @__PURE__ */ (0, import_jsx_runtime23.jsxs)(Box_default, { flexDirection: "row", children: [
            /* @__PURE__ */ (0, import_jsx_runtime23.jsx)(Box_default, { minWidth: STATUS_INDICATOR_WIDTH, children: /* @__PURE__ */ (0, import_jsx_runtime23.jsx)(Text, { color, children: icon }) }),
            /* @__PURE__ */ (0, import_jsx_runtime23.jsx)(Box_default, { flexGrow: 1, children: /* @__PURE__ */ (0, import_jsx_runtime23.jsx)(Text, { color, children: item.content }) })
          ] }, item.id);
        } else if (item.type === "tool_call") {
          const statusSymbol = item.status === "running" ? /* @__PURE__ */ (0, import_jsx_runtime23.jsx)(build_default, { type: "dots" }) : item.status === "completed" ? /* @__PURE__ */ (0, import_jsx_runtime23.jsx)(Text, { color: theme.status.success, children: TOOL_STATUS.SUCCESS }) : item.status === "cancelled" ? /* @__PURE__ */ (0, import_jsx_runtime23.jsx)(Text, { color: theme.status.warning, bold: true, children: TOOL_STATUS.CANCELED }) : /* @__PURE__ */ (0, import_jsx_runtime23.jsx)(Text, { color: theme.status.error, children: TOOL_STATUS.ERROR });
          const formattedArgs = item.description || formatToolArgs(item.args);
          const displayArgs = formattedArgs.length > 60 ? formattedArgs.slice(0, 60) + "..." : formattedArgs;
          return /* @__PURE__ */ (0, import_jsx_runtime23.jsxs)(Box_default, { flexDirection: "row", children: [
            /* @__PURE__ */ (0, import_jsx_runtime23.jsx)(Box_default, { minWidth: STATUS_INDICATOR_WIDTH, children: statusSymbol }),
            /* @__PURE__ */ (0, import_jsx_runtime23.jsxs)(Box_default, { flexDirection: "row", flexGrow: 1, flexWrap: "wrap", children: [
              /* @__PURE__ */ (0, import_jsx_runtime23.jsx)(
                Text,
                {
                  bold: true,
                  color: theme.text.primary,
                  strikethrough: item.status === "cancelled",
                  children: item.displayName || item.content
                }
              ),
              displayArgs && /* @__PURE__ */ (0, import_jsx_runtime23.jsx)(Box_default, { marginLeft: 1, children: /* @__PURE__ */ (0, import_jsx_runtime23.jsx)(
                Text,
                {
                  color: theme.text.secondary,
                  wrap: "truncate",
                  strikethrough: item.status === "cancelled",
                  children: displayArgs
                }
              ) })
            ] })
          ] }, item.id);
        }
        return null;
      }
    ) }),
    progress.result && /* @__PURE__ */ (0, import_jsx_runtime23.jsxs)(Box_default, { flexDirection: "column", marginTop: 1, children: [
      progress.terminateReason && progress.terminateReason !== "GOAL" && /* @__PURE__ */ (0, import_jsx_runtime23.jsx)(Box_default, { marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime23.jsxs)(Text, { color: theme.status.warning, bold: true, children: [
        "Agent Finished Early (",
        progress.terminateReason,
        ")"
      ] }) }),
      /* @__PURE__ */ (0, import_jsx_runtime23.jsx)(
        MarkdownDisplay,
        {
          text: safeJsonToMarkdown(progress.result),
          isPending: progress.state !== "completed",
          terminalWidth
        }
      )
    ] })
  ] });
};

// packages/cli/src/ui/components/messages/ToolResultDisplay.tsx
var import_jsx_runtime24 = __toESM(require_jsx_runtime(), 1);
var ToolResultDisplay = ({
  resultDisplay,
  availableTerminalHeight,
  terminalWidth,
  renderOutputAsMarkdown = true,
  maxLines,
  hasFocus = false,
  overflowDirection = "top"
}) => {
  const { renderMarkdown, constrainHeight } = useUIState();
  const isAlternateBuffer = useAlternateBuffer();
  const availableHeight = calculateToolContentMaxLines({
    availableTerminalHeight,
    isAlternateBuffer,
    maxLinesLimit: maxLines
  });
  const combinedPaddingAndBorderWidth = 4;
  const childWidth = terminalWidth - combinedPaddingAndBorderWidth;
  const keyExtractor = import_react22.default.useCallback(
    (_, index) => index.toString(),
    []
  );
  const renderVirtualizedAnsiLine = import_react22.default.useCallback(
    ({ item }) => /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(Box_default, { height: 1, overflow: "hidden", children: /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(AnsiLineText, { line: item }) }),
    []
  );
  if (!resultDisplay) return null;
  if (typeof resultDisplay === "object" && "todos" in resultDisplay) {
    return null;
  }
  const renderContent = (contentData) => {
    const prettyJSON = typeof contentData === "string" ? tryParseJSON(contentData) : null;
    const formattedJSON = prettyJSON ? JSON.stringify(prettyJSON, null, 2) : null;
    let content;
    if (formattedJSON) {
      content = /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(Text, { wrap: "wrap", color: theme.text.primary, children: formattedJSON });
    } else if (isSubagentProgress(contentData)) {
      content = /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(
        SubagentProgressDisplay,
        {
          progress: contentData,
          terminalWidth: childWidth
        }
      );
    } else if (typeof contentData === "string" && renderOutputAsMarkdown) {
      content = /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(
        MarkdownDisplay,
        {
          text: contentData,
          terminalWidth: childWidth,
          renderMarkdown,
          isPending: false
        }
      );
    } else if (typeof contentData === "string" && !renderOutputAsMarkdown) {
      content = /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(Text, { wrap: "wrap", color: theme.text.primary, children: contentData });
    } else if (isStructuredToolResult(contentData)) {
      if (renderOutputAsMarkdown) {
        content = /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(
          MarkdownDisplay,
          {
            text: contentData.summary,
            terminalWidth: childWidth,
            renderMarkdown,
            isPending: false
          }
        );
      } else {
        content = /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(Text, { wrap: "wrap", color: theme.text.primary, children: contentData.summary });
      }
    } else if (typeof contentData === "object" && contentData !== null && "fileDiff" in contentData) {
      content = /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(
        DiffRenderer,
        {
          diffContent: (
            // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
            contentData.fileDiff
          ),
          filename: contentData.fileName,
          availableTerminalHeight: availableHeight,
          terminalWidth: childWidth
        }
      );
    } else if (Array.isArray(contentData)) {
      const shouldDisableTruncation = isAlternateBuffer || availableTerminalHeight === void 0 && maxLines === void 0;
      content = /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(
        AnsiOutputText,
        {
          data: contentData,
          availableTerminalHeight: isAlternateBuffer ? void 0 : availableHeight,
          width: childWidth,
          maxLines: isAlternateBuffer ? void 0 : maxLines,
          disableTruncation: shouldDisableTruncation
        }
      );
    } else if (typeof contentData === "object" && contentData !== null) {
      content = /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(Text, { wrap: "wrap", color: theme.text.primary, children: JSON.stringify(contentData, null, 2) });
    } else {
      content = null;
    }
    if (isAlternateBuffer) {
      const effectiveMaxHeight = maxLines ?? availableHeight;
      return /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(
        Scrollable,
        {
          width: childWidth,
          maxHeight: effectiveMaxHeight,
          hasFocus,
          scrollToBottom: true,
          reportOverflow: true,
          children: content
        }
      );
    }
    return content;
  };
  if (Array.isArray(resultDisplay)) {
    const limit = maxLines ?? availableHeight ?? ACTIVE_SHELL_MAX_LINES;
    const data = resultDisplay;
    const listHeight = !constrainHeight ? data.length : Math.min(data.length, limit);
    if (isAlternateBuffer) {
      const initialScrollIndex = overflowDirection === "bottom" ? 0 : SCROLL_TO_ITEM_END;
      return /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(Box_default, { width: childWidth, flexDirection: "column", maxHeight: listHeight, children: /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(
        ScrollableListWithForwardRef,
        {
          width: childWidth,
          containerHeight: listHeight,
          data,
          renderItem: renderVirtualizedAnsiLine,
          estimatedItemHeight: () => 1,
          fixedItemHeight: true,
          keyExtractor,
          initialScrollIndex,
          hasFocus
        }
      ) });
    } else {
      let displayData = data;
      let hiddenLines = 0;
      if (constrainHeight && data.length > listHeight) {
        hiddenLines = data.length - listHeight;
        if (overflowDirection === "top") {
          displayData = data.slice(hiddenLines);
        } else {
          displayData = data.slice(0, listHeight);
        }
      }
      return /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(Box_default, { width: childWidth, flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(
        MaxSizedBox,
        {
          maxHeight: constrainHeight ? listHeight : void 0,
          maxWidth: childWidth,
          overflowDirection,
          additionalHiddenLinesCount: hiddenLines,
          children: displayData.map((item, index) => {
            const actualIndex = (overflowDirection === "top" ? hiddenLines : 0) + index;
            return /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(
              Box_default,
              {
                height: 1,
                overflow: "hidden",
                children: /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(AnsiLineText, { line: item })
              },
              keyExtractor(item, actualIndex)
            );
          })
        }
      ) });
    }
  }
  if (isAlternateBuffer) {
    return /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(Box_default, { width: childWidth, flexDirection: "column", children: renderContent(resultDisplay) });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(Box_default, { width: childWidth, flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(
    SlicingMaxSizedBox,
    {
      data: resultDisplay,
      maxLines,
      isAlternateBuffer,
      maxHeight: availableHeight,
      maxWidth: childWidth,
      overflowDirection,
      children: (truncatedResultDisplay) => renderContent(truncatedResultDisplay)
    }
  ) });
};

// packages/cli/src/ui/components/ShellInputPrompt.tsx
var import_react23 = __toESM(require_react(), 1);

// packages/cli/src/ui/key/keyToAnsi.ts
var SPECIAL_KEYS = {
  up: "\x1B[A",
  down: "\x1B[B",
  right: "\x1B[C",
  left: "\x1B[D",
  escape: "\x1B",
  tab: "	",
  backspace: "\x7F",
  delete: "\x1B[3~",
  home: "\x1B[H",
  end: "\x1B[F",
  pageup: "\x1B[5~",
  pagedown: "\x1B[6~",
  enter: "\r"
};
function keyToAnsi(key) {
  if (key.ctrl) {
    if (key.name >= "a" && key.name <= "z") {
      return String.fromCharCode(
        key.name.charCodeAt(0) - "a".charCodeAt(0) + 1
      );
    }
  }
  if (key.name in SPECIAL_KEYS) {
    return SPECIAL_KEYS[key.name];
  }
  if (!key.ctrl && !key.cmd && key.sequence) {
    return key.sequence;
  }
  return null;
}

// packages/cli/src/ui/components/ShellInputPrompt.tsx
var ShellInputPrompt = ({
  activeShellPtyId,
  focus = true,
  scrollPageSize = ACTIVE_SHELL_MAX_LINES
}) => {
  const keyMatchers = useKeyMatchers();
  const handleShellInputSubmit = (0, import_react23.useCallback)(
    (input) => {
      if (activeShellPtyId) {
        ShellExecutionService.writeToPty(activeShellPtyId, input);
      }
    },
    [activeShellPtyId]
  );
  const handleInput = (0, import_react23.useCallback)(
    (key) => {
      if (!focus || !activeShellPtyId) {
        return false;
      }
      if (keyMatchers["background.toggle" /* TOGGLE_BACKGROUND_SHELL */](key)) {
        return false;
      }
      if (keyMatchers["app.unfocusShellInput" /* UNFOCUS_SHELL_INPUT */](key)) {
        return false;
      }
      if (keyMatchers["scroll.up" /* SCROLL_UP */](key)) {
        ShellExecutionService.scrollPty(activeShellPtyId, -1);
        return true;
      }
      if (keyMatchers["scroll.down" /* SCROLL_DOWN */](key)) {
        ShellExecutionService.scrollPty(activeShellPtyId, 1);
        return true;
      }
      if (keyMatchers["scroll.pageUp" /* PAGE_UP */](key)) {
        ShellExecutionService.scrollPty(activeShellPtyId, -scrollPageSize);
        return true;
      }
      if (keyMatchers["scroll.pageDown" /* PAGE_DOWN */](key)) {
        ShellExecutionService.scrollPty(activeShellPtyId, scrollPageSize);
        return true;
      }
      const ansiSequence = keyToAnsi(key);
      if (ansiSequence) {
        handleShellInputSubmit(ansiSequence);
        return true;
      }
      return false;
    },
    [
      focus,
      handleShellInputSubmit,
      activeShellPtyId,
      scrollPageSize,
      keyMatchers
    ]
  );
  useKeypress(handleInput, { isActive: focus });
  return null;
};

// packages/cli/src/ui/components/messages/ToolMessage.tsx
var import_jsx_runtime25 = (
  // It is crucial we don't replace this <> with a Box because otherwise the
  // sticky header inside it would be sticky to that box rather than to the
  // parent component of this ToolMessage.
  __toESM(require_jsx_runtime(), 1)
);
var ToolMessage = ({
  name,
  description,
  resultDisplay,
  status,
  kind,
  availableTerminalHeight,
  terminalWidth,
  emphasis = "medium",
  renderOutputAsMarkdown = true,
  isFirst,
  borderColor,
  borderDimColor,
  activeShellPtyId,
  embeddedShellFocused,
  ptyId,
  config,
  progressMessage,
  originalRequestName,
  progress,
  progressTotal
}) => {
  const isThisShellFocused2 = isThisShellFocused(
    name,
    status,
    ptyId,
    activeShellPtyId,
    embeddedShellFocused
  );
  const isThisShellFocusable2 = isThisShellFocusable(name, status, config);
  const { shouldShowFocusHint } = useFocusHint(
    isThisShellFocusable2,
    isThisShellFocused2,
    resultDisplay
  );
  return /* @__PURE__ */ (0, import_jsx_runtime25.jsxs)(import_jsx_runtime25.Fragment, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime25.jsxs)(
      StickyHeader,
      {
        width: terminalWidth,
        isFirst,
        borderColor,
        borderDimColor,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(
            ToolStatusIndicator,
            {
              status,
              name,
              isFocused: isThisShellFocused2
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(
            ToolInfo,
            {
              name,
              status,
              description,
              emphasis,
              progressMessage,
              originalRequestName
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(
            FocusHint,
            {
              shouldShowFocusHint,
              isThisShellFocused: isThisShellFocused2
            }
          ),
          emphasis === "high" && /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(TrailingIndicator, {})
        ]
      }
    ),
    /* @__PURE__ */ (0, import_jsx_runtime25.jsxs)(
      Box_default,
      {
        width: terminalWidth,
        borderStyle: "round",
        borderColor,
        borderDimColor,
        borderTop: false,
        borderBottom: false,
        borderLeft: true,
        borderRight: true,
        paddingX: 1,
        flexDirection: "column",
        children: [
          status === CoreToolCallStatus.Executing && progress !== void 0 && /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(
            McpProgressIndicator,
            {
              progress,
              total: progressTotal,
              message: progressMessage,
              barWidth: 20
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(
            ToolResultDisplay,
            {
              resultDisplay,
              availableTerminalHeight,
              terminalWidth,
              renderOutputAsMarkdown,
              hasFocus: isThisShellFocused2,
              maxLines: kind === Kind.Agent && availableTerminalHeight !== void 0 ? SUBAGENT_MAX_LINES : void 0,
              overflowDirection: kind === Kind.Agent ? "bottom" : "top"
            }
          ),
          isThisShellFocused2 && config && /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(Box_default, { paddingLeft: STATUS_INDICATOR_WIDTH, marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(
            ShellInputPrompt,
            {
              activeShellPtyId: activeShellPtyId ?? null,
              focus: embeddedShellFocused
            }
          ) })
        ]
      }
    )
  ] });
};

// packages/cli/src/ui/components/messages/ShellToolMessage.tsx
var import_react29 = __toESM(require_react(), 1);

// packages/cli/src/ui/contexts/UIActionsContext.tsx
var import_react27 = __toESM(require_react(), 1);

// packages/cli/src/ui/IdeIntegrationNudge.tsx
var import_jsx_runtime26 = __toESM(require_jsx_runtime(), 1);
function IdeIntegrationNudge({
  ide,
  onComplete
}) {
  useKeypress(
    (key) => {
      if (key.name === "escape") {
        onComplete({
          userSelection: "no",
          isExtensionPreInstalled: false
        });
        return true;
      }
      return false;
    },
    { isActive: true }
  );
  const { displayName: ideName } = ide;
  const isExtensionPreInstalled = !!process.env["GEMINI_CLI_IDE_SERVER_PORT"] && !!process.env["GEMINI_CLI_IDE_WORKSPACE_PATH"];
  const OPTIONS = [
    {
      label: "Yes",
      value: {
        userSelection: "yes",
        isExtensionPreInstalled
      },
      key: "Yes"
    },
    {
      label: "No (esc)",
      value: {
        userSelection: "no",
        isExtensionPreInstalled
      },
      key: "No (esc)"
    },
    {
      label: "No, don't ask again",
      value: {
        userSelection: "dismiss",
        isExtensionPreInstalled
      },
      key: "No, don't ask again"
    }
  ];
  const installText = isExtensionPreInstalled ? `If you select Yes, the CLI will have access to your open files and display diffs directly in ${ideName ?? "your editor"}.` : `If you select Yes, we'll install an extension that allows the CLI to access your open files and display diffs directly in ${ideName ?? "your editor"}.`;
  return /* @__PURE__ */ (0, import_jsx_runtime26.jsxs)(
    Box_default,
    {
      flexDirection: "column",
      borderStyle: "round",
      borderColor: theme.status.warning,
      padding: 1,
      width: "100%",
      marginLeft: 1,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime26.jsxs)(Box_default, { marginBottom: 1, flexDirection: "column", children: [
          /* @__PURE__ */ (0, import_jsx_runtime26.jsxs)(Text, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(Text, { color: theme.status.warning, children: "> " }),
            `Do you want to connect ${ideName ?? "your editor"} to Gemini CLI?`
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(Text, { color: theme.text.secondary, children: installText })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(RadioButtonSelect, { items: OPTIONS, onSelect: onComplete })
      ]
    }
  );
}

// packages/cli/src/ui/components/FolderTrustDialog.tsx
var import_react24 = __toESM(require_react(), 1);
import * as process4 from "node:process";
import * as path2 from "node:path";

// packages/cli/src/ui/components/ShowMoreLines.tsx
var import_jsx_runtime27 = __toESM(require_jsx_runtime(), 1);
var ShowMoreLines = ({
  constrainHeight,
  isOverflowing: isOverflowingProp
}) => {
  const overflowState = useOverflowState();
  const streamingState = useStreamingContext();
  const isOverflowing = isOverflowingProp ?? (overflowState !== void 0 && overflowState.overflowingIds.size > 0);
  if (!isOverflowing || !constrainHeight || !(streamingState === "idle" /* Idle */ || streamingState === "waiting_for_confirmation" /* WaitingForConfirmation */ || streamingState === "responding" /* Responding */)) {
    return null;
  }
  return /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(Box_default, { paddingX: 1, marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(Text, { color: theme.text.accent, wrap: "truncate", children: "Press Ctrl+O to show more lines" }) });
};

// packages/cli/src/ui/components/FolderTrustDialog.tsx
var import_jsx_runtime28 = __toESM(require_jsx_runtime(), 1);
var FolderTrustDialog = ({
  onSelect,
  isRestarting,
  discoveryResults
}) => {
  const [exiting, setExiting] = (0, import_react24.useState)(false);
  const { terminalHeight, terminalWidth, constrainHeight } = useUIState();
  const isAlternateBuffer = useAlternateBuffer();
  const isExpanded = !constrainHeight;
  (0, import_react24.useEffect)(() => {
    let timer;
    if (isRestarting) {
      timer = setTimeout(relaunchApp, 250);
    }
    return () => {
      if (timer) clearTimeout(timer);
    };
  }, [isRestarting]);
  const handleExit = (0, import_react24.useCallback)(() => {
    setExiting(true);
    setTimeout(async () => {
      await runExitCleanup();
      process4.exit(ExitCodes.FATAL_CANCELLATION_ERROR);
    }, 100);
  }, []);
  useKeypress(
    (key) => {
      if (key.name === "escape") {
        handleExit();
        return true;
      }
      return false;
    },
    { isActive: !isRestarting }
  );
  const dirName = path2.basename(process4.cwd());
  const parentFolder = path2.basename(path2.dirname(process4.cwd()));
  const options = [
    {
      label: `Trust folder (${dirName})`,
      value: "trust_folder" /* TRUST_FOLDER */,
      key: `Trust folder (${dirName})`
    },
    {
      label: `Trust parent folder (${parentFolder})`,
      value: "trust_parent" /* TRUST_PARENT */,
      key: `Trust parent folder (${parentFolder})`
    },
    {
      label: "Don't trust",
      value: "do_not_trust" /* DO_NOT_TRUST */,
      key: "Don't trust"
    }
  ];
  const hasDiscovery = discoveryResults && (discoveryResults.commands.length > 0 || discoveryResults.mcps.length > 0 || discoveryResults.hooks.length > 0 || discoveryResults.skills.length > 0 || discoveryResults.settings.length > 0);
  const hasWarnings = discoveryResults && discoveryResults.securityWarnings.length > 0;
  const hasErrors = discoveryResults && discoveryResults.discoveryErrors && discoveryResults.discoveryErrors.length > 0;
  const dialogWidth = terminalWidth - 2;
  const borderColor = theme.status.warning;
  const overhead = 3 + options.length + 2 + 1 + 2;
  const scrollableHeight = Math.max(4, terminalHeight - overhead);
  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);
  const discoveryContent = /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(Box_default, { flexDirection: "column", children: [
    /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Box_default, { marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Text, { color: theme.text.primary, children: "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." }) }),
    hasErrors && /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(Box_default, { flexDirection: "column", marginBottom: 1, children: [
      /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Text, { color: theme.status.error, bold: true, children: "\u274C Discovery Errors:" }),
      discoveryResults.discoveryErrors.map((error, i) => /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Box_default, { marginLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(Text, { color: theme.status.error, children: [
        "\u2022 ",
        stripAnsi(error)
      ] }) }, i))
    ] }),
    hasWarnings && /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(Box_default, { flexDirection: "column", marginBottom: 1, children: [
      /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Text, { color: theme.status.warning, bold: true, children: "\u26A0\uFE0F Security Warnings:" }),
      discoveryResults.securityWarnings.map((warning, i) => /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Box_default, { marginLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(Text, { color: theme.status.warning, children: [
        "\u2022 ",
        stripAnsi(warning)
      ] }) }, i))
    ] }),
    hasDiscovery && /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(Box_default, { flexDirection: "column", marginBottom: 1, children: [
      /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Text, { color: theme.text.primary, bold: true, children: "This folder contains:" }),
      groups.map((group) => /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(Box_default, { flexDirection: "column", marginLeft: 2, children: [
        /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(Text, { color: theme.text.primary, bold: true, children: [
          "\u2022 ",
          group.label,
          " (",
          group.items.length,
          "):"
        ] }),
        group.items.map((item, idx) => /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Box_default, { marginLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(Text, { color: theme.text.primary, children: [
          "- ",
          stripAnsi(item)
        ] }) }, idx))
      ] }, group.label))
    ] })
  ] });
  const title = /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Text, { bold: true, color: theme.text.primary, children: "Do you trust the files in this folder?" });
  const selectOptions = /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(
    RadioButtonSelect,
    {
      items: options,
      onSelect,
      isFocused: !isRestarting
    }
  );
  const renderContent = () => {
    if (isAlternateBuffer) {
      return /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(Box_default, { flexDirection: "column", width: dialogWidth, children: [
        /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(
          StickyHeader,
          {
            width: dialogWidth,
            isFirst: true,
            borderColor,
            borderDimColor: false,
            children: title
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(
          Box_default,
          {
            flexDirection: "column",
            borderLeft: true,
            borderRight: true,
            borderColor,
            borderStyle: "round",
            borderTop: false,
            borderBottom: false,
            width: dialogWidth,
            children: [
              /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(
                Scrollable,
                {
                  hasFocus: !isRestarting,
                  height: scrollableHeight,
                  width: dialogWidth - 2,
                  children: /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Box_default, { flexDirection: "column", paddingX: 1, children: discoveryContent })
                }
              ),
              /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Box_default, { paddingX: 1, marginY: 1, children: selectOptions })
            ]
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(
          Box_default,
          {
            height: 0,
            width: dialogWidth,
            borderLeft: true,
            borderRight: true,
            borderTop: false,
            borderBottom: true,
            borderColor,
            borderStyle: "round"
          }
        )
      ] });
    }
    return /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(
      Box_default,
      {
        flexDirection: "column",
        borderStyle: "round",
        borderColor,
        padding: 1,
        width: "100%",
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Box_default, { marginBottom: 1, children: title }),
          /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(
            MaxSizedBox,
            {
              maxHeight: isExpanded ? void 0 : Math.max(4, terminalHeight - 12),
              overflowDirection: "bottom",
              children: discoveryContent
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Box_default, { marginTop: 1, children: selectOptions })
        ]
      }
    );
  };
  const content = /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(Box_default, { flexDirection: "column", width: "100%", children: [
    /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Box_default, { flexDirection: "column", marginLeft: 1, marginRight: 1, children: renderContent() }),
    /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Box_default, { paddingX: 2, marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(ShowMoreLines, { constrainHeight }) }),
    isRestarting && /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Box_default, { marginLeft: 1, marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Text, { color: theme.status.warning, children: "Gemini CLI is restarting to apply the trust changes..." }) }),
    exiting && /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Box_default, { marginLeft: 1, marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Text, { color: theme.status.warning, children: "A folder trust level must be selected to continue. Exiting since escape was pressed." }) })
  ] });
  return /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(OverflowProvider, { children: content });
};

// packages/cli/src/ui/components/PermissionsModifyTrustDialog.tsx
import * as process6 from "node:process";
import * as path4 from "node:path";

// packages/cli/src/ui/hooks/usePermissionsModifyTrust.ts
var import_react25 = __toESM(require_react(), 1);
import * as process5 from "node:process";
import * as path3 from "node:path";
function getInitialTrustState(settings, cwd5, isCurrentWorkspace) {
  const folders = loadTrustedFolders();
  const explicitTrustLevel = folders.user.config[cwd5];
  if (!isCurrentWorkspace) {
    return {
      currentTrustLevel: explicitTrustLevel,
      isInheritedTrustFromParent: false,
      isInheritedTrustFromIde: false
    };
  }
  const { isTrusted, source: source2 } = isWorkspaceTrusted(
    settings.merged,
    process5.cwd()
  );
  const isInheritedTrust = isTrusted && (!explicitTrustLevel || explicitTrustLevel === "DO_NOT_TRUST" /* DO_NOT_TRUST */);
  return {
    currentTrustLevel: explicitTrustLevel,
    isInheritedTrustFromParent: !!(source2 === "file" && isInheritedTrust),
    isInheritedTrustFromIde: !!(source2 === "ide" && isInheritedTrust)
  };
}
var usePermissionsModifyTrust = (onExit, addItem, targetDirectory) => {
  const settings = useSettings();
  const cwd5 = targetDirectory;
  const isCurrentWorkspace = path3.resolve(targetDirectory).toLowerCase() === path3.resolve(process5.cwd()).toLowerCase();
  const [initialState5] = (0, import_react25.useState)(
    () => getInitialTrustState(settings, cwd5, isCurrentWorkspace)
  );
  const [currentTrustLevel] = (0, import_react25.useState)(
    initialState5.currentTrustLevel
  );
  const [pendingTrustLevel, setPendingTrustLevel] = (0, import_react25.useState)();
  const [isInheritedTrustFromParent] = (0, import_react25.useState)(
    initialState5.isInheritedTrustFromParent
  );
  const [isInheritedTrustFromIde] = (0, import_react25.useState)(
    initialState5.isInheritedTrustFromIde
  );
  const [needsRestart, setNeedsRestart] = (0, import_react25.useState)(false);
  const isFolderTrustEnabled = settings.merged.security.folderTrust.enabled ?? true;
  const updateTrustLevel = (0, import_react25.useCallback)(
    async (trustLevel) => {
      if (!isCurrentWorkspace) {
        const folders = loadTrustedFolders();
        await folders.setValue(cwd5, trustLevel);
        onExit();
        return;
      }
      const wasTrusted = isWorkspaceTrusted(
        settings.merged,
        process5.cwd()
      ).isTrusted;
      const currentConfig = loadTrustedFolders().user.config;
      const newConfig = { ...currentConfig, [cwd5]: trustLevel };
      const { isTrusted, source: source2 } = isWorkspaceTrusted(
        settings.merged,
        process5.cwd(),
        newConfig
      );
      if (trustLevel === "DO_NOT_TRUST" /* DO_NOT_TRUST */ && isTrusted) {
        let message = "Note: This folder is still trusted because the connected IDE workspace is trusted.";
        if (source2 === "file") {
          message = "Note: This folder is still trusted because a parent folder is trusted.";
        }
        addItem(
          {
            type: "warning" /* WARNING */,
            text: message
          },
          Date.now()
        );
      }
      if (wasTrusted !== isTrusted) {
        setPendingTrustLevel(trustLevel);
        setNeedsRestart(true);
      } else {
        const folders = loadTrustedFolders();
        try {
          await folders.setValue(cwd5, trustLevel);
        } catch {
          coreEvents.emitFeedback(
            "error",
            "Failed to save trust settings. Your changes may not persist."
          );
        }
        onExit();
      }
    },
    [cwd5, settings.merged, onExit, addItem, isCurrentWorkspace]
  );
  const commitTrustLevelChange = (0, import_react25.useCallback)(async () => {
    if (pendingTrustLevel) {
      const folders = loadTrustedFolders();
      try {
        await folders.setValue(cwd5, pendingTrustLevel);
        return true;
      } catch {
        coreEvents.emitFeedback(
          "error",
          "Failed to save trust settings. Your changes may not persist."
        );
        setNeedsRestart(false);
        setPendingTrustLevel(void 0);
        return false;
      }
    }
    return true;
  }, [cwd5, pendingTrustLevel]);
  return {
    cwd: cwd5,
    currentTrustLevel,
    isInheritedTrustFromParent,
    isInheritedTrustFromIde,
    needsRestart,
    updateTrustLevel,
    commitTrustLevelChange,
    isFolderTrustEnabled
  };
};

// packages/cli/src/ui/components/PermissionsModifyTrustDialog.tsx
var import_jsx_runtime29 = __toESM(require_jsx_runtime(), 1);
function PermissionsModifyTrustDialog({
  onExit,
  addItem,
  targetDirectory
}) {
  const currentDirectory = targetDirectory ?? process6.cwd();
  const dirName = path4.basename(currentDirectory);
  const parentFolder = path4.basename(path4.dirname(currentDirectory));
  const TRUST_LEVEL_ITEMS = [
    {
      label: `Trust this folder (${dirName})`,
      value: "TRUST_FOLDER" /* TRUST_FOLDER */,
      key: "TRUST_FOLDER" /* TRUST_FOLDER */
    },
    {
      label: `Trust parent folder (${parentFolder})`,
      value: "TRUST_PARENT" /* TRUST_PARENT */,
      key: "TRUST_PARENT" /* TRUST_PARENT */
    },
    {
      label: "Don't trust",
      value: "DO_NOT_TRUST" /* DO_NOT_TRUST */,
      key: "DO_NOT_TRUST" /* DO_NOT_TRUST */
    }
  ];
  const {
    cwd: cwd5,
    currentTrustLevel,
    isInheritedTrustFromParent,
    isInheritedTrustFromIde,
    needsRestart,
    updateTrustLevel,
    commitTrustLevelChange
  } = usePermissionsModifyTrust(onExit, addItem, currentDirectory);
  useKeypress(
    (key) => {
      if (key.name === "escape") {
        onExit();
        return true;
      }
      if (needsRestart && key.name === "r") {
        void (async () => {
          const success = await commitTrustLevelChange();
          if (success) {
            void relaunchApp();
          } else {
            onExit();
          }
        })();
        return true;
      }
      return false;
    },
    { isActive: true }
  );
  const index = TRUST_LEVEL_ITEMS.findIndex(
    (item) => item.value === currentTrustLevel
  );
  const initialIndex = index === -1 ? 0 : index;
  return /* @__PURE__ */ (0, import_jsx_runtime29.jsxs)(import_jsx_runtime29.Fragment, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime29.jsxs)(
      Box_default,
      {
        borderStyle: "round",
        borderColor: theme.border.default,
        flexDirection: "column",
        padding: 1,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime29.jsxs)(Box_default, { flexDirection: "column", paddingBottom: 1, children: [
            /* @__PURE__ */ (0, import_jsx_runtime29.jsxs)(Text, { bold: true, children: [
              "> ",
              "Modify Trust Level"
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(Box_default, { marginTop: 1 }),
            /* @__PURE__ */ (0, import_jsx_runtime29.jsxs)(Text, { children: [
              "Folder: ",
              cwd5
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime29.jsxs)(Text, { children: [
              "Current Level: ",
              /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(Text, { bold: true, children: currentTrustLevel || "Not Set" })
            ] }),
            isInheritedTrustFromParent && /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(Text, { color: theme.text.secondary, children: "Note: This folder behaves as a trusted folder because one of the parent folders is trusted. It will remain trusted even if you set a different trust level here. To change this, you need to modify the trust setting in the parent folder." }),
            isInheritedTrustFromIde && /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(Text, { color: theme.text.secondary, children: "Note: This folder behaves as a trusted folder because the connected IDE workspace is trusted. It will remain trusted even if you set a different trust level here." })
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(
            RadioButtonSelect,
            {
              items: TRUST_LEVEL_ITEMS,
              onSelect: updateTrustLevel,
              isFocused: true,
              initialIndex
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(Text, { color: theme.text.secondary, children: "(Use Enter to select, Esc to close)" }) })
        ]
      }
    ),
    needsRestart && /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(Box_default, { marginLeft: 1, marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(Text, { color: theme.status.warning, children: "To apply the trust changes, Gemini CLI must be restarted. Press 'r' to restart CLI now." }) })
  ] });
}

// packages/cli/src/ui/components/NewAgentsNotification.tsx
var import_react26 = __toESM(require_react(), 1);
var import_jsx_runtime30 = __toESM(require_jsx_runtime(), 1);
var NewAgentsNotification = ({
  agents,
  onSelect
}) => {
  const [isProcessing, setIsProcessing] = (0, import_react26.useState)(false);
  const options = [
    {
      label: "Acknowledge and Enable",
      value: "acknowledge" /* ACKNOWLEDGE */,
      key: "acknowledge"
    },
    {
      label: "Do not enable (Ask again next time)",
      value: "ignore" /* IGNORE */,
      key: "ignore"
    }
  ];
  const handleSelect = async (choice) => {
    setIsProcessing(true);
    try {
      await onSelect(choice);
    } finally {
      setIsProcessing(false);
    }
  };
  const MAX_DISPLAYED_AGENTS = 5;
  const displayAgents = agents.slice(0, MAX_DISPLAYED_AGENTS);
  const remaining = agents.length - MAX_DISPLAYED_AGENTS;
  return /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Box_default, { flexDirection: "column", width: "100%", children: /* @__PURE__ */ (0, import_jsx_runtime30.jsxs)(
    Box_default,
    {
      flexDirection: "column",
      borderStyle: "round",
      borderColor: theme.status.warning,
      padding: 1,
      marginLeft: 1,
      marginRight: 1,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime30.jsxs)(Box_default, { flexDirection: "column", marginBottom: 1, children: [
          /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Text, { bold: true, color: theme.text.primary, children: "New Agents Discovered" }),
          /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Text, { color: theme.text.primary, children: "The following agents were found in this project. Please review them:" }),
          /* @__PURE__ */ (0, import_jsx_runtime30.jsxs)(
            Box_default,
            {
              flexDirection: "column",
              marginTop: 1,
              borderStyle: "single",
              padding: 1,
              children: [
                displayAgents.map((agent) => {
                  const mcpServers = agent.kind === "local" ? agent.mcpServers : void 0;
                  const hasMcpServers = mcpServers && Object.keys(mcpServers).length > 0;
                  return /* @__PURE__ */ (0, import_jsx_runtime30.jsxs)(Box_default, { flexDirection: "column", children: [
                    /* @__PURE__ */ (0, import_jsx_runtime30.jsxs)(Box_default, { children: [
                      /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Box_default, { flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime30.jsxs)(Text, { bold: true, color: theme.text.primary, children: [
                        "- ",
                        agent.name,
                        ":",
                        " "
                      ] }) }),
                      /* @__PURE__ */ (0, import_jsx_runtime30.jsxs)(Text, { color: theme.text.secondary, children: [
                        " ",
                        agent.description
                      ] })
                    ] }),
                    hasMcpServers && /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Box_default, { marginLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime30.jsxs)(Text, { color: theme.text.secondary, children: [
                      "(Includes MCP servers:",
                      " ",
                      Object.keys(mcpServers).join(", "),
                      ")"
                    ] }) })
                  ] }, agent.name);
                }),
                remaining > 0 && /* @__PURE__ */ (0, import_jsx_runtime30.jsxs)(Text, { color: theme.text.secondary, children: [
                  "... and ",
                  remaining,
                  " more."
                ] })
              ]
            }
          )
        ] }),
        isProcessing ? /* @__PURE__ */ (0, import_jsx_runtime30.jsxs)(Box_default, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(CliSpinner, {}),
          /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Text, { color: theme.text.primary, children: " Processing..." })
        ] }) : /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(
          RadioButtonSelect,
          {
            items: options,
            onSelect: handleSelect,
            isFocused: true
          }
        )
      ]
    }
  ) });
};

// packages/cli/src/ui/contexts/UIActionsContext.tsx
var UIActionsContext = (0, import_react27.createContext)(null);
var useUIActions = () => {
  const context = (0, import_react27.useContext)(UIActionsContext);
  if (!context) {
    throw new Error("useUIActions must be used within a UIActionsProvider");
  }
  return context;
};

// packages/cli/src/ui/hooks/useMouseClick.ts
var import_react28 = __toESM(require_react(), 1);
var useMouseClick = (containerRef, handler, options = {}) => {
  const { isActive = true, button = "left", name } = options;
  const handlerRef = (0, import_react28.useRef)(handler);
  handlerRef.current = handler;
  const onMouse = (0, import_react28.useCallback)(
    (event) => {
      const eventName = name ?? (button === "left" ? "left-press" : "right-release");
      if (event.name === eventName && containerRef.current) {
        const { x, y, width, height } = getBoundingBox(containerRef.current);
        const mouseX = event.col - 1;
        const mouseY = event.row - 1;
        const relativeX = mouseX - x;
        const relativeY = mouseY - y;
        if (relativeX >= 0 && relativeX < width && relativeY >= 0 && relativeY < height) {
          handlerRef.current(event, relativeX, relativeY);
        }
      }
    },
    [containerRef, button, name]
  );
  useMouse(onMouse, { isActive });
};

// packages/cli/src/ui/components/messages/ShellToolMessage.tsx
var import_jsx_runtime31 = __toESM(require_jsx_runtime(), 1);
var ShellToolMessage = ({
  name,
  description,
  resultDisplay,
  status,
  availableTerminalHeight,
  terminalWidth,
  emphasis = "medium",
  renderOutputAsMarkdown = true,
  ptyId,
  config,
  isFirst,
  borderColor,
  borderDimColor,
  isExpandable,
  originalRequestName
}) => {
  const {
    activePtyId: activeShellPtyId,
    embeddedShellFocused,
    constrainHeight
  } = useUIState();
  const isAlternateBuffer = useAlternateBuffer();
  const isThisShellFocused2 = isThisShellFocused(
    name,
    status,
    ptyId,
    activeShellPtyId,
    embeddedShellFocused
  );
  const maxLines = calculateShellMaxLines({
    status,
    isAlternateBuffer,
    isThisShellFocused: isThisShellFocused2,
    availableTerminalHeight,
    constrainHeight,
    isExpandable
  });
  const availableHeight = calculateToolContentMaxLines({
    availableTerminalHeight,
    isAlternateBuffer,
    maxLinesLimit: maxLines
  });
  import_react29.default.useEffect(() => {
    const isExecuting = status === CoreToolCallStatus.Executing;
    if (isExecuting && ptyId) {
      try {
        const childWidth = terminalWidth - 4;
        const finalHeight = availableHeight ?? ACTIVE_SHELL_MAX_LINES - SHELL_CONTENT_OVERHEAD;
        ShellExecutionService.resizePty(
          ptyId,
          Math.max(1, childWidth),
          Math.max(1, finalHeight)
        );
      } catch (e) {
        if (!(e instanceof Error && e.message.includes("Cannot resize a pty that has already exited"))) {
          throw e;
        }
      }
    }
  }, [ptyId, status, terminalWidth, availableHeight]);
  const { setEmbeddedShellFocused } = useUIActions();
  const wasFocusedRef = import_react29.default.useRef(false);
  import_react29.default.useEffect(() => {
    if (isThisShellFocused2) {
      wasFocusedRef.current = true;
    } else if (wasFocusedRef.current) {
      if (embeddedShellFocused) {
        setEmbeddedShellFocused(false);
      }
      wasFocusedRef.current = false;
    }
  }, [isThisShellFocused2, embeddedShellFocused, setEmbeddedShellFocused]);
  const headerRef = import_react29.default.useRef(null);
  const contentRef = import_react29.default.useRef(null);
  const isThisShellFocusable2 = isThisShellFocusable(name, status, config);
  const handleFocus = () => {
    if (isThisShellFocusable2) {
      setEmbeddedShellFocused(true);
    }
  };
  useMouseClick(headerRef, handleFocus, { isActive: !!isThisShellFocusable2 });
  useMouseClick(contentRef, handleFocus, { isActive: !!isThisShellFocusable2 });
  const { shouldShowFocusHint } = useFocusHint(
    isThisShellFocusable2,
    isThisShellFocused2,
    resultDisplay
  );
  return /* @__PURE__ */ (0, import_jsx_runtime31.jsxs)(import_jsx_runtime31.Fragment, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime31.jsxs)(
      StickyHeader,
      {
        width: terminalWidth,
        isFirst,
        borderColor,
        borderDimColor,
        containerRef: headerRef,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(
            ToolStatusIndicator,
            {
              status,
              name,
              isFocused: isThisShellFocused2
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(
            ToolInfo,
            {
              name,
              status,
              description,
              emphasis,
              originalRequestName
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(
            FocusHint,
            {
              shouldShowFocusHint,
              isThisShellFocused: isThisShellFocused2
            }
          ),
          emphasis === "high" && /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(TrailingIndicator, {})
        ]
      }
    ),
    /* @__PURE__ */ (0, import_jsx_runtime31.jsxs)(
      Box_default,
      {
        ref: contentRef,
        width: terminalWidth,
        borderStyle: "round",
        borderColor,
        borderDimColor,
        borderTop: false,
        borderBottom: false,
        borderLeft: true,
        borderRight: true,
        paddingX: 1,
        flexDirection: "column",
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(
            ToolResultDisplay,
            {
              resultDisplay,
              availableTerminalHeight,
              terminalWidth,
              renderOutputAsMarkdown,
              hasFocus: isThisShellFocused2,
              maxLines
            }
          ),
          isThisShellFocused2 && config && /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(
            ShellInputPrompt,
            {
              activeShellPtyId: activeShellPtyId ?? null,
              focus: embeddedShellFocused,
              scrollPageSize: availableTerminalHeight ?? ACTIVE_SHELL_MAX_LINES
            }
          )
        ]
      }
    )
  ] });
};

// packages/cli/src/ui/components/messages/TopicMessage.tsx
var import_react31 = __toESM(require_react(), 1);

// packages/cli/src/ui/contexts/ToolActionsContext.tsx
var import_react30 = __toESM(require_react(), 1);
var import_jsx_runtime32 = __toESM(require_jsx_runtime(), 1);
function hasLegacyCallback(details) {
  return !!details && "onConfirm" in details && typeof details.onConfirm === "function";
}
var ToolActionsContext = (0, import_react30.createContext)(null);
var useToolActions = () => {
  const context = (0, import_react30.useContext)(ToolActionsContext);
  if (!context) {
    throw new Error("useToolActions must be used within a ToolActionsProvider");
  }
  return context;
};
var ToolActionsProvider = (props) => {
  const {
    children,
    config,
    toolCalls,
    isExpanded,
    toggleExpansion,
    toggleAllExpansion
  } = props;
  const [ideClient, setIdeClient] = (0, import_react30.useState)(null);
  const [isDiffingEnabled, setIsDiffingEnabled] = (0, import_react30.useState)(false);
  (0, import_react30.useEffect)(() => {
    let isMounted = true;
    let activeClient = null;
    const handleStatusChange = () => {
      if (isMounted && activeClient) {
        setIsDiffingEnabled(activeClient.isDiffingEnabled());
      }
    };
    if (config.getIdeMode()) {
      IdeClient.getInstance().then((client) => {
        if (!isMounted) return;
        activeClient = client;
        setIdeClient(client);
        setIsDiffingEnabled(client.isDiffingEnabled());
        client.addStatusChangeListener(handleStatusChange);
      }).catch((error) => {
        debugLogger.error("Failed to get IdeClient instance:", error);
      });
    }
    return () => {
      isMounted = false;
      if (activeClient) {
        activeClient.removeStatusChangeListener(handleStatusChange);
      }
    };
  }, [config]);
  const confirm = (0, import_react30.useCallback)(
    async (callId, outcome, payload) => {
      const tool = toolCalls.find((t) => t.callId === callId);
      if (!tool) {
        debugLogger.warn(`ToolActions: Tool ${callId} not found`);
        return;
      }
      const details = tool.confirmationDetails;
      if (details?.type === "edit" && isDiffingEnabled && "filePath" in details) {
        const cliOutcome = outcome === ToolConfirmationOutcome.Cancel ? "rejected" : "accepted";
        await ideClient?.resolveDiffFromCli(details.filePath, cliOutcome);
      }
      if (tool.correlationId) {
        await config.getMessageBus().publish({
          type: MessageBusType.TOOL_CONFIRMATION_RESPONSE,
          correlationId: tool.correlationId,
          confirmed: outcome !== ToolConfirmationOutcome.Cancel,
          requiresUserConfirmation: false,
          outcome,
          payload
        });
        return;
      }
      if (hasLegacyCallback(details)) {
        await details.onConfirm(outcome, payload);
        return;
      }
      debugLogger.warn(
        `ToolActions: No correlationId or callback for ${callId}`
      );
    },
    [config, ideClient, toolCalls, isDiffingEnabled]
  );
  const cancel = (0, import_react30.useCallback)(
    async (callId) => {
      await confirm(callId, ToolConfirmationOutcome.Cancel);
    },
    [confirm]
  );
  return /* @__PURE__ */ (0, import_jsx_runtime32.jsx)(
    ToolActionsContext.Provider,
    {
      value: {
        confirm,
        cancel,
        isDiffingEnabled,
        isExpanded,
        toggleExpansion,
        toggleAllExpansion
      },
      children
    }
  );
};

// packages/cli/src/ui/components/messages/TopicMessage.tsx
var import_jsx_runtime33 = __toESM(require_jsx_runtime(), 1);
var isTopicTool = (name) => name === UPDATE_TOPIC_TOOL_NAME || name === UPDATE_TOPIC_DISPLAY_NAME;
var TopicMessage = ({
  callId,
  args,
  availableTerminalHeight,
  isExpandable = true
}) => {
  const { isExpanded: isExpandedInContext, toggleExpansion } = useToolActions();
  const isExpanded = (isExpandedInContext ? isExpandedInContext(callId) : false) || availableTerminalHeight === void 0;
  const overflowActions = useOverflowActions();
  const uniqueId = (0, import_react31.useId)();
  const overflowId = `topic-${uniqueId}`;
  const containerRef = (0, import_react31.useRef)(null);
  const rawTitle = args?.[TOPIC_PARAM_TITLE];
  const title = typeof rawTitle === "string" ? rawTitle : void 0;
  const rawStrategicIntent = args?.[TOPIC_PARAM_STRATEGIC_INTENT];
  const strategicIntent = typeof rawStrategicIntent === "string" ? rawStrategicIntent : void 0;
  const rawSummary = args?.[TOPIC_PARAM_SUMMARY];
  const summary = typeof rawSummary === "string" ? rawSummary : void 0;
  const intent = strategicIntent || summary;
  const hasExtraSummary = !!(strategicIntent && summary && strategicIntent !== summary);
  const handleToggle = (0, import_react31.useCallback)(() => {
    if (toggleExpansion && hasExtraSummary) {
      toggleExpansion(callId);
    }
  }, [toggleExpansion, hasExtraSummary, callId]);
  useMouseClick(containerRef, handleToggle, {
    isActive: isExpandable && hasExtraSummary
  });
  (0, import_react31.useEffect)(() => {
    const hasHiddenContent = isExpandable && hasExtraSummary && !isExpanded;
    if (hasHiddenContent && overflowActions) {
      overflowActions.addOverflowingId(overflowId);
    } else if (overflowActions) {
      overflowActions.removeOverflowingId(overflowId);
    }
    return () => {
      overflowActions?.removeOverflowingId(overflowId);
    };
  }, [isExpandable, hasExtraSummary, isExpanded, overflowActions, overflowId]);
  return /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)(Box_default, { ref: containerRef, flexDirection: "column", marginLeft: 2, children: [
    /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)(Box_default, { flexDirection: "row", flexWrap: "wrap", children: [
      /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)(Text, { color: theme.text.primary, bold: true, wrap: "truncate-end", children: [
        title || "Topic",
        intent && /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(Text, { children: ": " })
      ] }),
      intent && /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(Text, { color: theme.text.secondary, wrap: "wrap", children: intent })
    ] }),
    isExpanded && hasExtraSummary && summary && /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(Box_default, { marginTop: 1, marginLeft: 0, children: /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(Text, { color: theme.text.secondary, wrap: "wrap", children: summary }) })
  ] });
};

// packages/cli/src/ui/components/messages/SubagentGroupDisplay.tsx
var import_react32 = __toESM(require_react(), 1);
var import_jsx_runtime34 = __toESM(require_jsx_runtime(), 1);
var SubagentGroupDisplay = ({
  toolCalls,
  availableTerminalHeight,
  terminalWidth,
  borderColor,
  borderDimColor,
  isFirst,
  isExpandable = true
}) => {
  const isExpanded = availableTerminalHeight === void 0;
  const overflowActions = useOverflowActions();
  const uniqueId = (0, import_react32.useId)();
  const overflowId = `subagent-${uniqueId}`;
  (0, import_react32.useEffect)(() => {
    if (isExpandable && overflowActions) {
      overflowActions.addOverflowingId(overflowId);
    }
    return () => {
      if (overflowActions) {
        overflowActions.removeOverflowingId(overflowId);
      }
    };
  }, [isExpandable, overflowActions, overflowId]);
  if (toolCalls.length === 0) {
    return null;
  }
  let headerText = "";
  if (toolCalls.length === 1) {
    const singleAgent = toolCalls[0].resultDisplay;
    if (isSubagentProgress(singleAgent)) {
      switch (singleAgent.state) {
        case "completed":
          headerText = "Agent Completed";
          break;
        case "cancelled":
          headerText = "Agent Cancelled";
          break;
        case "error":
          headerText = "Agent Error";
          break;
        default:
          headerText = "Running Agent...";
          break;
      }
    } else {
      headerText = "Running Agent...";
    }
  } else {
    let completedCount = 0;
    let runningCount = 0;
    for (const tc of toolCalls) {
      const progress = tc.resultDisplay;
      if (isSubagentProgress(progress)) {
        if (progress.state === "completed") completedCount++;
        else if (progress.state === "running") runningCount++;
      } else {
        runningCount++;
      }
    }
    if (completedCount === toolCalls.length) {
      headerText = `${toolCalls.length} Agents Completed`;
    } else if (completedCount > 0) {
      headerText = `${toolCalls.length} Agents (${runningCount} running, ${completedCount} completed)...`;
    } else {
      headerText = `Running ${toolCalls.length} Agents...`;
    }
  }
  const toggleText = `(ctrl+o to ${isExpanded ? "collapse" : "expand"})`;
  const renderCollapsedRow = (key, agentName, icon, content, displayArgs) => /* @__PURE__ */ (0, import_jsx_runtime34.jsxs)(Box_default, { flexDirection: "row", marginLeft: 0, marginTop: 0, children: [
    /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(Box_default, { minWidth: 2, flexShrink: 0, children: icon }),
    /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(Box_default, { flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(Text, { bold: true, color: theme.text.primary, wrap: "truncate", children: agentName }) }),
    /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(Box_default, { flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(Text, { color: theme.text.secondary, children: " \xB7 " }) }),
    /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(Box_default, { flexShrink: 1, minWidth: 0, children: /* @__PURE__ */ (0, import_jsx_runtime34.jsxs)(Text, { color: theme.text.secondary, wrap: "truncate", children: [
      content,
      displayArgs && ` ${displayArgs}`
    ] }) })
  ] }, key);
  return /* @__PURE__ */ (0, import_jsx_runtime34.jsxs)(
    Box_default,
    {
      flexDirection: "column",
      width: terminalWidth,
      borderLeft: true,
      borderRight: true,
      borderTop: isFirst,
      borderBottom: false,
      borderColor,
      borderDimColor,
      borderStyle: "round",
      paddingLeft: 1,
      paddingTop: 0,
      paddingBottom: 0,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime34.jsxs)(Box_default, { flexDirection: "row", gap: 1, marginBottom: isExpanded ? 1 : 0, children: [
          /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(Text, { color: theme.text.secondary, children: "\u2261" }),
          /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(Text, { bold: true, color: theme.text.primary, children: headerText }),
          isExpandable && /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(Text, { color: theme.text.secondary, children: toggleText })
        ] }),
        toolCalls.map((toolCall) => {
          const progress = toolCall.resultDisplay;
          if (!isSubagentProgress(progress)) {
            const agentName = toolCall.name || "agent";
            if (!isExpanded) {
              return renderCollapsedRow(
                toolCall.callId,
                agentName,
                /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(Text, { color: theme.text.primary, children: "!" }),
                "Starting..."
              );
            } else {
              return /* @__PURE__ */ (0, import_jsx_runtime34.jsxs)(
                Box_default,
                {
                  flexDirection: "column",
                  marginLeft: 0,
                  marginBottom: 1,
                  children: [
                    /* @__PURE__ */ (0, import_jsx_runtime34.jsxs)(Box_default, { flexDirection: "row", gap: 1, children: [
                      /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(Text, { color: theme.text.primary, children: "!" }),
                      /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(Text, { bold: true, color: theme.text.primary, children: agentName })
                    ] }),
                    /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(Box_default, { marginLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(Text, { color: theme.text.secondary, children: "Starting..." }) })
                  ]
                },
                toolCall.callId
              );
            }
          }
          const history = toolCall.subagentHistory ?? progress.recentActivity;
          const lastActivity = history[history.length - 1];
          if (!isExpanded) {
            let content = "Starting...";
            let formattedArgs;
            if (progress.state === "completed") {
              if (progress.terminateReason && progress.terminateReason !== "GOAL") {
                content = `Finished Early (${progress.terminateReason})`;
              } else {
                content = "Completed successfully";
              }
            } else if (lastActivity) {
              content = lastActivity.displayName || lastActivity.content;
              if (lastActivity.description) {
                formattedArgs = lastActivity.description;
              } else if (lastActivity.type === "tool_call" && lastActivity.args) {
                formattedArgs = formatToolArgs(lastActivity.args);
              }
            }
            const displayArgs = progress.state === "completed" ? "" : formattedArgs;
            const renderStatusIcon = () => {
              const state = progress.state ?? "running";
              switch (state) {
                case "running":
                  return /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(Text, { color: theme.text.primary, children: "!" });
                case "completed":
                  return /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(Text, { color: theme.status.success, children: "\u2713" });
                case "cancelled":
                  return /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(Text, { color: theme.status.warning, children: "\u2139" });
                case "error":
                  return /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(Text, { color: theme.status.error, children: "\u2717" });
                default:
                  return checkExhaustive(state);
              }
            };
            return renderCollapsedRow(
              toolCall.callId,
              progress.agentName,
              renderStatusIcon(),
              lastActivity?.type === "thought" ? `\u{1F4AD} ${content}` : content,
              displayArgs
            );
          }
          return /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(
            Box_default,
            {
              flexDirection: "column",
              marginLeft: 0,
              marginBottom: 1,
              children: /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(
                SubagentProgressDisplay,
                {
                  progress,
                  terminalWidth,
                  historyOverrides: toolCall.subagentHistory
                }
              )
            },
            toolCall.callId
          );
        })
      ]
    }
  );
};

// packages/cli/src/ui/components/messages/DenseToolMessage.tsx
var import_react33 = __toESM(require_react(), 1);
var import_jsx_runtime35 = __toESM(require_jsx_runtime(), 1);
var PAYLOAD_MARGIN_LEFT = 6;
var PAYLOAD_BORDER_CHROME_WIDTH = 4;
var PAYLOAD_SCROLL_GUTTER = 4;
var PAYLOAD_MAX_WIDTH = 120 + PAYLOAD_SCROLL_GUTTER;
var hasPayload = (res) => {
  if (!hasSummary(res)) return false;
  if (!("payload" in res)) return false;
  const value = res.payload;
  return typeof value === "string";
};
var RenderItemsList = ({ items, maxVisible = 20 }) => {
  if (!items || items.length === 0) return null;
  return /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Box_default, { flexDirection: "column", children: [
    items.slice(0, maxVisible).map((item, i) => /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Text, { color: theme.text.secondary, children: item }, i)),
    items.length > maxVisible && /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Text, { color: theme.text.secondary, children: [
      "... and ",
      items.length - maxVisible,
      " more"
    ] })
  ] });
};
function getFileOpData(diff2, status, resultDisplay, terminalWidth, availableTerminalHeight, isClickable) {
  const added = (diff2.diffStat?.model_added_lines ?? 0) + (diff2.diffStat?.user_added_lines ?? 0);
  const removed = (diff2.diffStat?.model_removed_lines ?? 0) + (diff2.diffStat?.user_removed_lines ?? 0);
  const isAcceptedOrConfirming = status === CoreToolCallStatus.Success || status === CoreToolCallStatus.Executing || status === CoreToolCallStatus.AwaitingApproval;
  const addColor = isAcceptedOrConfirming ? theme.status.success : theme.text.secondary;
  const removeColor = isAcceptedOrConfirming ? theme.status.error : theme.text.secondary;
  const showDiffStat = !!diff2.diffStat;
  const description = /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Box_default, { flexDirection: "row", children: /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Text, { color: theme.text.secondary, wrap: "truncate-end", children: diff2.fileName }) });
  let resultSummary = "";
  let resultColor = theme.text.secondary;
  if (status === CoreToolCallStatus.AwaitingApproval) {
    resultSummary = "Confirming";
  } else if (status === CoreToolCallStatus.Success || status === CoreToolCallStatus.Executing) {
    resultSummary = "Accepted";
    resultColor = theme.text.accent;
  } else if (status === CoreToolCallStatus.Cancelled) {
    resultSummary = "Rejected";
    resultColor = theme.status.error;
  } else if (status === CoreToolCallStatus.Error) {
    resultSummary = typeof resultDisplay === "string" ? resultDisplay : "Failed";
    resultColor = theme.status.error;
  }
  const summary = /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Box_default, { flexDirection: "row", children: [
    resultSummary && /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Text, { color: resultColor, wrap: "truncate-end", children: [
      "\u2192",
      " ",
      /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Text, { underline: isClickable, children: resultSummary.replace(/\n/g, " ") })
    ] }),
    showDiffStat && /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Box_default, { marginLeft: 1, marginRight: 2, children: /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Text, { color: theme.text.secondary, children: [
      "(",
      /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Text, { color: addColor, children: [
        "+",
        added
      ] }),
      ", ",
      /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Text, { color: removeColor, children: [
        "-",
        removed
      ] }),
      ")"
    ] }) })
  ] });
  const payload = /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
    DiffRenderer,
    {
      diffContent: diff2.fileDiff,
      filename: diff2.fileName,
      terminalWidth: terminalWidth - PAYLOAD_MARGIN_LEFT,
      availableTerminalHeight,
      disableColor: status === CoreToolCallStatus.Cancelled
    }
  );
  return { description, summary, payload };
}
function getReadManyFilesData(result) {
  const items = result.files ?? [];
  const maxVisible = 10;
  const includePatterns = result.include?.join(", ") ?? "";
  const description = /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Text, { color: theme.text.secondary, wrap: "truncate-end", children: [
    "Attempting to read files from ",
    includePatterns
  ] });
  const skippedCount = result.skipped?.length ?? 0;
  const summaryStr = `Read ${items.length} file(s)${skippedCount > 0 ? ` (${skippedCount} ignored)` : ""}`;
  const summary = /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Text, { color: theme.text.accent, children: [
    "\u2192 ",
    summaryStr
  ] });
  const hasItems = items.length > 0;
  const payload = hasItems ? /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Box_default, { flexDirection: "column", marginLeft: 2, children: hasItems && /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(RenderItemsList, { items, maxVisible }) }) : void 0;
  return { description, summary, payload };
}
function getListDirectoryData(result, originalDescription) {
  const description = originalDescription ? /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Text, { color: theme.text.secondary, wrap: "truncate-end", children: originalDescription }) : void 0;
  const summary = /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Text, { color: theme.text.accent, children: [
    "\u2192 ",
    result.summary
  ] });
  return { description, summary, payload: void 0 };
}
function getListResultData(result, originalDescription) {
  if (isReadManyFilesResult(result)) {
    return getReadManyFilesData(result);
  }
  return getListDirectoryData(result, originalDescription);
}
function getGenericSuccessData(resultDisplay, originalDescription) {
  let summary;
  let payload;
  const description = originalDescription ? /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Text, { color: theme.text.secondary, wrap: "truncate-end", children: originalDescription }) : void 0;
  if (typeof resultDisplay === "string") {
    const flattened = resultDisplay.replace(/\n/g, " ").trim();
    summary = /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Text, { color: theme.text.accent, wrap: "truncate-end", children: [
      "\u2192 ",
      flattened
    ] });
  } else if (isGrepResult(resultDisplay)) {
    summary = /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Text, { color: theme.text.accent, children: [
      "\u2192 ",
      resultDisplay.summary
    ] });
    const matches = resultDisplay.matches;
    if (matches.length > 0) {
      payload = /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Box_default, { flexDirection: "column", marginLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
        RenderItemsList,
        {
          items: matches.map(
            (m) => `${m.filePath}:${m.lineNumber}: ${m.line.trim()}`
          ),
          maxVisible: 10
        }
      ) });
    }
  } else if (isTodoList(resultDisplay)) {
    summary = /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Text, { color: theme.text.accent, wrap: "wrap", children: "\u2192 Todos updated" });
  } else if (hasPayload(resultDisplay)) {
    summary = /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Text, { color: theme.text.accent, children: [
      "\u2192 ",
      resultDisplay.summary
    ] });
    payload = /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Box_default, { marginLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Text, { color: theme.text.secondary, children: resultDisplay.payload }) });
  } else {
    summary = /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Text, { color: theme.text.accent, wrap: "wrap", children: "\u2192 Returned (possible empty result)" });
  }
  return { description, summary, payload };
}
var DenseToolMessage = (props) => {
  const {
    callId,
    name,
    status,
    resultDisplay,
    confirmationDetails,
    outputFile,
    terminalWidth,
    availableTerminalHeight,
    description: originalDescription
  } = props;
  const settings = useSettings();
  const isAlternateBuffer = useAlternateBuffer();
  const { isExpanded: isExpandedInContext, toggleExpansion } = useToolActions();
  const [localIsExpanded, setLocalIsExpanded] = (0, import_react33.useState)(false);
  const isExpanded = isExpandedInContext ? isExpandedInContext(callId) : localIsExpanded;
  const [isFocused, setIsFocused] = (0, import_react33.useState)(false);
  const toggleRef = (0, import_react33.useRef)(null);
  const diff2 = (0, import_react33.useMemo)(() => {
    if (isFileDiff(resultDisplay)) return resultDisplay;
    if (confirmationDetails?.type === "edit") {
      const details = confirmationDetails;
      return {
        fileName: details.fileName,
        fileDiff: details.fileDiff,
        filePath: details.filePath,
        originalContent: details.originalContent,
        newContent: details.newContent,
        diffStat: details.diffStat
      };
    }
    return void 0;
  }, [resultDisplay, confirmationDetails]);
  const handleToggle = () => {
    const next = !isExpanded;
    if (!next) {
      setIsFocused(false);
    } else {
      setIsFocused(true);
    }
    if (toggleExpansion) {
      toggleExpansion(callId);
    } else {
      setLocalIsExpanded(next);
    }
  };
  useMouseClick(toggleRef, handleToggle, {
    isActive: isAlternateBuffer && !!diff2
  });
  const viewParts = (0, import_react33.useMemo)(() => {
    if (diff2) {
      return getFileOpData(
        diff2,
        status,
        resultDisplay,
        terminalWidth,
        availableTerminalHeight,
        isAlternateBuffer
      );
    }
    if (isListResult(resultDisplay)) {
      return getListResultData(resultDisplay, originalDescription);
    }
    if (isGrepResult(resultDisplay)) {
      return getGenericSuccessData(resultDisplay, originalDescription);
    }
    if (status === CoreToolCallStatus.Success && resultDisplay) {
      return getGenericSuccessData(resultDisplay, originalDescription);
    }
    if (status === CoreToolCallStatus.Error) {
      const text = typeof resultDisplay === "string" ? resultDisplay.replace(/\n/g, " ") : "Failed";
      const errorSummary = /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Text, { color: theme.status.error, wrap: "truncate-end", children: [
        "\u2192 ",
        text
      ] });
      const descriptionText2 = originalDescription ? /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Text, { color: theme.text.secondary, wrap: "truncate-end", children: originalDescription }) : void 0;
      return {
        description: descriptionText2,
        summary: errorSummary,
        payload: void 0
      };
    }
    const descriptionText = originalDescription ? /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Text, { color: theme.text.secondary, wrap: "truncate-end", children: originalDescription }) : void 0;
    return {
      description: descriptionText,
      summary: void 0,
      payload: void 0
    };
  }, [
    diff2,
    status,
    resultDisplay,
    terminalWidth,
    availableTerminalHeight,
    originalDescription,
    isAlternateBuffer
  ]);
  const { description, summary } = viewParts;
  const diffLines = (0, import_react33.useMemo)(() => {
    if (!diff2 || !isExpanded || !isAlternateBuffer) return [];
    const parsedLines = parseDiffWithLineNumbers(diff2.fileDiff);
    const isNewFileResult = isNewFile(parsedLines);
    if (isNewFileResult) {
      const addedContent = parsedLines.filter((line) => line.type === "add").map((line) => line.content).join("\n");
      const fileExtension = getFileExtension(diff2.fileName);
      return colorizeCode({
        code: addedContent,
        language: fileExtension,
        maxWidth: terminalWidth - PAYLOAD_MARGIN_LEFT,
        settings,
        disableColor: status === CoreToolCallStatus.Cancelled,
        returnLines: true
      });
    } else {
      return renderDiffLines({
        parsedLines,
        filename: diff2.fileName,
        terminalWidth: terminalWidth - PAYLOAD_MARGIN_LEFT,
        disableColor: status === CoreToolCallStatus.Cancelled
      });
    }
  }, [diff2, isExpanded, isAlternateBuffer, terminalWidth, settings, status]);
  const showPayload = (0, import_react33.useMemo)(() => {
    const policy = !isAlternateBuffer || !diff2 || isExpanded;
    if (!policy) return false;
    if (diff2) {
      if (isAlternateBuffer) {
        return isExpanded && diffLines.length > 0;
      }
      return true;
    }
    return !!(viewParts.payload || outputFile);
  }, [
    isAlternateBuffer,
    diff2,
    isExpanded,
    diffLines.length,
    viewParts.payload,
    outputFile
  ]);
  const keyExtractor = (_item, index) => `diff-line-${index}`;
  const renderItem = ({ item }) => /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Box_default, { minHeight: 1, children: item });
  return /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Box_default, { flexDirection: "column", children: [
    /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Box_default, { marginLeft: 2, flexDirection: "row", flexWrap: "wrap", children: [
      /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(ToolStatusIndicator, { status, name }),
      /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Box_default, { maxWidth: 25, flexShrink: 1, flexGrow: 0, children: /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Text, { color: theme.text.primary, bold: true, wrap: "truncate-end", children: [
        name,
        " "
      ] }) }),
      /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Box_default, { marginLeft: 1, flexShrink: 1, flexGrow: 0, children: description }),
      summary && /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
        Box_default,
        {
          ref: isAlternateBuffer && diff2 ? toggleRef : void 0,
          marginLeft: 1,
          flexGrow: 0,
          children: summary
        },
        "tool-summary"
      )
    ] }),
    showPayload && isAlternateBuffer && diffLines.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
      Box_default,
      {
        marginLeft: PAYLOAD_MARGIN_LEFT,
        marginTop: 1,
        marginBottom: 1,
        paddingX: 1,
        flexDirection: "column",
        height: Math.min(diffLines.length, COMPACT_TOOL_SUBVIEW_MAX_LINES) + 2,
        maxHeight: COMPACT_TOOL_SUBVIEW_MAX_LINES + 2,
        borderStyle: "round",
        borderColor: theme.border.default,
        borderDimColor: true,
        maxWidth: Math.min(
          PAYLOAD_MAX_WIDTH,
          terminalWidth - PAYLOAD_MARGIN_LEFT
        ),
        children: /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
          ScrollableListWithForwardRef,
          {
            data: diffLines,
            renderItem,
            keyExtractor,
            estimatedItemHeight: () => 1,
            hasFocus: isFocused,
            width: Math.min(
              PAYLOAD_MAX_WIDTH,
              terminalWidth - PAYLOAD_MARGIN_LEFT - PAYLOAD_BORDER_CHROME_WIDTH - PAYLOAD_SCROLL_GUTTER
            )
          }
        )
      }
    ),
    showPayload && (!isAlternateBuffer || !diff2) && viewParts.payload && /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Box_default, { marginLeft: PAYLOAD_MARGIN_LEFT, marginTop: 1, marginBottom: 1, children: viewParts.payload }),
    showPayload && outputFile && /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Box_default, { marginLeft: PAYLOAD_MARGIN_LEFT, marginTop: 1, marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Text, { color: theme.text.secondary, children: [
      "(Output saved to: ",
      outputFile,
      ")"
    ] }) })
  ] });
};

// packages/cli/src/ui/utils/borderStyles.ts
function isTrackedToolCall(tool) {
  return "request" in tool;
}
function getToolGroupBorderAppearance(item, activeShellPtyId, embeddedShellFocused, allPendingItems = [], backgroundTasks = /* @__PURE__ */ new Map()) {
  if (item.type !== "tool_group") {
    return { borderColor: "", borderDimColor: false };
  }
  const toolsToInspect = item.tools.length > 0 ? item.tools : allPendingItems.filter(
    (i) => i !== null && i !== void 0 && i.type === "tool_group" && i.tools.length > 0
  ).slice(-1).flatMap((i) => i.tools);
  const hasPending = toolsToInspect.some((t) => {
    if (isTrackedToolCall(t)) {
      return t.status !== "success" && t.status !== "error" && t.status !== "cancelled";
    } else {
      return t.status !== CoreToolCallStatus.Success && t.status !== CoreToolCallStatus.Error && t.status !== CoreToolCallStatus.Cancelled;
    }
  });
  const isEmbeddedShellFocused = toolsToInspect.some((t) => {
    if (isTrackedToolCall(t)) {
      return isShellTool(t.request.name) && t.status === "executing" && t.pid === activeShellPtyId && !!embeddedShellFocused;
    } else {
      return isShellTool(t.name) && t.status === CoreToolCallStatus.Executing && t.ptyId === activeShellPtyId && !!embeddedShellFocused;
    }
  });
  const isShellCommand = toolsToInspect.some((t) => {
    if (isTrackedToolCall(t)) {
      return isShellTool(t.request.name);
    } else {
      return isShellTool(t.name);
    }
  });
  const isCurrentlyInShellTurn = !!activeShellPtyId && !backgroundTasks.has(activeShellPtyId);
  const isShell = isShellCommand || item.tools.length === 0 && isCurrentlyInShellTurn;
  const isPending = hasPending || item.tools.length === 0 && isCurrentlyInShellTurn;
  const isEffectivelyFocused = isEmbeddedShellFocused || item.tools.length === 0 && isCurrentlyInShellTurn && !!embeddedShellFocused;
  const borderColor = isEffectivelyFocused ? theme.ui.focus : isShell && isPending ? theme.ui.active : isPending ? theme.status.warning : theme.border.default;
  const borderDimColor = isPending && (!isShell || !isEffectivelyFocused);
  return { borderColor, borderDimColor };
}

// packages/cli/src/ui/components/messages/ToolGroupMessage.tsx
var import_jsx_runtime36 = __toESM(require_jsx_runtime(), 1);
var COMPACT_OUTPUT_ALLOWLIST = /* @__PURE__ */ new Set([
  EDIT_DISPLAY_NAME,
  GLOB_DISPLAY_NAME,
  WEB_SEARCH_DISPLAY_NAME,
  READ_FILE_DISPLAY_NAME,
  LS_DISPLAY_NAME,
  GREP_DISPLAY_NAME,
  WEB_FETCH_DISPLAY_NAME,
  WRITE_FILE_DISPLAY_NAME,
  READ_MANY_FILES_DISPLAY_NAME
]);
var isCompactTool = (tool, isCompactModeEnabled) => {
  const hasCompactOutputSupport = COMPACT_OUTPUT_ALLOWLIST.has(tool.name);
  const displayStatus = mapCoreStatusToDisplayStatus(tool.status);
  return isCompactModeEnabled && hasCompactOutputSupport && displayStatus !== "Confirming" /* Confirming */;
};
var hasDensePayload = (tool) => {
  if (tool.outputFile) return true;
  const res = tool.resultDisplay;
  if (!res) return false;
  if (isFileDiff(res)) return true;
  if (tool.confirmationDetails?.type === "edit") return true;
  if (isGrepResult(res) && res.matches.length > 0) return true;
  if (isListResult(res) && "include" in res) {
    const includeProp = res.include;
    if (Array.isArray(includeProp) && res.files.length > 0) {
      return true;
    }
  }
  if (typeof res === "object" && res !== null && "summary" in res && "payload" in res) {
    return true;
  }
  return false;
};
var TOOL_MESSAGE_HORIZONTAL_MARGIN = 4;
var ToolGroupMessage = ({
  item,
  toolCalls: allToolCalls,
  availableTerminalHeight,
  terminalWidth,
  borderTop: borderTopOverride,
  borderBottom: borderBottomOverride,
  isExpandable,
  isToolGroupBoundary
}) => {
  const settings = useSettings();
  const isLowErrorVerbosity = settings.merged.ui?.errorVerbosity !== "full";
  const isCompactModeEnabled = settings.merged.ui?.compactToolOutput === true;
  const visibleToolCalls = (0, import_react34.useMemo)(
    () => allToolCalls.filter((t) => {
      if (isLowErrorVerbosity && t.status === CoreToolCallStatus.Error && !t.isClientInitiated) {
        return false;
      }
      if (shouldHideToolCall({
        displayName: t.name,
        status: t.status,
        approvalMode: t.approvalMode,
        hasResultDisplay: !!t.resultDisplay,
        parentCallId: t.parentCallId
      })) {
        return false;
      }
      const displayStatus = mapCoreStatusToDisplayStatus(t.status);
      return displayStatus !== "Confirming" /* Confirming */;
    }),
    [allToolCalls, isLowErrorVerbosity]
  );
  const {
    activePtyId,
    embeddedShellFocused,
    backgroundTasks,
    pendingHistoryItems
  } = useUIState();
  const config = useConfig();
  const { borderColor, borderDimColor } = (0, import_react34.useMemo)(
    () => getToolGroupBorderAppearance(
      item,
      activePtyId,
      embeddedShellFocused,
      pendingHistoryItems,
      backgroundTasks
    ),
    [
      item,
      activePtyId,
      embeddedShellFocused,
      pendingHistoryItems,
      backgroundTasks
    ]
  );
  const groupedTools = (0, import_react34.useMemo)(() => {
    const groups = [];
    for (const tool of visibleToolCalls) {
      if (tool.kind === Kind.Agent) {
        const lastGroup = groups[groups.length - 1];
        if (Array.isArray(lastGroup)) {
          lastGroup.push(tool);
        } else {
          groups.push([tool]);
        }
      } else {
        groups.push(tool);
      }
    }
    return groups;
  }, [visibleToolCalls]);
  const staticHeight = (0, import_react34.useMemo)(() => {
    let height = 0;
    for (let i = 0; i < groupedTools.length; i++) {
      const group = groupedTools[i];
      const isLast = i === groupedTools.length - 1;
      const prevGroup = i > 0 ? groupedTools[i - 1] : null;
      const prevIsCompact = prevGroup && !Array.isArray(prevGroup) && isCompactTool(prevGroup, isCompactModeEnabled);
      const nextGroup = !isLast ? groupedTools[i + 1] : null;
      const nextIsCompact = nextGroup && !Array.isArray(nextGroup) && isCompactTool(nextGroup, isCompactModeEnabled);
      const nextIsTopicToolCall = nextGroup && !Array.isArray(nextGroup) && isTopicTool(nextGroup.name);
      const isAgentGroup = Array.isArray(group);
      const isCompact = !isAgentGroup && isCompactTool(group, isCompactModeEnabled);
      const isTopicToolCall = !isAgentGroup && isTopicTool(group.name);
      let isFirst = i === 0;
      if (!isFirst) {
        let allPreviousTopics = true;
        for (let j = 0; j < i; j++) {
          const prevGroupItem = groupedTools[j];
          if (Array.isArray(prevGroupItem) || !isTopicTool(prevGroupItem.name)) {
            allPreviousTopics = false;
            break;
          }
        }
        isFirst = allPreviousTopics;
      }
      const isFirstProp = !!(isFirst ? borderTopOverride ?? true : prevIsCompact);
      const showClosingBorder = !isCompact && !isTopicToolCall && (nextIsCompact || nextIsTopicToolCall || isLast);
      if (isAgentGroup) {
        height += (isFirstProp ? 1 : 0) + 1 + group.length + (showClosingBorder ? 1 : 0);
      } else if (isTopicToolCall) {
        const hasTopMargin = !(isFirst && isToolGroupBoundary);
        height += (hasTopMargin ? 1 : 0) + 1 + 1;
      } else if (isCompact) {
        height += 1;
      } else {
        height += TOOL_RESULT_STANDARD_RESERVED_LINE_COUNT - 1 + TOOL_RESULT_STATIC_HEIGHT + (group.outputFile ? 1 : 0) + (showClosingBorder ? 1 : 0);
      }
    }
    return height;
  }, [
    groupedTools,
    isCompactModeEnabled,
    borderTopOverride,
    isToolGroupBoundary
  ]);
  let countToolCallsWithResults = 0;
  for (const tool of visibleToolCalls) {
    if (tool.kind !== Kind.Agent) {
      if (isCompactTool(tool, isCompactModeEnabled)) {
        if (hasDensePayload(tool)) {
          countToolCallsWithResults++;
        }
      } else if (tool.resultDisplay !== void 0 && tool.resultDisplay !== "") {
        countToolCallsWithResults++;
      }
    }
  }
  const availableTerminalHeightPerToolMessage = availableTerminalHeight ? Math.max(
    Math.floor(
      (availableTerminalHeight - staticHeight) / Math.max(1, countToolCallsWithResults)
    ),
    1
  ) : void 0;
  const contentWidth = terminalWidth - TOOL_MESSAGE_HORIZONTAL_MARGIN;
  const isExplicitClosingSlice = allToolCalls.length === 0;
  const shouldShowGroup = visibleToolCalls.length > 0 || isExplicitClosingSlice && borderBottomOverride === true;
  if (!shouldShowGroup) {
    return null;
  }
  const content = /* @__PURE__ */ (0, import_jsx_runtime36.jsxs)(
    Box_default,
    {
      flexDirection: "column",
      width: terminalWidth,
      paddingRight: TOOL_MESSAGE_HORIZONTAL_MARGIN,
      marginBottom: 0,
      children: [
        visibleToolCalls.length === 0 && isExplicitClosingSlice && borderBottomOverride === true && /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(
          Box_default,
          {
            width: contentWidth,
            borderLeft: true,
            borderRight: true,
            borderTop: false,
            borderBottom: true,
            borderColor,
            borderDimColor,
            borderStyle: "round"
          }
        ),
        groupedTools.map((group, index) => {
          let isFirst = index === 0;
          if (!isFirst) {
            let allPreviousWereTopics = true;
            for (let i = 0; i < index; i++) {
              const prevGroup2 = groupedTools[i];
              if (Array.isArray(prevGroup2) || !isTopicTool(prevGroup2.name)) {
                allPreviousWereTopics = false;
                break;
              }
            }
            isFirst = allPreviousWereTopics;
          }
          const isLast = index === groupedTools.length - 1;
          const prevGroup = index > 0 ? groupedTools[index - 1] : null;
          const prevIsCompact = prevGroup && !Array.isArray(prevGroup) && isCompactTool(prevGroup, isCompactModeEnabled);
          const nextGroup = !isLast ? groupedTools[index + 1] : null;
          const nextIsCompact = nextGroup && !Array.isArray(nextGroup) && isCompactTool(nextGroup, isCompactModeEnabled);
          const nextIsTopicToolCall = nextGroup && !Array.isArray(nextGroup) && isTopicTool(nextGroup.name);
          const isAgentGroup = Array.isArray(group);
          const isCompact = !isAgentGroup && isCompactTool(group, isCompactModeEnabled);
          const isTopicToolCall = !isAgentGroup && isTopicTool(group.name);
          const isFirstProp = !!(isFirst ? borderTopOverride ?? true : prevIsCompact);
          const showClosingBorder = !isCompact && !isTopicToolCall && (nextIsCompact || nextIsTopicToolCall || isLast);
          if (isAgentGroup) {
            return /* @__PURE__ */ (0, import_jsx_runtime36.jsxs)(
              Box_default,
              {
                flexDirection: "column",
                width: contentWidth,
                children: [
                  /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(
                    SubagentGroupDisplay,
                    {
                      toolCalls: group,
                      availableTerminalHeight,
                      terminalWidth: contentWidth,
                      borderColor,
                      borderDimColor,
                      isFirst: isFirstProp,
                      isExpandable
                    }
                  ),
                  showClosingBorder && /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(
                    Box_default,
                    {
                      width: contentWidth,
                      borderLeft: true,
                      borderRight: true,
                      borderTop: false,
                      borderBottom: isLast ? borderBottomOverride ?? true : true,
                      borderColor,
                      borderDimColor,
                      borderStyle: "round"
                    }
                  )
                ]
              },
              group[0].callId
            );
          }
          const tool = group;
          const isShellToolCall = isShellTool(tool.name);
          const commonProps = {
            ...tool,
            availableTerminalHeight: availableTerminalHeightPerToolMessage,
            terminalWidth: contentWidth,
            emphasis: "medium",
            isFirst: isCompact ? false : isFirstProp,
            borderColor,
            borderDimColor,
            isExpandable
          };
          return /* @__PURE__ */ (0, import_jsx_runtime36.jsxs)(import_react34.Fragment, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime36.jsxs)(Box_default, { flexDirection: "column", minHeight: 1, width: contentWidth, children: [
              isCompact ? /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(DenseToolMessage, { ...commonProps }) : isTopicToolCall ? /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(
                Box_default,
                {
                  marginTop: isFirst && isToolGroupBoundary ? 0 : 1,
                  marginBottom: 1,
                  children: /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(TopicMessage, { ...commonProps })
                }
              ) : isShellToolCall ? /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(ShellToolMessage, { ...commonProps, config }) : /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(ToolMessage, { ...commonProps }),
              !isCompact && tool.outputFile && /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(
                Box_default,
                {
                  borderLeft: true,
                  borderRight: true,
                  borderTop: false,
                  borderBottom: false,
                  borderColor,
                  borderDimColor,
                  flexDirection: "column",
                  borderStyle: "round",
                  paddingLeft: 1,
                  paddingRight: 1,
                  children: /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime36.jsxs)(Text, { color: theme.text.primary, children: [
                    "Output too long and was saved to: ",
                    tool.outputFile
                  ] }) })
                }
              )
            ] }),
            showClosingBorder && /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(
              Box_default,
              {
                width: contentWidth,
                borderLeft: true,
                borderRight: true,
                borderTop: false,
                borderBottom: isLast ? borderBottomOverride ?? true : true,
                borderColor,
                borderDimColor,
                borderStyle: "round"
              }
            )
          ] }, tool.callId);
        })
      ]
    }
  );
  return content;
};

// packages/cli/src/ui/components/messages/GeminiMessageContent.tsx
var import_jsx_runtime37 = __toESM(require_jsx_runtime(), 1);
var GeminiMessageContent = ({
  text,
  isPending,
  availableTerminalHeight,
  terminalWidth
}) => {
  const { renderMarkdown } = useUIState();
  const originalPrefix = "\u2726 ";
  const prefixWidth = originalPrefix.length;
  return /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(Box_default, { flexDirection: "column", paddingLeft: prefixWidth, children: /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(
    MarkdownDisplay,
    {
      text,
      isPending,
      availableTerminalHeight: availableTerminalHeight === void 0 ? void 0 : Math.max(availableTerminalHeight - 1, 1),
      terminalWidth: Math.max(terminalWidth - prefixWidth, 0),
      renderMarkdown
    }
  ) });
};

// packages/cli/src/ui/components/messages/CompressionMessage.tsx
var import_jsx_runtime38 = __toESM(require_jsx_runtime(), 1);
function CompressionMessage({
  compression
}) {
  const { isPending, originalTokenCount, newTokenCount, compressionStatus } = compression;
  const originalTokens = originalTokenCount ?? 0;
  const newTokens = newTokenCount ?? 0;
  const getCompressionText = () => {
    if (isPending) {
      return "Compressing chat history";
    }
    switch (compressionStatus) {
      case CompressionStatus.COMPRESSED:
        return `Chat history compressed from ${originalTokens} to ${newTokens} tokens.`;
      case CompressionStatus.COMPRESSION_FAILED_INFLATED_TOKEN_COUNT:
        if (originalTokens < 5e4) {
          return "Compression was not beneficial for this history size.";
        }
        return "Chat history compression did not reduce size. This may indicate issues with the compression prompt.";
      case CompressionStatus.COMPRESSION_FAILED_TOKEN_COUNT_ERROR:
        return "Could not compress chat history due to a token counting error.";
      case CompressionStatus.COMPRESSION_FAILED_EMPTY_SUMMARY:
        return "Chat history compression failed: the model returned an empty summary.";
      case CompressionStatus.NOOP:
        return "Nothing to compress.";
      default:
        return "";
    }
  };
  const text = getCompressionText();
  return /* @__PURE__ */ (0, import_jsx_runtime38.jsxs)(Box_default, { flexDirection: "row", children: [
    /* @__PURE__ */ (0, import_jsx_runtime38.jsx)(Box_default, { marginRight: 1, children: isPending ? /* @__PURE__ */ (0, import_jsx_runtime38.jsx)(CliSpinner, { type: "dots" }) : /* @__PURE__ */ (0, import_jsx_runtime38.jsx)(Text, { color: theme.text.accent, children: "\u2726" }) }),
    /* @__PURE__ */ (0, import_jsx_runtime38.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime38.jsx)(
      Text,
      {
        color: compression.isPending ? theme.text.accent : theme.status.success,
        "aria-label": SCREEN_READER_MODEL_PREFIX,
        children: text
      }
    ) })
  ] });
}

// packages/cli/src/ui/components/messages/WarningMessage.tsx
var import_jsx_runtime39 = __toESM(require_jsx_runtime(), 1);
var WarningMessage = ({ text }) => {
  const prefix = "\u26A0 ";
  const prefixWidth = 3;
  return /* @__PURE__ */ (0, import_jsx_runtime39.jsxs)(Box_default, { flexDirection: "row", marginTop: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime39.jsx)(Box_default, { width: prefixWidth, children: /* @__PURE__ */ (0, import_jsx_runtime39.jsx)(Text, { color: theme.status.warning, children: prefix }) }),
    /* @__PURE__ */ (0, import_jsx_runtime39.jsx)(Box_default, { flexGrow: 1, children: /* @__PURE__ */ (0, import_jsx_runtime39.jsx)(Text, { wrap: "wrap", children: /* @__PURE__ */ (0, import_jsx_runtime39.jsx)(RenderInline, { text, defaultColor: theme.status.warning }) }) })
  ] });
};

// packages/cli/src/ui/components/messages/SubagentHistoryMessage.tsx
var import_jsx_runtime40 = __toESM(require_jsx_runtime(), 1);
var SubagentHistoryMessage = ({
  item,
  terminalWidth
}) => /* @__PURE__ */ (0, import_jsx_runtime40.jsxs)(Box_default, { flexDirection: "column", width: terminalWidth, marginBottom: 1, children: [
  /* @__PURE__ */ (0, import_jsx_runtime40.jsx)(Box_default, { marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime40.jsxs)(Text, { bold: true, color: "cyan", children: [
    "\u{1F916} ",
    item.agentName,
    " Trace (",
    item.history.length,
    " items)"
  ] }) }),
  item.history.map((activity) => /* @__PURE__ */ (0, import_jsx_runtime40.jsx)(Box_default, { marginLeft: 2, marginBottom: 0, children: /* @__PURE__ */ (0, import_jsx_runtime40.jsxs)(Text, { color: activity.type === "thought" ? "gray" : "white", children: [
    activity.type === "thought" ? "\u{1F9E0}" : "\u{1F6E0}\uFE0F",
    " ",
    activity.content,
    activity.status === "running" && " (Running...)",
    activity.status === "completed" && " \u2705",
    activity.status === "error" && " \u274C"
  ] }) }, activity.id))
] });

// packages/cli/src/ui/components/AboutBox.tsx
var import_jsx_runtime41 = __toESM(require_jsx_runtime(), 1);
var AboutBox = ({
  cliVersion,
  osVersion,
  sandboxEnv,
  modelVersion,
  selectedAuthType,
  gcpProject,
  ideClient,
  userEmail,
  tier
}) => {
  const settings = useSettings();
  const showUserIdentity = settings.merged.ui.showUserIdentity;
  return /* @__PURE__ */ (0, import_jsx_runtime41.jsxs)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: theme.border.default,
      flexDirection: "column",
      padding: 1,
      marginY: 1,
      width: "100%",
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Box_default, { marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Text, { bold: true, color: theme.text.accent, children: "About Gemini CLI" }) }),
        /* @__PURE__ */ (0, import_jsx_runtime41.jsxs)(Box_default, { flexDirection: "row", children: [
          /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Box_default, { width: "35%", children: /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Text, { bold: true, color: theme.text.link, children: "CLI Version" }) }),
          /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Text, { color: theme.text.primary, children: cliVersion }) })
        ] }),
        GIT_COMMIT_INFO && !["N/A"].includes(GIT_COMMIT_INFO) && /* @__PURE__ */ (0, import_jsx_runtime41.jsxs)(Box_default, { flexDirection: "row", children: [
          /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Box_default, { width: "35%", children: /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Text, { bold: true, color: theme.text.link, children: "Git Commit" }) }),
          /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Text, { color: theme.text.primary, children: GIT_COMMIT_INFO }) })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime41.jsxs)(Box_default, { flexDirection: "row", children: [
          /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Box_default, { width: "35%", children: /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Text, { bold: true, color: theme.text.link, children: "Model" }) }),
          /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Text, { color: theme.text.primary, children: getDisplayString(modelVersion) }) })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime41.jsxs)(Box_default, { flexDirection: "row", children: [
          /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Box_default, { width: "35%", children: /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Text, { bold: true, color: theme.text.link, children: "Sandbox" }) }),
          /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Text, { color: theme.text.primary, children: sandboxEnv }) })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime41.jsxs)(Box_default, { flexDirection: "row", children: [
          /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Box_default, { width: "35%", children: /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Text, { bold: true, color: theme.text.link, children: "OS" }) }),
          /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Text, { color: theme.text.primary, children: osVersion }) })
        ] }),
        showUserIdentity && /* @__PURE__ */ (0, import_jsx_runtime41.jsxs)(Box_default, { flexDirection: "row", children: [
          /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Box_default, { width: "35%", children: /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Text, { bold: true, color: theme.text.link, children: "Auth Method" }) }),
          /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Text, { color: theme.text.primary, children: selectedAuthType.startsWith("oauth") ? userEmail ? `Signed in with Google (${userEmail})` : "Signed in with Google" : selectedAuthType }) })
        ] }),
        showUserIdentity && tier && /* @__PURE__ */ (0, import_jsx_runtime41.jsxs)(Box_default, { flexDirection: "row", children: [
          /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Box_default, { width: "35%", children: /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Text, { bold: true, color: theme.text.link, children: "Tier" }) }),
          /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Text, { color: theme.text.primary, children: tier }) })
        ] }),
        gcpProject && /* @__PURE__ */ (0, import_jsx_runtime41.jsxs)(Box_default, { flexDirection: "row", children: [
          /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Box_default, { width: "35%", children: /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Text, { bold: true, color: theme.text.link, children: "GCP Project" }) }),
          /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Text, { color: theme.text.primary, children: gcpProject }) })
        ] }),
        ideClient && /* @__PURE__ */ (0, import_jsx_runtime41.jsxs)(Box_default, { flexDirection: "row", children: [
          /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Box_default, { width: "35%", children: /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Text, { bold: true, color: theme.text.link, children: "IDE Client" }) }),
          /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Text, { color: theme.text.primary, children: ideClient }) })
        ] })
      ]
    }
  );
};

// node_modules/ink-gradient/dist/index.js
var import_react35 = __toESM(require_react(), 1);
var import_prop_types = __toESM(require_prop_types(), 1);
var import_gradient_string = __toESM(require_gradient_string(), 1);
var Gradient = (props) => {
  if (props.name && props.colors) {
    throw new Error("The `name` and `colors` props are mutually exclusive");
  }
  let gradient;
  if (props.name) {
    gradient = import_gradient_string.default[props.name];
  } else if (props.colors) {
    gradient = (0, import_gradient_string.default)(props.colors);
  } else {
    throw new Error("Either `name` or `colors` prop must be provided");
  }
  const applyGradient = (text) => gradient.multiline(stripAnsi(text));
  return import_react35.default.createElement(Transform, { transform: applyGradient }, props.children);
};
Gradient.propTypes = {
  children: import_prop_types.default.oneOfType([
    import_prop_types.default.arrayOf(import_prop_types.default.node),
    import_prop_types.default.node
  ]).isRequired,
  name: import_prop_types.default.oneOf([
    "cristal",
    "teen",
    "mind",
    "morning",
    "vice",
    "passion",
    "fruit",
    "instagram",
    "atlas",
    "retro",
    "summer",
    "pastel",
    "rainbow"
  ]),
  colors: import_prop_types.default.arrayOf(import_prop_types.default.oneOfType([
    import_prop_types.default.string,
    import_prop_types.default.object
  ]))
};
var dist_default = Gradient;

// packages/cli/src/ui/components/ThemedGradient.tsx
var import_jsx_runtime42 = __toESM(require_jsx_runtime(), 1);
var ThemedGradient = ({ children, ...props }) => {
  const gradient = theme.ui.gradient;
  if (gradient && gradient.length >= 2) {
    return /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(dist_default, { colors: gradient, children: /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(Text, { ...props, children }) });
  }
  if (gradient && gradient.length === 1) {
    return /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(Text, { color: gradient[0], ...props, children });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(Text, { color: theme.text.accent, ...props, children });
};

// packages/cli/src/ui/contexts/SessionContext.tsx
var import_react36 = __toESM(require_react(), 1);
var import_jsx_runtime43 = __toESM(require_jsx_runtime(), 1);
function areModelMetricsEqual(a, b) {
  if (a.api.totalRequests !== b.api.totalRequests || a.api.totalErrors !== b.api.totalErrors || a.api.totalLatencyMs !== b.api.totalLatencyMs) {
    return false;
  }
  if (a.tokens.input !== b.tokens.input || a.tokens.prompt !== b.tokens.prompt || a.tokens.candidates !== b.tokens.candidates || a.tokens.total !== b.tokens.total || a.tokens.cached !== b.tokens.cached || a.tokens.thoughts !== b.tokens.thoughts || a.tokens.tool !== b.tokens.tool) {
    return false;
  }
  return true;
}
function areToolCallStatsEqual(a, b) {
  if (a.count !== b.count || a.success !== b.success || a.fail !== b.fail || a.durationMs !== b.durationMs) {
    return false;
  }
  if (a.decisions["accept" /* ACCEPT */] !== b.decisions["accept" /* ACCEPT */] || a.decisions["reject" /* REJECT */] !== b.decisions["reject" /* REJECT */] || a.decisions["modify" /* MODIFY */] !== b.decisions["modify" /* MODIFY */] || a.decisions["auto_accept" /* AUTO_ACCEPT */] !== b.decisions["auto_accept" /* AUTO_ACCEPT */]) {
    return false;
  }
  return true;
}
function areMetricsEqual(a, b) {
  if (a === b) return true;
  if (!a || !b) return false;
  if (a.files.totalLinesAdded !== b.files.totalLinesAdded || a.files.totalLinesRemoved !== b.files.totalLinesRemoved) {
    return false;
  }
  const toolsA = a.tools;
  const toolsB = b.tools;
  if (toolsA.totalCalls !== toolsB.totalCalls || toolsA.totalSuccess !== toolsB.totalSuccess || toolsA.totalFail !== toolsB.totalFail || toolsA.totalDurationMs !== toolsB.totalDurationMs) {
    return false;
  }
  if (toolsA.totalDecisions["accept" /* ACCEPT */] !== toolsB.totalDecisions["accept" /* ACCEPT */] || toolsA.totalDecisions["reject" /* REJECT */] !== toolsB.totalDecisions["reject" /* REJECT */] || toolsA.totalDecisions["modify" /* MODIFY */] !== toolsB.totalDecisions["modify" /* MODIFY */] || toolsA.totalDecisions["auto_accept" /* AUTO_ACCEPT */] !== toolsB.totalDecisions["auto_accept" /* AUTO_ACCEPT */]) {
    return false;
  }
  const toolsByNameAKeys = Object.keys(toolsA.byName);
  const toolsByNameBKeys = Object.keys(toolsB.byName);
  if (toolsByNameAKeys.length !== toolsByNameBKeys.length) return false;
  for (const key of toolsByNameAKeys) {
    const toolA = toolsA.byName[key];
    const toolB = toolsB.byName[key];
    if (!toolB || !areToolCallStatsEqual(toolA, toolB)) {
      return false;
    }
  }
  const modelsAKeys = Object.keys(a.models);
  const modelsBKeys = Object.keys(b.models);
  if (modelsAKeys.length !== modelsBKeys.length) return false;
  for (const key of modelsAKeys) {
    if (!b.models[key] || !areModelMetricsEqual(a.models[key], b.models[key])) {
      return false;
    }
  }
  return true;
}
var SessionStatsContext = (0, import_react36.createContext)(
  void 0
);
var SessionStatsProvider = ({
  children
}) => {
  const [stats, setStats] = (0, import_react36.useState)({
    sessionId,
    sessionStartTime: /* @__PURE__ */ new Date(),
    metrics: uiTelemetryService.getMetrics(),
    lastPromptTokenCount: 0,
    promptCount: 0
  });
  (0, import_react36.useEffect)(() => {
    const handleUpdate = ({
      metrics,
      lastPromptTokenCount
    }) => {
      setStats((prevState) => {
        if (prevState.lastPromptTokenCount === lastPromptTokenCount && areMetricsEqual(prevState.metrics, metrics)) {
          return prevState;
        }
        return {
          ...prevState,
          metrics,
          lastPromptTokenCount
        };
      });
    };
    const handleClear = (newSessionId) => {
      setStats((prevState) => ({
        ...prevState,
        sessionId: newSessionId || prevState.sessionId,
        sessionStartTime: /* @__PURE__ */ new Date(),
        promptCount: 0
      }));
    };
    uiTelemetryService.on("update", handleUpdate);
    uiTelemetryService.on("clear", handleClear);
    handleUpdate({
      metrics: uiTelemetryService.getMetrics(),
      lastPromptTokenCount: uiTelemetryService.getLastPromptTokenCount()
    });
    return () => {
      uiTelemetryService.off("update", handleUpdate);
      uiTelemetryService.off("clear", handleClear);
    };
  }, []);
  const startNewPrompt = (0, import_react36.useCallback)(() => {
    setStats((prevState) => ({
      ...prevState,
      promptCount: prevState.promptCount + 1
    }));
  }, []);
  const getPromptCount = (0, import_react36.useCallback)(
    () => stats.promptCount,
    [stats.promptCount]
  );
  const value = (0, import_react36.useMemo)(
    () => ({
      stats,
      startNewPrompt,
      getPromptCount
    }),
    [stats, startNewPrompt, getPromptCount]
  );
  return /* @__PURE__ */ (0, import_jsx_runtime43.jsx)(SessionStatsContext.Provider, { value, children });
};
var useSessionStats = () => {
  const context = (0, import_react36.useContext)(SessionStatsContext);
  if (context === void 0) {
    throw new Error(
      "useSessionStats must be used within a SessionStatsProvider"
    );
  }
  return context;
};

// packages/cli/src/ui/utils/computeStats.ts
function calculateErrorRate(metrics) {
  if (metrics.api.totalRequests === 0) {
    return 0;
  }
  return metrics.api.totalErrors / metrics.api.totalRequests * 100;
}
function calculateAverageLatency(metrics) {
  if (metrics.api.totalRequests === 0) {
    return 0;
  }
  return metrics.api.totalLatencyMs / metrics.api.totalRequests;
}
function calculateCacheHitRate(metrics) {
  if (metrics.tokens.prompt === 0) {
    return 0;
  }
  return metrics.tokens.cached / metrics.tokens.prompt * 100;
}
var computeSessionStats = (metrics) => {
  const { models, tools, files } = metrics;
  const totalApiTime = Object.values(models).reduce(
    (acc, model) => acc + model.api.totalLatencyMs,
    0
  );
  const totalToolTime = tools.totalDurationMs;
  const agentActiveTime = totalApiTime + totalToolTime;
  const apiTimePercent = agentActiveTime > 0 ? totalApiTime / agentActiveTime * 100 : 0;
  const toolTimePercent = agentActiveTime > 0 ? totalToolTime / agentActiveTime * 100 : 0;
  const totalCachedTokens = Object.values(models).reduce(
    (acc, model) => acc + model.tokens.cached,
    0
  );
  const totalInputTokens = Object.values(models).reduce(
    (acc, model) => acc + model.tokens.input,
    0
  );
  const totalPromptTokens = Object.values(models).reduce(
    (acc, model) => acc + model.tokens.prompt,
    0
  );
  const cacheEfficiency = totalPromptTokens > 0 ? totalCachedTokens / totalPromptTokens * 100 : 0;
  const totalDecisions = tools.totalDecisions.accept + tools.totalDecisions.reject + tools.totalDecisions.modify + tools.totalDecisions.auto_accept;
  const successRate = tools.totalCalls > 0 ? tools.totalSuccess / tools.totalCalls * 100 : 0;
  const agreementRate = totalDecisions > 0 ? (tools.totalDecisions.accept + tools.totalDecisions.auto_accept) / totalDecisions * 100 : 0;
  return {
    totalApiTime,
    totalToolTime,
    agentActiveTime,
    apiTimePercent,
    toolTimePercent,
    cacheEfficiency,
    totalDecisions,
    successRate,
    agreementRate,
    totalCachedTokens,
    totalInputTokens,
    totalPromptTokens,
    totalLinesAdded: files.totalLinesAdded,
    totalLinesRemoved: files.totalLinesRemoved
  };
};

// packages/cli/src/ui/components/StatsDisplay.tsx
var import_jsx_runtime44 = __toESM(require_jsx_runtime(), 1);
var StatRow = ({ title, children }) => /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Box_default, { children: [
  /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Box_default, { width: 28, children: /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Text, { color: theme.text.link, children: title }) }),
  children
] });
var SubStatRow = ({ title, children }) => /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Box_default, { paddingLeft: 2, children: [
  /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Box_default, { width: 26, children: /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Text, { color: theme.text.secondary, children: [
    "\xBB ",
    title
  ] }) }),
  children
] });
var Section = ({ title, children }) => /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Box_default, { flexDirection: "column", marginBottom: 1, children: [
  /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Text, { bold: true, color: theme.text.primary, children: title }),
  children
] });
var ModelUsageTable = ({ models }) => {
  const nameWidth = 28;
  const requestsWidth = 8;
  const inputTokensWidth = 14;
  const cacheReadsWidth = 14;
  const outputTokensWidth = 14;
  const rows = [];
  Object.entries(models).forEach(([name, metrics]) => {
    rows.push({
      name,
      displayName: name,
      requests: metrics.api.totalRequests,
      cachedTokens: metrics.tokens.cached.toLocaleString(),
      inputTokens: metrics.tokens.prompt.toLocaleString(),
      outputTokens: metrics.tokens.candidates.toLocaleString(),
      isSubRow: false
    });
    if (metrics.roles) {
      const roleEntries = Object.entries(metrics.roles).filter(
        (entry) => entry[1] !== void 0 && entry[1].totalRequests > 0
      );
      roleEntries.sort(([a], [b]) => {
        if (a === b) return 0;
        if (a === LlmRole.MAIN) return -1;
        if (b === LlmRole.MAIN) return 1;
        return a.localeCompare(b);
      });
      roleEntries.forEach(([role, roleMetrics]) => {
        rows.push({
          name: `${name}-${role}`,
          displayName: `  \u21B3 ${role}`,
          requests: roleMetrics.totalRequests,
          cachedTokens: roleMetrics.tokens.cached.toLocaleString(),
          inputTokens: roleMetrics.tokens.prompt.toLocaleString(),
          outputTokens: roleMetrics.tokens.candidates.toLocaleString(),
          isSubRow: true
        });
      });
    }
  });
  return /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Box_default, { flexDirection: "column", marginTop: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Text, { bold: true, color: theme.text.primary, children: "Model Usage" }),
    /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Text, { color: theme.text.secondary, children: "Use /model to view model quota information" }),
    /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Box_default, { height: 1 }),
    /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(
      Box_default,
      {
        borderBottom: true,
        borderStyle: "single",
        borderColor: theme.border.default,
        borderTop: false,
        borderLeft: false,
        borderRight: false,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Box_default, { width: nameWidth, children: /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Text, { bold: true, color: theme.text.secondary, children: "Model" }) }),
          /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Box_default, { width: requestsWidth, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Text, { bold: true, color: theme.text.secondary, children: "Reqs" }) }),
          /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Box_default, { width: inputTokensWidth, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Text, { bold: true, color: theme.text.secondary, children: "Input Tokens" }) }),
          /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Box_default, { width: cacheReadsWidth, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Text, { bold: true, color: theme.text.secondary, children: "Cache Reads" }) }),
          /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Box_default, { width: outputTokensWidth, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Text, { bold: true, color: theme.text.secondary, children: "Output Tokens" }) })
        ]
      }
    ),
    rows.map((row) => /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Box_default, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Box_default, { width: nameWidth, children: /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(
        Text,
        {
          color: row.isSubRow ? theme.text.secondary : theme.text.primary,
          wrap: "truncate-end",
          children: row.displayName
        }
      ) }),
      /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Box_default, { width: requestsWidth, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(
        Text,
        {
          color: row.isSubRow ? theme.text.secondary : theme.text.primary,
          children: row.requests
        }
      ) }),
      /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Box_default, { width: inputTokensWidth, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(
        Text,
        {
          color: row.isSubRow ? theme.text.secondary : theme.text.primary,
          children: row.inputTokens
        }
      ) }),
      /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Box_default, { width: cacheReadsWidth, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(
        Text,
        {
          color: row.isSubRow ? theme.text.secondary : theme.text.primary,
          children: row.cachedTokens
        }
      ) }),
      /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Box_default, { width: outputTokensWidth, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(
        Text,
        {
          color: row.isSubRow ? theme.text.secondary : theme.text.primary,
          children: row.outputTokens
        }
      ) })
    ] }, row.name))
  ] });
};
var StatsDisplay = ({
  duration,
  title,
  footer,
  selectedAuthType,
  userEmail,
  tier,
  creditBalance
}) => {
  const { stats } = useSessionStats();
  const { metrics } = stats;
  const { tools, files, models } = metrics;
  const computed = computeSessionStats(metrics);
  const settings = useSettings();
  const showUserIdentity = settings.merged.ui.showUserIdentity;
  const successThresholds = {
    green: TOOL_SUCCESS_RATE_HIGH,
    yellow: TOOL_SUCCESS_RATE_MEDIUM
  };
  const agreementThresholds = {
    green: USER_AGREEMENT_RATE_HIGH,
    yellow: USER_AGREEMENT_RATE_MEDIUM
  };
  const successColor = getStatusColor(computed.successRate, successThresholds);
  const agreementColor = getStatusColor(
    computed.agreementRate,
    agreementThresholds
  );
  const renderTitle = () => {
    if (title) {
      return /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(ThemedGradient, { bold: true, children: title });
    }
    return /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Text, { bold: true, color: theme.text.accent, children: "Session Stats" });
  };
  const renderFooter = () => {
    if (!footer) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(ThemedGradient, { bold: true, children: footer });
  };
  return /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: theme.border.default,
      flexDirection: "column",
      paddingTop: 1,
      paddingX: 2,
      overflow: "hidden",
      children: [
        renderTitle(),
        /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Box_default, { height: 1 }),
        /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Section, { title: "Interaction Summary", children: [
          /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(StatRow, { title: "Session ID:", children: /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Text, { color: theme.text.primary, children: stats.sessionId }) }),
          showUserIdentity && selectedAuthType && /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(StatRow, { title: "Auth Method:", children: /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Text, { color: theme.text.primary, children: selectedAuthType.startsWith("oauth") ? userEmail ? `Signed in with Google (${userEmail})` : "Signed in with Google" : selectedAuthType }) }),
          showUserIdentity && tier && /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(StatRow, { title: "Tier:", children: /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Text, { color: theme.text.primary, children: tier }) }),
          showUserIdentity && creditBalance != null && creditBalance >= 0 && /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(StatRow, { title: "Google AI Credits:", children: /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(
            Text,
            {
              color: creditBalance > 0 ? theme.text.primary : theme.text.secondary,
              children: creditBalance.toLocaleString()
            }
          ) }),
          /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(StatRow, { title: "Tool Calls:", children: /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Text, { color: theme.text.primary, children: [
            tools.totalCalls,
            " (",
            " ",
            /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Text, { color: theme.status.success, children: [
              "\u2713 ",
              tools.totalSuccess
            ] }),
            " ",
            /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Text, { color: theme.status.error, children: [
              "x ",
              tools.totalFail
            ] }),
            " )"
          ] }) }),
          /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(StatRow, { title: "Success Rate:", children: /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Text, { color: successColor, children: [
            computed.successRate.toFixed(1),
            "%"
          ] }) }),
          computed.totalDecisions > 0 && /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(StatRow, { title: "User Agreement:", children: /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Text, { color: agreementColor, children: [
            computed.agreementRate.toFixed(1),
            "%",
            " ",
            /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Text, { color: theme.text.secondary, children: [
              "(",
              computed.totalDecisions,
              " reviewed)"
            ] })
          ] }) }),
          files && (files.totalLinesAdded > 0 || files.totalLinesRemoved > 0) && /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(StatRow, { title: "Code Changes:", children: /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Text, { color: theme.text.primary, children: [
            /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Text, { color: theme.status.success, children: [
              "+",
              files.totalLinesAdded
            ] }),
            " ",
            /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Text, { color: theme.status.error, children: [
              "-",
              files.totalLinesRemoved
            ] })
          ] }) })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Section, { title: "Performance", children: [
          /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(StatRow, { title: "Wall Time:", children: /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Text, { color: theme.text.primary, children: duration }) }),
          /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(StatRow, { title: "Agent Active:", children: /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Text, { color: theme.text.primary, children: formatDuration(computed.agentActiveTime) }) }),
          /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(SubStatRow, { title: "API Time:", children: /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Text, { color: theme.text.primary, children: [
            formatDuration(computed.totalApiTime),
            " ",
            /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Text, { color: theme.text.secondary, children: [
              "(",
              computed.apiTimePercent.toFixed(1),
              "%)"
            ] })
          ] }) }),
          /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(SubStatRow, { title: "Tool Time:", children: /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Text, { color: theme.text.primary, children: [
            formatDuration(computed.totalToolTime),
            " ",
            /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Text, { color: theme.text.secondary, children: [
              "(",
              computed.toolTimePercent.toFixed(1),
              "%)"
            ] })
          ] }) })
        ] }),
        Object.keys(models).length > 0 && /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(ModelUsageTable, { models }),
        renderFooter()
      ]
    }
  );
};

// packages/cli/src/ui/components/Table.tsx
var import_jsx_runtime45 = __toESM(require_jsx_runtime(), 1);
function Table({ data, columns }) {
  return /* @__PURE__ */ (0, import_jsx_runtime45.jsxs)(Box_default, { flexDirection: "column", children: [
    /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(Box_default, { flexDirection: "row", children: columns.map((col, index) => /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(
      Box_default,
      {
        width: col.width,
        flexGrow: col.flexGrow,
        flexShrink: col.flexShrink,
        flexBasis: col.flexBasis ?? (col.width ? void 0 : 0),
        paddingRight: 1,
        children: typeof col.header === "string" ? /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(Text, { bold: true, color: theme.text.primary, children: col.header }) : col.header
      },
      `header-${index}`
    )) }),
    /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(
      Box_default,
      {
        borderStyle: "single",
        borderBottom: true,
        borderTop: false,
        borderLeft: false,
        borderRight: false,
        borderColor: theme.border.default,
        marginBottom: 0
      }
    ),
    data.map((item, rowIndex) => /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(Box_default, { flexDirection: "row", children: columns.map((col, colIndex) => /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(
      Box_default,
      {
        width: col.width,
        flexGrow: col.flexGrow,
        flexShrink: col.flexShrink,
        flexBasis: col.flexBasis ?? (col.width ? void 0 : 0),
        paddingRight: 1,
        children: col.renderCell ? col.renderCell(item) : /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(Text, { color: theme.text.primary, children: String(item[col.key]) })
      },
      `cell-${rowIndex}-${colIndex}`
    )) }, `row-${rowIndex}`))
  ] });
}

// packages/cli/src/ui/components/QuotaStatsInfo.tsx
var import_jsx_runtime46 = __toESM(require_jsx_runtime(), 1);
var QuotaStatsInfo = ({
  remaining,
  limit,
  resetTime,
  showDetails = true
}) => {
  if (remaining === void 0 || limit === void 0 || limit === 0) {
    return null;
  }
  const usedPercentage = 100 - remaining / limit * 100;
  const color = getUsedStatusColor(usedPercentage, {
    warning: QUOTA_USED_WARNING_THRESHOLD,
    critical: QUOTA_USED_CRITICAL_THRESHOLD
  });
  return /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)(Box_default, { flexDirection: "column", marginTop: 0, marginBottom: 0, children: [
    /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Text, { color, children: remaining === 0 ? `Limit reached${resetTime ? `, resets in ${formatResetTime(resetTime, "terse")}` : ""}` : `${usedPercentage.toFixed(0)}% used${resetTime ? ` (Limit resets in ${formatResetTime(resetTime, "terse")})` : ""}` }),
    showDetails && /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)(import_jsx_runtime46.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)(Text, { color: theme.text.primary, children: [
        "Usage limit: ",
        limit.toLocaleString()
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Text, { color: theme.text.primary, children: "Usage limits span all sessions and reset daily." }),
      remaining === 0 && /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Text, { color: theme.text.primary, children: "Please /auth to upgrade or switch to an API key to continue." })
    ] })
  ] });
};

// packages/cli/src/ui/components/ModelStatsDisplay.tsx
var import_jsx_runtime47 = __toESM(require_jsx_runtime(), 1);
var ModelStatsDisplay = ({
  selectedAuthType,
  userEmail,
  tier,
  currentModel,
  quotaStats
}) => {
  const { stats } = useSessionStats();
  const pooledRemaining = quotaStats?.remaining;
  const pooledLimit = quotaStats?.limit;
  const pooledResetTime = quotaStats?.resetTime;
  const { models } = stats.metrics;
  const settings = useSettings();
  const showUserIdentity = settings.merged.ui.showUserIdentity;
  const activeModels = Object.entries(models).filter(
    ([, metrics]) => metrics.api.totalRequests > 0
  );
  if (activeModels.length === 0) {
    return /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(
      Box_default,
      {
        borderStyle: "round",
        borderColor: theme.border.default,
        paddingTop: 1,
        paddingX: 2,
        children: /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(Text, { color: theme.text.primary, children: "No API calls have been made in this session." })
      }
    );
  }
  const modelNames = activeModels.map(([name]) => name);
  const hasThoughts = activeModels.some(
    ([, metrics]) => metrics.tokens.thoughts > 0
  );
  const hasTool = activeModels.some(([, metrics]) => metrics.tokens.tool > 0);
  const hasCached = activeModels.some(
    ([, metrics]) => metrics.tokens.cached > 0
  );
  const allRoles = [
    ...new Set(
      activeModels.flatMap(([, metrics]) => Object.keys(metrics.roles ?? {}))
    )
  ].filter((role) => {
    const validRoles = Object.values(LlmRole);
    return validRoles.includes(role);
  }).sort((a, b) => {
    if (a === b) return 0;
    if (a === LlmRole.MAIN) return -1;
    if (b === LlmRole.MAIN) return 1;
    return a.localeCompare(b);
  });
  const createRow = (metric, getValue, options = {}) => {
    const row = {
      metric,
      isSection: options.isSection,
      isSubtle: options.isSubtle
    };
    activeModels.forEach(([name, metrics]) => {
      row[name] = getValue(metrics);
    });
    return row;
  };
  const rows = [];
  rows.push({ metric: "API", isSection: true });
  rows.push(createRow("Requests", (m) => m.api.totalRequests.toLocaleString()));
  rows.push(
    createRow("Errors", (m) => {
      const errorRate = calculateErrorRate(m);
      return /* @__PURE__ */ (0, import_jsx_runtime47.jsxs)(
        Text,
        {
          color: m.api.totalErrors > 0 ? theme.status.error : theme.text.primary,
          children: [
            m.api.totalErrors.toLocaleString(),
            " (",
            errorRate.toFixed(1),
            "%)"
          ]
        }
      );
    })
  );
  rows.push(
    createRow("Avg Latency", (m) => formatDuration(calculateAverageLatency(m)))
  );
  rows.push({ metric: "" });
  rows.push({ metric: "Tokens", isSection: true });
  rows.push(
    createRow("Total", (m) => /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(Text, { color: theme.text.secondary, children: m.tokens.total.toLocaleString() }))
  );
  rows.push(
    createRow(
      "Input",
      (m) => /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(Text, { color: theme.text.primary, children: m.tokens.input.toLocaleString() }),
      { isSubtle: true }
    )
  );
  if (hasCached) {
    rows.push(
      createRow(
        "Cache Reads",
        (m) => {
          const cacheHitRate = calculateCacheHitRate(m);
          return /* @__PURE__ */ (0, import_jsx_runtime47.jsxs)(Text, { color: theme.text.secondary, children: [
            m.tokens.cached.toLocaleString(),
            " (",
            cacheHitRate.toFixed(1),
            "%)"
          ] });
        },
        { isSubtle: true }
      )
    );
  }
  if (hasThoughts) {
    rows.push(
      createRow(
        "Thoughts",
        (m) => /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(Text, { color: theme.text.primary, children: m.tokens.thoughts.toLocaleString() }),
        { isSubtle: true }
      )
    );
  }
  if (hasTool) {
    rows.push(
      createRow(
        "Tool",
        (m) => /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(Text, { color: theme.text.primary, children: m.tokens.tool.toLocaleString() }),
        { isSubtle: true }
      )
    );
  }
  rows.push(
    createRow(
      "Output",
      (m) => /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(Text, { color: theme.text.primary, children: m.tokens.candidates.toLocaleString() }),
      { isSubtle: true }
    )
  );
  if (allRoles.length > 0) {
    rows.push({ metric: "" });
    rows.push({ metric: "Roles", isSection: true });
    allRoles.forEach((role) => {
      const roleHeaderRow = {
        metric: role,
        isSection: true,
        color: theme.text.primary
      };
      rows.push(roleHeaderRow);
      const addRoleMetric = (metric, getValue) => {
        const row = {
          metric,
          isSubtle: true
        };
        activeModels.forEach(([name, metrics]) => {
          const roleMetrics = metrics.roles?.[role];
          if (roleMetrics) {
            row[name] = getValue(roleMetrics);
          } else {
            row[name] = /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(Text, { color: theme.text.secondary, children: "-" });
          }
        });
        rows.push(row);
      };
      addRoleMetric("Requests", (r2) => r2.totalRequests.toLocaleString());
      addRoleMetric("Input", (r2) => /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(Text, { color: theme.text.primary, children: r2.tokens.input.toLocaleString() }));
      addRoleMetric("Output", (r2) => /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(Text, { color: theme.text.primary, children: r2.tokens.candidates.toLocaleString() }));
      addRoleMetric("Cache Reads", (r2) => /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(Text, { color: theme.text.secondary, children: r2.tokens.cached.toLocaleString() }));
    });
  }
  const columns = [
    {
      key: "metric",
      header: "Metric",
      width: 28,
      renderCell: (row) => /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(
        Text,
        {
          bold: row.isSection,
          color: row.isSection ? theme.text.primary : theme.text.link,
          children: row.isSubtle ? `  \u21B3 ${row.metric}` : row.metric
        }
      )
    },
    ...modelNames.map((name) => ({
      key: name,
      header: name,
      flexGrow: 1,
      renderCell: (row) => {
        if (row.isSection) return null;
        const val = row[name];
        if (val === void 0 || val === null) return null;
        if (typeof val === "string" || typeof val === "number") {
          return /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(Text, { color: theme.text.primary, children: val });
        }
        return val;
      }
    }))
  ];
  const isAuto = currentModel && isAutoModel(currentModel);
  const statsTitle = isAuto ? `${getDisplayString(currentModel)} Stats For Nerds` : "Model Stats For Nerds";
  return /* @__PURE__ */ (0, import_jsx_runtime47.jsxs)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: theme.border.default,
      flexDirection: "column",
      paddingTop: 1,
      paddingX: 2,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(Text, { bold: true, color: theme.text.accent, children: statsTitle }),
        /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(Box_default, { height: 1 }),
        showUserIdentity && selectedAuthType && /* @__PURE__ */ (0, import_jsx_runtime47.jsxs)(Box_default, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(Box_default, { width: 28, children: /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(Text, { color: theme.text.link, children: "Auth Method:" }) }),
          /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(Text, { color: theme.text.primary, children: selectedAuthType.startsWith("oauth") ? userEmail ? `Signed in with Google (${userEmail})` : "Signed in with Google" : selectedAuthType })
        ] }),
        showUserIdentity && tier && /* @__PURE__ */ (0, import_jsx_runtime47.jsxs)(Box_default, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(Box_default, { width: 28, children: /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(Text, { color: theme.text.link, children: "Tier:" }) }),
          /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(Text, { color: theme.text.primary, children: tier })
        ] }),
        isAuto && pooledRemaining !== void 0 && pooledLimit !== void 0 && pooledLimit > 0 && /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(
          QuotaStatsInfo,
          {
            remaining: pooledRemaining,
            limit: pooledLimit,
            resetTime: pooledResetTime
          }
        ),
        (showUserIdentity || isAuto) && /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(Box_default, { height: 1 }),
        /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(Table, { data: rows, columns })
      ]
    }
  );
};

// packages/cli/src/ui/components/ToolStatsDisplay.tsx
var import_jsx_runtime48 = __toESM(require_jsx_runtime(), 1);
var TOOL_NAME_COL_WIDTH = 25;
var CALLS_COL_WIDTH = 8;
var SUCCESS_RATE_COL_WIDTH = 15;
var AVG_DURATION_COL_WIDTH = 15;
var StatRow2 = ({ name, stats }) => {
  const successRate = stats.count > 0 ? stats.success / stats.count * 100 : 0;
  const avgDuration = stats.count > 0 ? stats.durationMs / stats.count : 0;
  const successColor = getStatusColor(successRate, {
    green: TOOL_SUCCESS_RATE_HIGH,
    yellow: TOOL_SUCCESS_RATE_MEDIUM
  });
  return /* @__PURE__ */ (0, import_jsx_runtime48.jsxs)(Box_default, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Box_default, { width: TOOL_NAME_COL_WIDTH, children: /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Text, { color: theme.text.link, children: name }) }),
    /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Box_default, { width: CALLS_COL_WIDTH, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Text, { color: theme.text.primary, children: stats.count }) }),
    /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Box_default, { width: SUCCESS_RATE_COL_WIDTH, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime48.jsxs)(Text, { color: successColor, children: [
      successRate.toFixed(1),
      "%"
    ] }) }),
    /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Box_default, { width: AVG_DURATION_COL_WIDTH, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Text, { color: theme.text.primary, children: formatDuration(avgDuration) }) })
  ] });
};
var ToolStatsDisplay = () => {
  const { stats } = useSessionStats();
  const { tools } = stats.metrics;
  const activeTools = Object.entries(tools.byName).filter(
    ([, metrics]) => metrics.count > 0
  );
  if (activeTools.length === 0) {
    return /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(
      Box_default,
      {
        borderStyle: "round",
        borderColor: theme.border.default,
        paddingTop: 1,
        paddingX: 2,
        children: /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Text, { color: theme.text.primary, children: "No tool calls have been made in this session." })
      }
    );
  }
  const totalDecisions = Object.values(tools.byName).reduce(
    (acc, tool) => {
      acc.accept += tool.decisions.accept;
      acc.reject += tool.decisions.reject;
      acc.modify += tool.decisions.modify;
      return acc;
    },
    { accept: 0, reject: 0, modify: 0 }
  );
  const totalReviewed = totalDecisions.accept + totalDecisions.reject + totalDecisions.modify;
  const agreementRate = totalReviewed > 0 ? totalDecisions.accept / totalReviewed * 100 : 0;
  const agreementColor = getStatusColor(agreementRate, {
    green: USER_AGREEMENT_RATE_HIGH,
    yellow: USER_AGREEMENT_RATE_MEDIUM
  });
  return /* @__PURE__ */ (0, import_jsx_runtime48.jsxs)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: theme.border.default,
      flexDirection: "column",
      paddingTop: 1,
      paddingX: 2,
      width: 70,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Text, { bold: true, color: theme.text.accent, children: "Tool Stats For Nerds" }),
        /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Box_default, { height: 1 }),
        /* @__PURE__ */ (0, import_jsx_runtime48.jsxs)(Box_default, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Box_default, { width: TOOL_NAME_COL_WIDTH, children: /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Text, { bold: true, color: theme.text.primary, children: "Tool Name" }) }),
          /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Box_default, { width: CALLS_COL_WIDTH, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Text, { bold: true, color: theme.text.primary, children: "Calls" }) }),
          /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Box_default, { width: SUCCESS_RATE_COL_WIDTH, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Text, { bold: true, color: theme.text.primary, children: "Success Rate" }) }),
          /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Box_default, { width: AVG_DURATION_COL_WIDTH, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Text, { bold: true, color: theme.text.primary, children: "Avg Duration" }) })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(
          Box_default,
          {
            borderStyle: "single",
            borderBottom: true,
            borderTop: false,
            borderLeft: false,
            borderRight: false,
            borderColor: theme.border.default,
            width: "100%"
          }
        ),
        activeTools.map(([name, stats2]) => /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(StatRow2, { name, stats: stats2 }, name)),
        /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Box_default, { height: 1 }),
        /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Text, { bold: true, color: theme.text.primary, children: "User Decision Summary" }),
        /* @__PURE__ */ (0, import_jsx_runtime48.jsxs)(Box_default, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(
            Box_default,
            {
              width: TOOL_NAME_COL_WIDTH + CALLS_COL_WIDTH + SUCCESS_RATE_COL_WIDTH,
              children: /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Text, { color: theme.text.link, children: "Total Reviewed Suggestions:" })
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Box_default, { width: AVG_DURATION_COL_WIDTH, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Text, { color: theme.text.primary, children: totalReviewed }) })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime48.jsxs)(Box_default, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(
            Box_default,
            {
              width: TOOL_NAME_COL_WIDTH + CALLS_COL_WIDTH + SUCCESS_RATE_COL_WIDTH,
              children: /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Text, { color: theme.text.primary, children: " \xBB Accepted:" })
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Box_default, { width: AVG_DURATION_COL_WIDTH, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Text, { color: theme.status.success, children: totalDecisions.accept }) })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime48.jsxs)(Box_default, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(
            Box_default,
            {
              width: TOOL_NAME_COL_WIDTH + CALLS_COL_WIDTH + SUCCESS_RATE_COL_WIDTH,
              children: /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Text, { color: theme.text.primary, children: " \xBB Rejected:" })
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Box_default, { width: AVG_DURATION_COL_WIDTH, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Text, { color: theme.status.error, children: totalDecisions.reject }) })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime48.jsxs)(Box_default, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(
            Box_default,
            {
              width: TOOL_NAME_COL_WIDTH + CALLS_COL_WIDTH + SUCCESS_RATE_COL_WIDTH,
              children: /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Text, { color: theme.text.primary, children: " \xBB Modified:" })
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Box_default, { width: AVG_DURATION_COL_WIDTH, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Text, { color: theme.status.warning, children: totalDecisions.modify }) })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(
          Box_default,
          {
            borderStyle: "single",
            borderBottom: true,
            borderTop: false,
            borderLeft: false,
            borderRight: false,
            borderColor: theme.border.default,
            width: "100%"
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime48.jsxs)(Box_default, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(
            Box_default,
            {
              width: TOOL_NAME_COL_WIDTH + CALLS_COL_WIDTH + SUCCESS_RATE_COL_WIDTH,
              children: /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Text, { color: theme.text.primary, children: " Overall Agreement Rate:" })
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Box_default, { width: AVG_DURATION_COL_WIDTH, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Text, { bold: true, color: totalReviewed > 0 ? agreementColor : void 0, children: totalReviewed > 0 ? `${agreementRate.toFixed(1)}%` : "--" }) })
        ] })
      ]
    }
  );
};

// packages/cli/src/ui/components/SessionSummaryDisplay.tsx
var import_jsx_runtime49 = __toESM(require_jsx_runtime(), 1);
var SessionSummaryDisplay = ({
  duration
}) => {
  const { stats } = useSessionStats();
  const config = useConfig();
  const { shell: shell2 } = getShellConfiguration();
  const worktreeSettings = config.getWorktreeSettings();
  const escapedSessionId = escapeShellArg(stats.sessionId, shell2);
  let footer = `To resume this session: gemini --resume ${escapedSessionId}`;
  if (worktreeSettings) {
    footer = `To resume work in this worktree: cd ${escapeShellArg(worktreeSettings.path, shell2)} && gemini --resume ${escapedSessionId}
To remove manually: git worktree remove ${escapeShellArg(worktreeSettings.path, shell2)}`;
  }
  return /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(
    StatsDisplay,
    {
      title: "Agent powering down. Goodbye!",
      duration,
      footer
    }
  );
};

// packages/cli/src/ui/components/Help.tsx
var import_jsx_runtime50 = __toESM(require_jsx_runtime(), 1);
var Help = ({ commands }) => /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)(
  Box_default,
  {
    flexDirection: "column",
    marginBottom: 1,
    borderColor: theme.border.default,
    borderStyle: "round",
    padding: 1,
    children: [
      /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Text, { bold: true, color: theme.text.primary, children: "Basics:" }),
      /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)(Text, { color: theme.text.primary, children: [
        /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Text, { bold: true, color: theme.text.accent, children: "Add context" }),
        ": Use",
        " ",
        /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Text, { bold: true, color: theme.text.accent, children: "@" }),
        " ",
        "to specify files for context (e.g.,",
        " ",
        /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Text, { bold: true, color: theme.text.accent, children: "@src/myFile.ts" }),
        ") to target specific files or folders."
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)(Text, { color: theme.text.primary, children: [
        /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Text, { bold: true, color: theme.text.accent, children: "Shell mode" }),
        ": Execute shell commands via",
        " ",
        /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Text, { bold: true, color: theme.text.accent, children: "!" }),
        " ",
        "(e.g.,",
        " ",
        /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Text, { bold: true, color: theme.text.accent, children: "!npm run start" }),
        ") or use natural language (e.g.",
        " ",
        /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Text, { bold: true, color: theme.text.accent, children: "start server" }),
        ")."
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Box_default, { height: 1 }),
      /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Text, { bold: true, color: theme.text.primary, children: "Commands:" }),
      commands.filter((command) => command.description && !command.hidden).map((command) => /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)(Box_default, { flexDirection: "column", children: [
        /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)(Text, { color: theme.text.primary, children: [
          /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)(Text, { bold: true, color: theme.text.accent, children: [
            " ",
            "/",
            command.name
          ] }),
          command.kind === "mcp-prompt" /* MCP_PROMPT */ && /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Text, { color: theme.text.secondary, children: " [MCP]" }),
          command.description && " - " + sanitizeForDisplay(command.description, 100)
        ] }),
        command.subCommands && command.subCommands.filter((subCommand) => !subCommand.hidden).map((subCommand) => /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)(Text, { color: theme.text.primary, children: [
          /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)(Text, { bold: true, color: theme.text.accent, children: [
            "   ",
            subCommand.name
          ] }),
          subCommand.description && " - " + sanitizeForDisplay(subCommand.description, 100)
        ] }, subCommand.name))
      ] }, command.name)),
      /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)(Text, { color: theme.text.primary, children: [
        /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)(Text, { bold: true, color: theme.text.accent, children: [
          " ",
          "!",
          " "
        ] }),
        "- shell command"
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)(Text, { color: theme.text.primary, children: [
        /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Text, { color: theme.text.secondary, children: "[MCP]" }),
        " - Model Context Protocol command (from external servers)"
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Box_default, { height: 1 }),
      /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Text, { bold: true, color: theme.text.primary, children: "Keyboard Shortcuts:" }),
      /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)(Text, { color: theme.text.primary, children: [
        /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)(Text, { bold: true, color: theme.text.accent, children: [
          formatCommand("cursor.wordLeft" /* MOVE_WORD_LEFT */),
          "/",
          formatCommand("cursor.wordRight" /* MOVE_WORD_RIGHT */)
        ] }),
        " ",
        "- Jump through words in the input"
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)(Text, { color: theme.text.primary, children: [
        /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Text, { bold: true, color: theme.text.accent, children: formatCommand("basic.quit" /* QUIT */) }),
        " ",
        "- Quit application"
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)(Text, { color: theme.text.primary, children: [
        /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Text, { bold: true, color: theme.text.accent, children: formatCommand("input.newline" /* NEWLINE */) }),
        " ",
        "- New line"
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)(Text, { color: theme.text.primary, children: [
        /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Text, { bold: true, color: theme.text.accent, children: formatCommand("app.clearScreen" /* CLEAR_SCREEN */) }),
        " ",
        "- Clear the screen"
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)(Text, { color: theme.text.primary, children: [
        /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Text, { bold: true, color: theme.text.accent, children: formatCommand("app.toggleCopyMode" /* TOGGLE_COPY_MODE */) }),
        " ",
        "- Enter selection mode to copy text"
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)(Text, { color: theme.text.primary, children: [
        /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Text, { bold: true, color: theme.text.accent, children: formatCommand("input.openExternalEditor" /* OPEN_EXTERNAL_EDITOR */) }),
        " ",
        "- Open input in external editor"
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)(Text, { color: theme.text.primary, children: [
        /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Text, { bold: true, color: theme.text.accent, children: formatCommand("app.toggleYolo" /* TOGGLE_YOLO */) }),
        " ",
        "- Toggle YOLO mode"
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)(Text, { color: theme.text.primary, children: [
        /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Text, { bold: true, color: theme.text.accent, children: formatCommand("input.submit" /* SUBMIT */) }),
        " ",
        "- Send message"
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)(Text, { color: theme.text.primary, children: [
        /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Text, { bold: true, color: theme.text.accent, children: formatCommand("basic.cancel" /* ESCAPE */) }),
        " ",
        "- Cancel operation / Clear input (double press)"
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)(Text, { color: theme.text.primary, children: [
        /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)(Text, { bold: true, color: theme.text.accent, children: [
          formatCommand("scroll.pageUp" /* PAGE_UP */),
          "/",
          formatCommand("scroll.pageDown" /* PAGE_DOWN */)
        ] }),
        " ",
        "- Scroll page up/down"
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)(Text, { color: theme.text.primary, children: [
        /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Text, { bold: true, color: theme.text.accent, children: formatCommand("app.cycleApprovalMode" /* CYCLE_APPROVAL_MODE */) }),
        " ",
        "- Toggle auto-accepting edits"
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)(Text, { color: theme.text.primary, children: [
        /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)(Text, { bold: true, color: theme.text.accent, children: [
          formatCommand("history.previous" /* HISTORY_UP */),
          "/",
          formatCommand("history.next" /* HISTORY_DOWN */)
        ] }),
        " ",
        "- Cycle through your prompt history"
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Box_default, { height: 1 }),
      /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)(Text, { color: theme.text.primary, children: [
        "For a full list of shortcuts, see",
        " ",
        /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Text, { bold: true, color: theme.text.accent, children: KEYBOARD_SHORTCUTS_URL })
      ] })
    ]
  }
);

// packages/cli/src/ui/components/views/ExtensionsList.tsx
var import_jsx_runtime51 = __toESM(require_jsx_runtime(), 1);
var ExtensionsList = ({ extensions }) => {
  const { extensionsUpdateState } = useUIState();
  if (extensions.length === 0) {
    return /* @__PURE__ */ (0, import_jsx_runtime51.jsx)(Text, { children: "No extensions installed." });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime51.jsxs)(Box_default, { flexDirection: "column", marginBottom: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime51.jsx)(Text, { children: "Installed extensions: " }),
    /* @__PURE__ */ (0, import_jsx_runtime51.jsx)(Box_default, { flexDirection: "column", paddingLeft: 2, children: extensions.map((ext) => {
      const state = extensionsUpdateState.get(ext.name);
      const isActive = ext.isActive;
      const activeString = isActive ? "active" : "disabled";
      const activeColor = isActive ? "green" : "grey";
      let stateColor = "gray";
      const stateText = state || "unknown state";
      switch (state) {
        case "checking for updates" /* CHECKING_FOR_UPDATES */:
        case "updating" /* UPDATING */:
          stateColor = "cyan";
          break;
        case "update available" /* UPDATE_AVAILABLE */:
        case "updated, needs restart" /* UPDATED_NEEDS_RESTART */:
          stateColor = "yellow";
          break;
        case "error" /* ERROR */:
          stateColor = "red";
          break;
        case "up to date" /* UP_TO_DATE */:
        case "not updatable" /* NOT_UPDATABLE */:
        case "updated" /* UPDATED */:
          stateColor = "green";
          break;
        case void 0:
          break;
        default:
          debugLogger.warn(`Unhandled ExtensionUpdateState ${state}`);
          break;
      }
      return /* @__PURE__ */ (0, import_jsx_runtime51.jsxs)(Box_default, { flexDirection: "column", marginBottom: 1, children: [
        /* @__PURE__ */ (0, import_jsx_runtime51.jsxs)(Text, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime51.jsx)(Text, { color: "cyan", children: `${ext.name} (v${ext.version})` }),
          /* @__PURE__ */ (0, import_jsx_runtime51.jsx)(Text, { color: activeColor, children: ` - ${activeString}` }),
          /* @__PURE__ */ (0, import_jsx_runtime51.jsx)(Text, { color: stateColor, children: ` (${stateText})` })
        ] }),
        ext.resolvedSettings && ext.resolvedSettings.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime51.jsxs)(Box_default, { flexDirection: "column", paddingLeft: 2, children: [
          /* @__PURE__ */ (0, import_jsx_runtime51.jsx)(Text, { children: "settings:" }),
          ext.resolvedSettings.map((setting) => /* @__PURE__ */ (0, import_jsx_runtime51.jsxs)(Text, { children: [
            "- ",
            setting.name,
            ": ",
            getFormattedSettingValue(setting),
            setting.scope && /* @__PURE__ */ (0, import_jsx_runtime51.jsxs)(Text, { color: "gray", children: [
              " ",
              "(",
              setting.scope.charAt(0).toUpperCase() + setting.scope.slice(1),
              setting.source ? ` - ${setting.source}` : "",
              ")"
            ] })
          ] }, setting.name))
        ] })
      ] }, ext.name);
    }) })
  ] });
};

// packages/cli/src/ui/components/views/ToolsList.tsx
var import_jsx_runtime52 = __toESM(require_jsx_runtime(), 1);
var ToolsList = ({
  tools,
  showDescriptions,
  terminalWidth
}) => /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Box_default, { flexDirection: "column", marginBottom: 1, children: [
  /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text, { bold: true, color: theme.text.primary, children: "Available Gemini CLI tools:" }),
  /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Box_default, { height: 1 }),
  tools.length > 0 ? tools.map((tool) => /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Box_default, { flexDirection: "row", children: [
    /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Text, { color: theme.text.primary, children: [
      "  ",
      "- "
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Box_default, { flexDirection: "column", children: [
      /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Text, { bold: true, color: theme.text.accent, children: [
        tool.displayName,
        " (",
        tool.name,
        ")"
      ] }),
      showDescriptions && tool.description && /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(
        MarkdownDisplay,
        {
          terminalWidth,
          text: tool.description,
          isPending: false
        }
      )
    ] })
  ] }, tool.name)) : /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text, { color: theme.text.primary, children: " No tools available" })
] });

// packages/cli/src/ui/components/views/SkillsList.tsx
var import_jsx_runtime53 = __toESM(require_jsx_runtime(), 1);
var SkillsList = ({
  skills,
  showDescriptions
}) => {
  const sortSkills = (a, b) => {
    if (a.isBuiltin === b.isBuiltin) {
      return a.name.localeCompare(b.name);
    }
    return a.isBuiltin ? 1 : -1;
  };
  const enabledSkills = skills.filter((s) => !s.disabled).sort(sortSkills);
  const disabledSkills = skills.filter((s) => s.disabled).sort(sortSkills);
  const renderSkill = (skill) => /* @__PURE__ */ (0, import_jsx_runtime53.jsxs)(Box_default, { flexDirection: "row", children: [
    /* @__PURE__ */ (0, import_jsx_runtime53.jsxs)(Text, { color: theme.text.primary, children: [
      "  ",
      "- "
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime53.jsxs)(Box_default, { flexDirection: "column", children: [
      /* @__PURE__ */ (0, import_jsx_runtime53.jsxs)(Box_default, { flexDirection: "row", children: [
        /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(
          Text,
          {
            bold: true,
            color: skill.disabled ? theme.text.secondary : theme.text.link,
            children: skill.name
          }
        ),
        skill.isBuiltin && /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(Text, { color: theme.text.secondary, children: " [Built-in]" })
      ] }),
      showDescriptions && skill.description && /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(Box_default, { marginLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(
        Text,
        {
          color: skill.disabled ? theme.text.secondary : theme.text.primary,
          children: skill.description
        }
      ) })
    ] })
  ] }, skill.name);
  return /* @__PURE__ */ (0, import_jsx_runtime53.jsxs)(Box_default, { flexDirection: "column", marginBottom: 1, children: [
    enabledSkills.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime53.jsxs)(Box_default, { flexDirection: "column", children: [
      /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(Text, { bold: true, color: theme.text.primary, children: "Available Agent Skills:" }),
      /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(Box_default, { height: 1 }),
      enabledSkills.map(renderSkill)
    ] }),
    enabledSkills.length > 0 && disabledSkills.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(Box_default, { marginY: 1, children: /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(Text, { color: theme.text.secondary, children: "-".repeat(20) }) }),
    disabledSkills.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime53.jsxs)(Box_default, { flexDirection: "column", children: [
      /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(Text, { bold: true, color: theme.text.secondary, children: "Disabled Skills:" }),
      /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(Box_default, { height: 1 }),
      disabledSkills.map(renderSkill)
    ] }),
    skills.length === 0 && /* @__PURE__ */ (0, import_jsx_runtime53.jsxs)(Box_default, { flexDirection: "column", children: [
      /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(Text, { color: theme.text.primary, children: "No skills available." }),
      /* @__PURE__ */ (0, import_jsx_runtime53.jsxs)(Box_default, { flexDirection: "row", children: [
        /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(Text, { color: theme.text.primary, children: "Learn how to add skills: " }),
        /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(Text, { color: theme.text.link, children: SKILLS_DOCS_URL })
      ] })
    ] })
  ] });
};

// packages/cli/src/ui/components/views/AgentsStatus.tsx
var import_jsx_runtime54 = __toESM(require_jsx_runtime(), 1);
var AgentsStatus = ({
  agents,
  terminalWidth
}) => {
  const localAgents = agents.filter((a) => a.kind === "local");
  const remoteAgents = agents.filter((a) => a.kind === "remote");
  if (agents.length === 0) {
    return /* @__PURE__ */ (0, import_jsx_runtime54.jsx)(Box_default, { flexDirection: "column", marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime54.jsx)(Text, { children: "No agents available." }) });
  }
  const renderAgentList = (title, agentList) => {
    if (agentList.length === 0) return null;
    return /* @__PURE__ */ (0, import_jsx_runtime54.jsxs)(Box_default, { flexDirection: "column", children: [
      /* @__PURE__ */ (0, import_jsx_runtime54.jsx)(Text, { bold: true, color: theme.text.primary, children: title }),
      /* @__PURE__ */ (0, import_jsx_runtime54.jsx)(Box_default, { height: 1 }),
      agentList.map((agent) => /* @__PURE__ */ (0, import_jsx_runtime54.jsxs)(Box_default, { flexDirection: "row", children: [
        /* @__PURE__ */ (0, import_jsx_runtime54.jsxs)(Text, { color: theme.text.primary, children: [
          "  ",
          "- "
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime54.jsxs)(Box_default, { flexDirection: "column", children: [
          /* @__PURE__ */ (0, import_jsx_runtime54.jsxs)(Text, { bold: true, color: theme.text.accent, children: [
            agent.displayName || agent.name,
            agent.displayName && agent.displayName !== agent.name && /* @__PURE__ */ (0, import_jsx_runtime54.jsxs)(Text, { bold: false, children: [
              " (",
              agent.name,
              ")"
            ] })
          ] }),
          agent.description && /* @__PURE__ */ (0, import_jsx_runtime54.jsx)(
            MarkdownDisplay,
            {
              terminalWidth,
              text: agent.description,
              isPending: false
            }
          )
        ] })
      ] }, agent.name))
    ] });
  };
  return /* @__PURE__ */ (0, import_jsx_runtime54.jsxs)(Box_default, { flexDirection: "column", marginBottom: 1, children: [
    renderAgentList("Local Agents", localAgents),
    localAgents.length > 0 && remoteAgents.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime54.jsx)(Box_default, { height: 1 }),
    renderAgentList("Remote Agents", remoteAgents)
  ] });
};

// packages/cli/src/ui/components/views/McpStatus.tsx
var import_jsx_runtime55 = __toESM(require_jsx_runtime(), 1);
var McpStatus = ({
  servers,
  tools,
  prompts,
  resources,
  blockedServers,
  serverStatus,
  authStatus,
  enablementState,
  errors,
  discoveryInProgress,
  connectingServers,
  showDescriptions,
  showSchema
}) => {
  const serverNames = Object.keys(servers).filter(
    (serverName) => !blockedServers.some(
      (blockedServer) => blockedServer.name === serverName
    )
  );
  if (serverNames.length === 0 && blockedServers.length === 0) {
    return /* @__PURE__ */ (0, import_jsx_runtime55.jsxs)(Box_default, { flexDirection: "column", children: [
      /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(Text, { children: "No MCP servers configured." }),
      /* @__PURE__ */ (0, import_jsx_runtime55.jsxs)(Text, { children: [
        "Please view MCP documentation in your browser:",
        " ",
        /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(Text, { color: theme.text.link, children: "https://goo.gle/gemini-cli-docs-mcp" }),
        " ",
        "or use the cli /docs command"
      ] })
    ] });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime55.jsxs)(Box_default, { flexDirection: "column", children: [
    discoveryInProgress && /* @__PURE__ */ (0, import_jsx_runtime55.jsxs)(Box_default, { flexDirection: "column", marginBottom: 1, children: [
      /* @__PURE__ */ (0, import_jsx_runtime55.jsxs)(Text, { color: theme.status.warning, children: [
        "\u23F3 MCP servers are starting up (",
        connectingServers.length,
        " ",
        "initializing)..."
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(Text, { color: theme.text.primary, children: "Note: First startup may take longer. Tool availability will update automatically." })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(Text, { bold: true, children: "Configured MCP servers:" }),
    /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(Box_default, { height: 1 }),
    serverNames.map((serverName) => {
      const server = servers[serverName];
      const serverTools = tools.filter(
        (tool) => tool.serverName === serverName
      );
      const serverPrompts = prompts.filter(
        (prompt) => prompt.serverName === serverName
      );
      const serverResources = resources.filter(
        (resource) => resource.serverName === serverName
      );
      const originalStatus = serverStatus(serverName);
      const hasCachedItems = serverTools.length > 0 || serverPrompts.length > 0 || serverResources.length > 0;
      const status = originalStatus === MCPServerStatus.DISCONNECTED && hasCachedItems ? MCPServerStatus.CONNECTED : originalStatus;
      let statusIndicator = "";
      let statusText = "";
      let statusColor = theme.text.primary;
      const serverEnablement = enablementState[serverName];
      const isDisabled = serverEnablement && !serverEnablement.enabled;
      if (isDisabled) {
        statusIndicator = "\u23F8\uFE0F";
        statusText = serverEnablement.isSessionDisabled ? "Disabled (session)" : "Disabled";
        statusColor = theme.text.secondary;
      } else {
        switch (status) {
          case MCPServerStatus.CONNECTED:
            statusIndicator = "\u{1F7E2}";
            statusText = "Ready";
            statusColor = theme.status.success;
            break;
          case MCPServerStatus.CONNECTING:
            statusIndicator = "\u{1F504}";
            statusText = "Starting... (first startup may take longer)";
            statusColor = theme.status.warning;
            break;
          case MCPServerStatus.DISCONNECTED:
          default:
            statusIndicator = "\u{1F534}";
            statusText = "Disconnected";
            statusColor = theme.status.error;
            break;
        }
      }
      let serverDisplayName = serverName;
      if (server.extension?.name) {
        serverDisplayName += ` (from ${server.extension?.name})`;
      }
      const toolCount = serverTools.length;
      const promptCount = serverPrompts.length;
      const resourceCount = serverResources.length;
      const parts = [];
      if (toolCount > 0) {
        parts.push(`${toolCount} ${toolCount === 1 ? "tool" : "tools"}`);
      }
      if (promptCount > 0) {
        parts.push(
          `${promptCount} ${promptCount === 1 ? "prompt" : "prompts"}`
        );
      }
      if (resourceCount > 0) {
        parts.push(
          `${resourceCount} ${resourceCount === 1 ? "resource" : "resources"}`
        );
      }
      const serverAuthStatus = authStatus[serverName];
      let authStatusNode = null;
      if (serverAuthStatus === "authenticated") {
        authStatusNode = /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(Text, { children: " (OAuth)" });
      } else if (serverAuthStatus === "expired") {
        authStatusNode = /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(Text, { color: theme.status.error, children: " (OAuth expired)" });
      } else if (serverAuthStatus === "unauthenticated") {
        authStatusNode = /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(Text, { color: theme.status.warning, children: " (OAuth not authenticated)" });
      }
      return /* @__PURE__ */ (0, import_jsx_runtime55.jsxs)(Box_default, { flexDirection: "column", marginBottom: 1, children: [
        /* @__PURE__ */ (0, import_jsx_runtime55.jsxs)(Box_default, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime55.jsxs)(Text, { color: statusColor, children: [
            statusIndicator,
            " "
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(Text, { bold: true, children: serverDisplayName }),
          /* @__PURE__ */ (0, import_jsx_runtime55.jsxs)(Text, { children: [
            " - ",
            statusText,
            status === MCPServerStatus.CONNECTED && parts.length > 0 && ` (${parts.join(", ")})`
          ] }),
          authStatusNode
        ] }),
        status === MCPServerStatus.CONNECTING && /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(Text, { children: " (tools and prompts will appear when ready)" }),
        status === MCPServerStatus.DISCONNECTED && toolCount > 0 && /* @__PURE__ */ (0, import_jsx_runtime55.jsxs)(Text, { children: [
          " (",
          toolCount,
          " tools cached)"
        ] }),
        errors[serverName] && /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(Box_default, { marginLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime55.jsxs)(Text, { color: theme.status.error, children: [
          "Error: ",
          errors[serverName]
        ] }) }),
        showDescriptions && server?.description && /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(Text, { color: theme.text.secondary, children: server.description.trim() }),
        serverTools.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime55.jsxs)(Box_default, { flexDirection: "column", marginLeft: 2, children: [
          /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(Text, { color: theme.text.primary, children: "Tools:" }),
          serverTools.map((tool) => {
            const schemaContent = showSchema && tool.schema && (tool.schema.parametersJsonSchema || tool.schema.parameters) ? JSON.stringify(
              tool.schema.parametersJsonSchema ?? tool.schema.parameters,
              null,
              2
            ) : null;
            return /* @__PURE__ */ (0, import_jsx_runtime55.jsxs)(Box_default, { flexDirection: "column", children: [
              /* @__PURE__ */ (0, import_jsx_runtime55.jsxs)(Text, { children: [
                "- ",
                /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(Text, { color: theme.text.primary, children: tool.name })
              ] }),
              showDescriptions && tool.description && /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(Box_default, { marginLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(Text, { color: theme.text.secondary, children: tool.description.trim() }) }),
              schemaContent && /* @__PURE__ */ (0, import_jsx_runtime55.jsxs)(Box_default, { flexDirection: "column", marginLeft: 4, children: [
                /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(Text, { color: theme.text.secondary, children: "Parameters:" }),
                /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(Text, { color: theme.text.secondary, children: schemaContent })
              ] })
            ] }, tool.name);
          })
        ] }),
        serverPrompts.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime55.jsxs)(Box_default, { flexDirection: "column", marginLeft: 2, children: [
          /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(Text, { color: theme.text.primary, children: "Prompts:" }),
          serverPrompts.map((prompt) => /* @__PURE__ */ (0, import_jsx_runtime55.jsxs)(Box_default, { flexDirection: "column", children: [
            /* @__PURE__ */ (0, import_jsx_runtime55.jsxs)(Text, { children: [
              "- ",
              /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(Text, { color: theme.text.primary, children: prompt.name })
            ] }),
            showDescriptions && prompt.description && /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(Box_default, { marginLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(Text, { color: theme.text.primary, children: prompt.description.trim() }) })
          ] }, prompt.name))
        ] }),
        serverResources.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime55.jsxs)(Box_default, { flexDirection: "column", marginLeft: 2, children: [
          /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(Text, { color: theme.text.primary, children: "Resources:" }),
          serverResources.slice(0, MAX_MCP_RESOURCES_TO_SHOW).map((resource, index) => {
            const label = resource.name || resource.uri || "resource";
            return /* @__PURE__ */ (0, import_jsx_runtime55.jsxs)(
              Box_default,
              {
                flexDirection: "column",
                children: [
                  /* @__PURE__ */ (0, import_jsx_runtime55.jsxs)(Text, { children: [
                    "- ",
                    /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(Text, { color: theme.text.primary, children: label }),
                    resource.uri ? ` (${resource.uri})` : "",
                    resource.mimeType ? ` [${resource.mimeType}]` : ""
                  ] }),
                  showDescriptions && resource.description && /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(Box_default, { marginLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(Text, { color: theme.text.secondary, children: resource.description.trim() }) })
                ]
              },
              `${resource.serverName}-resource-${index}`
            );
          }),
          serverResources.length > MAX_MCP_RESOURCES_TO_SHOW && /* @__PURE__ */ (0, import_jsx_runtime55.jsxs)(Text, { color: theme.text.secondary, children: [
            "  ",
            "...",
            " ",
            serverResources.length - MAX_MCP_RESOURCES_TO_SHOW,
            " ",
            serverResources.length - MAX_MCP_RESOURCES_TO_SHOW === 1 ? "resource" : "resources",
            " ",
            "hidden"
          ] })
        ] })
      ] }, serverName);
    }),
    blockedServers.map((server) => /* @__PURE__ */ (0, import_jsx_runtime55.jsxs)(Box_default, { marginBottom: 1, children: [
      /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(Text, { color: theme.status.error, children: "\u{1F534} " }),
      /* @__PURE__ */ (0, import_jsx_runtime55.jsxs)(Text, { bold: true, children: [
        server.name,
        server.extensionName ? ` (from ${server.extensionName})` : ""
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime55.jsx)(Text, { children: " - Blocked" })
    ] }, server.name))
  ] });
};

// packages/cli/src/ui/components/views/ChatList.tsx
var import_jsx_runtime56 = __toESM(require_jsx_runtime(), 1);
var ChatList = ({ chats }) => {
  if (chats.length === 0) {
    return /* @__PURE__ */ (0, import_jsx_runtime56.jsx)(Text, { children: "No saved conversation checkpoints found." });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime56.jsxs)(Box_default, { flexDirection: "column", children: [
    /* @__PURE__ */ (0, import_jsx_runtime56.jsx)(Text, { children: "List of saved conversations:" }),
    /* @__PURE__ */ (0, import_jsx_runtime56.jsx)(Box_default, { height: 1 }),
    chats.map((chat) => {
      const isoString = chat.mtime;
      const match = isoString.match(
        /(\d{4}-\d{2}-\d{2})T(\d{2}:\d{2}:\d{2})/
      );
      const formattedDate = match ? `${match[1]} ${match[2]}` : "Invalid Date";
      return /* @__PURE__ */ (0, import_jsx_runtime56.jsx)(Box_default, { flexDirection: "row", children: /* @__PURE__ */ (0, import_jsx_runtime56.jsxs)(Text, { children: [
        "  ",
        "- ",
        /* @__PURE__ */ (0, import_jsx_runtime56.jsx)(Text, { color: theme.text.accent, children: chat.name }),
        " ",
        /* @__PURE__ */ (0, import_jsx_runtime56.jsxs)(Text, { color: theme.text.secondary, children: [
          "(",
          formattedDate,
          ")"
        ] })
      ] }) }, chat.name);
    }),
    /* @__PURE__ */ (0, import_jsx_runtime56.jsx)(Box_default, { height: 1 }),
    /* @__PURE__ */ (0, import_jsx_runtime56.jsx)(Text, { color: theme.text.secondary, children: "Note: Newest last, oldest first" })
  ] });
};

// packages/cli/src/ui/components/messages/ModelMessage.tsx
var import_jsx_runtime57 = __toESM(require_jsx_runtime(), 1);
var ModelMessage = ({ model }) => /* @__PURE__ */ (0, import_jsx_runtime57.jsx)(Box_default, { marginLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime57.jsxs)(Text, { color: theme.ui.comment, italic: true, children: [
  "Responding with ",
  getDisplayString(model)
] }) });

// packages/cli/src/ui/components/messages/ThinkingMessage.tsx
var import_react37 = __toESM(require_react(), 1);
var import_jsx_runtime58 = __toESM(require_jsx_runtime(), 1);
var THINKING_LEFT_PADDING = 1;
function normalizeThoughtLines(thought) {
  const subject = normalizeEscapedNewlines(thought.subject).trim();
  const description = normalizeEscapedNewlines(thought.description).trim();
  const isNoise = (text) => {
    const trimmed = text.trim();
    return !trimmed || /^\.+$/.test(trimmed);
  };
  const lines = [];
  if (subject && !isNoise(subject)) {
    lines.push(subject);
  }
  if (description) {
    const descriptionLines = description.split("\n").map((line) => line.trim()).filter((line) => !isNoise(line));
    lines.push(...descriptionLines);
  }
  return lines;
}
var ThinkingMessage = ({
  thought,
  terminalWidth,
  isFirstThinking
}) => {
  const fullLines = (0, import_react37.useMemo)(() => normalizeThoughtLines(thought), [thought]);
  if (fullLines.length === 0) {
    return null;
  }
  return /* @__PURE__ */ (0, import_jsx_runtime58.jsxs)(Box_default, { width: terminalWidth, flexDirection: "column", children: [
    isFirstThinking && /* @__PURE__ */ (0, import_jsx_runtime58.jsxs)(Text, { color: theme.text.primary, italic: true, children: [
      " ",
      "Thinking...",
      " "
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime58.jsxs)(
      Box_default,
      {
        marginLeft: THINKING_LEFT_PADDING,
        paddingLeft: 1,
        borderStyle: "single",
        borderLeft: true,
        borderRight: false,
        borderTop: false,
        borderBottom: false,
        borderColor: theme.text.secondary,
        flexDirection: "column",
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime58.jsx)(Text, { children: " " }),
          fullLines.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime58.jsx)(Text, { color: theme.text.primary, bold: true, italic: true, children: fullLines[0] }),
          fullLines.slice(1).map((line, index) => /* @__PURE__ */ (0, import_jsx_runtime58.jsx)(Text, { color: theme.text.secondary, italic: true, children: line }, `body-line-${index}`))
        ]
      }
    )
  ] });
};

// packages/cli/src/ui/components/messages/HintMessage.tsx
var import_jsx_runtime59 = __toESM(require_jsx_runtime(), 1);
var HintMessage = ({ text }) => {
  const prefix = "\u{1F4A1} ";
  const prefixWidth = prefix.length;
  const config = useConfig();
  const useBackgroundColor = config.getUseBackgroundColor();
  return /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(
    HalfLinePaddedBox,
    {
      backgroundBaseColor: theme.text.accent,
      backgroundOpacity: 0.1,
      useBackgroundColor,
      children: /* @__PURE__ */ (0, import_jsx_runtime59.jsxs)(
        Box_default,
        {
          flexDirection: "row",
          paddingY: 0,
          marginY: useBackgroundColor ? 0 : 1,
          paddingX: useBackgroundColor ? 1 : 0,
          alignSelf: "flex-start",
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(Box_default, { width: prefixWidth, flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(
              Text,
              {
                color: theme.text.accent,
                "aria-label": SCREEN_READER_USER_PREFIX,
                children: prefix
              }
            ) }),
            /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(Box_default, { flexGrow: 1, children: /* @__PURE__ */ (0, import_jsx_runtime59.jsx)(Text, { wrap: "wrap", italic: true, color: theme.text.accent, children: `Steering Hint: ${text}` }) })
          ]
        }
      )
    }
  );
};

// packages/cli/src/ui/utils/inlineThinkingMode.ts
function getInlineThinkingMode(settings) {
  return settings.merged.ui?.inlineThinkingMode ?? "off";
}

// packages/cli/src/ui/components/HistoryItemDisplay.tsx
var import_jsx_runtime60 = __toESM(require_jsx_runtime(), 1);
var HistoryItemDisplay = ({
  item,
  availableTerminalHeight,
  terminalWidth,
  isPending,
  commands,
  availableTerminalHeightGemini,
  isExpandable,
  isFirstThinking = false,
  isFirstAfterThinking = false,
  isToolGroupBoundary = false,
  suppressNarration = false
}) => {
  const settings = useSettings();
  const inlineThinkingMode = getInlineThinkingMode(settings);
  const itemForDisplay = (0, import_react38.useMemo)(() => escapeAnsiCtrlCodes(item), [item]);
  const needTopMargin = !!(isFirstAfterThinking && inlineThinkingMode !== "off" || isToolGroupBoundary);
  if (suppressNarration && (itemForDisplay.type === "thinking" || itemForDisplay.type === "gemini" || itemForDisplay.type === "gemini_content")) {
    return null;
  }
  return /* @__PURE__ */ (0, import_jsx_runtime60.jsxs)(
    Box_default,
    {
      flexDirection: "column",
      width: terminalWidth,
      marginTop: needTopMargin ? 1 : 0,
      children: [
        itemForDisplay.type === "thinking" && inlineThinkingMode !== "off" && /* @__PURE__ */ (0, import_jsx_runtime60.jsx)(
          ThinkingMessage,
          {
            thought: itemForDisplay.thought,
            terminalWidth,
            isFirstThinking
          }
        ),
        itemForDisplay.type === "hint" && /* @__PURE__ */ (0, import_jsx_runtime60.jsx)(HintMessage, { text: itemForDisplay.text }),
        itemForDisplay.type === "user" && /* @__PURE__ */ (0, import_jsx_runtime60.jsx)(UserMessage, { text: itemForDisplay.text, width: terminalWidth }),
        itemForDisplay.type === "user_shell" && /* @__PURE__ */ (0, import_jsx_runtime60.jsx)(UserShellMessage, { text: itemForDisplay.text, width: terminalWidth }),
        itemForDisplay.type === "gemini" && /* @__PURE__ */ (0, import_jsx_runtime60.jsx)(
          GeminiMessage,
          {
            text: itemForDisplay.text,
            isPending,
            availableTerminalHeight: availableTerminalHeightGemini ?? availableTerminalHeight,
            terminalWidth
          }
        ),
        itemForDisplay.type === "gemini_content" && /* @__PURE__ */ (0, import_jsx_runtime60.jsx)(
          GeminiMessageContent,
          {
            text: itemForDisplay.text,
            isPending,
            availableTerminalHeight: availableTerminalHeightGemini ?? availableTerminalHeight,
            terminalWidth
          }
        ),
        itemForDisplay.type === "info" && /* @__PURE__ */ (0, import_jsx_runtime60.jsx)(
          InfoMessage,
          {
            text: itemForDisplay.text,
            secondaryText: itemForDisplay.secondaryText,
            source: itemForDisplay.source,
            icon: itemForDisplay.icon,
            color: itemForDisplay.color,
            marginBottom: itemForDisplay.marginBottom
          }
        ),
        itemForDisplay.type === "warning" && /* @__PURE__ */ (0, import_jsx_runtime60.jsx)(WarningMessage, { text: itemForDisplay.text }),
        itemForDisplay.type === "error" && /* @__PURE__ */ (0, import_jsx_runtime60.jsx)(ErrorMessage, { text: itemForDisplay.text }),
        itemForDisplay.type === "about" && /* @__PURE__ */ (0, import_jsx_runtime60.jsx)(
          AboutBox,
          {
            cliVersion: itemForDisplay.cliVersion,
            osVersion: itemForDisplay.osVersion,
            sandboxEnv: itemForDisplay.sandboxEnv,
            modelVersion: itemForDisplay.modelVersion,
            selectedAuthType: itemForDisplay.selectedAuthType,
            gcpProject: itemForDisplay.gcpProject,
            ideClient: itemForDisplay.ideClient,
            userEmail: itemForDisplay.userEmail,
            tier: itemForDisplay.tier
          }
        ),
        itemForDisplay.type === "help" && commands && /* @__PURE__ */ (0, import_jsx_runtime60.jsx)(Help, { commands }),
        itemForDisplay.type === "stats" && /* @__PURE__ */ (0, import_jsx_runtime60.jsx)(
          StatsDisplay,
          {
            duration: itemForDisplay.duration,
            selectedAuthType: itemForDisplay.selectedAuthType,
            userEmail: itemForDisplay.userEmail,
            tier: itemForDisplay.tier
          }
        ),
        itemForDisplay.type === "model_stats" && /* @__PURE__ */ (0, import_jsx_runtime60.jsx)(
          ModelStatsDisplay,
          {
            selectedAuthType: itemForDisplay.selectedAuthType,
            userEmail: itemForDisplay.userEmail,
            tier: itemForDisplay.tier,
            currentModel: itemForDisplay.currentModel,
            quotaStats: itemForDisplay.pooledRemaining !== void 0 || itemForDisplay.pooledLimit !== void 0 || itemForDisplay.pooledResetTime !== void 0 ? {
              remaining: itemForDisplay.pooledRemaining,
              limit: itemForDisplay.pooledLimit,
              resetTime: itemForDisplay.pooledResetTime
            } : void 0
          }
        ),
        itemForDisplay.type === "tool_stats" && /* @__PURE__ */ (0, import_jsx_runtime60.jsx)(ToolStatsDisplay, {}),
        itemForDisplay.type === "model" && /* @__PURE__ */ (0, import_jsx_runtime60.jsx)(ModelMessage, { model: itemForDisplay.model }),
        itemForDisplay.type === "quit" && /* @__PURE__ */ (0, import_jsx_runtime60.jsx)(SessionSummaryDisplay, { duration: itemForDisplay.duration }),
        itemForDisplay.type === "tool_group" && /* @__PURE__ */ (0, import_jsx_runtime60.jsx)(
          ToolGroupMessage,
          {
            item: itemForDisplay,
            toolCalls: itemForDisplay.tools,
            availableTerminalHeight,
            terminalWidth,
            borderTop: itemForDisplay.borderTop,
            borderBottom: itemForDisplay.borderBottom,
            isExpandable,
            isToolGroupBoundary
          }
        ),
        itemForDisplay.type === "subagent" && /* @__PURE__ */ (0, import_jsx_runtime60.jsx)(
          SubagentHistoryMessage,
          {
            item: itemForDisplay,
            terminalWidth
          }
        ),
        itemForDisplay.type === "compression" && /* @__PURE__ */ (0, import_jsx_runtime60.jsx)(CompressionMessage, { compression: itemForDisplay.compression }),
        itemForDisplay.type === "extensions_list" && /* @__PURE__ */ (0, import_jsx_runtime60.jsx)(ExtensionsList, { extensions: itemForDisplay.extensions }),
        itemForDisplay.type === "tools_list" && /* @__PURE__ */ (0, import_jsx_runtime60.jsx)(
          ToolsList,
          {
            terminalWidth,
            tools: itemForDisplay.tools,
            showDescriptions: itemForDisplay.showDescriptions
          }
        ),
        itemForDisplay.type === "skills_list" && /* @__PURE__ */ (0, import_jsx_runtime60.jsx)(
          SkillsList,
          {
            skills: itemForDisplay.skills,
            showDescriptions: itemForDisplay.showDescriptions
          }
        ),
        itemForDisplay.type === "agents_list" && /* @__PURE__ */ (0, import_jsx_runtime60.jsx)(
          AgentsStatus,
          {
            agents: itemForDisplay.agents,
            terminalWidth
          }
        ),
        itemForDisplay.type === "mcp_status" && /* @__PURE__ */ (0, import_jsx_runtime60.jsx)(McpStatus, { ...itemForDisplay, serverStatus: getMCPServerStatus }),
        itemForDisplay.type === "chat_list" && /* @__PURE__ */ (0, import_jsx_runtime60.jsx)(ChatList, { chats: itemForDisplay.chats })
      ]
    },
    itemForDisplay.id
  );
};

// packages/cli/src/ui/hooks/useTerminalSize.ts
var import_react39 = __toESM(require_react(), 1);
function useTerminalSize() {
  const [size, setSize] = (0, import_react39.useState)({
    columns: process.stdout.columns || 60,
    rows: process.stdout.rows || 20
  });
  (0, import_react39.useEffect)(() => {
    function updateSize() {
      setSize({
        columns: process.stdout.columns || 60,
        rows: process.stdout.rows || 20
      });
    }
    process.stdout.on("resize", updateSize);
    return () => {
      process.stdout.off("resize", updateSize);
    };
  }, []);
  return size;
}

// packages/cli/src/ui/components/QuittingDisplay.tsx
var import_jsx_runtime61 = __toESM(require_jsx_runtime(), 1);
var QuittingDisplay = () => {
  const uiState = useUIState();
  const { rows: terminalHeight, columns: terminalWidth } = useTerminalSize();
  const availableTerminalHeight = terminalHeight;
  if (!uiState.quittingMessages) {
    return null;
  }
  return /* @__PURE__ */ (0, import_jsx_runtime61.jsx)(Box_default, { flexDirection: "column", marginBottom: 1, children: uiState.quittingMessages.map((item) => /* @__PURE__ */ (0, import_jsx_runtime61.jsx)(
    HistoryItemDisplay,
    {
      availableTerminalHeight: uiState.constrainHeight ? availableTerminalHeight : void 0,
      terminalWidth,
      item,
      isPending: false
    },
    item.id
  )) });
};

// packages/cli/src/ui/components/Notifications.tsx
var import_react41 = __toESM(require_react(), 1);

// packages/cli/src/ui/contexts/AppContext.tsx
var import_react40 = __toESM(require_react(), 1);
var AppContext = (0, import_react40.createContext)(null);
var useAppContext = () => {
  const context = (0, import_react40.useContext)(AppContext);
  if (!context) {
    throw new Error("useAppContext must be used within an AppProvider");
  }
  return context;
};

// packages/cli/src/ui/components/UpdateNotification.tsx
var import_jsx_runtime62 = __toESM(require_jsx_runtime(), 1);
var UpdateNotification = ({ message }) => /* @__PURE__ */ (0, import_jsx_runtime62.jsx)(
  Box_default,
  {
    borderStyle: "round",
    borderColor: theme.status.warning,
    paddingX: 1,
    marginY: 1,
    children: /* @__PURE__ */ (0, import_jsx_runtime62.jsx)(Text, { color: theme.status.warning, children: message })
  }
);

// packages/cli/src/ui/components/Notifications.tsx
var import_jsx_runtime63 = __toESM(require_jsx_runtime(), 1);
import * as fs from "node:fs/promises";
import path5 from "node:path";
var settingsPath = path5.join(homedir(), GEMINI_DIR, "settings.json");
var screenReaderNudgeFilePath = path5.join(
  Storage.getGlobalTempDir(),
  "seen_screen_reader_nudge.json"
);
var MAX_STARTUP_WARNING_SHOW_COUNT = 3;
var Notifications = () => {
  const { startupWarnings } = useAppContext();
  const { initError, streamingState, updateInfo } = useUIState();
  const isScreenReaderEnabled = use_is_screen_reader_enabled_default();
  const showInitError = initError && streamingState !== "responding" /* Responding */;
  const [hasSeenScreenReaderNudge, setHasSeenScreenReaderNudge] = (0, import_react41.useState)(
    () => persistentState.get("hasSeenScreenReaderNudge")
  );
  const [dismissed, setDismissed] = (0, import_react41.useState)(false);
  const hasIncrementedRef = (0, import_react41.useRef)(false);
  const visibleWarnings = (0, import_react41.useMemo)(() => {
    if (dismissed) return [];
    const counts = persistentState.get("startupWarningCounts") || {};
    return startupWarnings.filter((w) => {
      if (w.priority === WarningPriority.Low) {
        const count = counts[w.id] || 0;
        return count < MAX_STARTUP_WARNING_SHOW_COUNT;
      }
      return true;
    });
  }, [startupWarnings, dismissed]);
  const showStartupWarnings = visibleWarnings.length > 0;
  (0, import_react41.useEffect)(() => {
    if (visibleWarnings.length > 0 && !hasIncrementedRef.current) {
      const counts = { ...persistentState.get("startupWarningCounts") || {} };
      let changed = false;
      visibleWarnings.forEach((w) => {
        if (w.priority === WarningPriority.Low) {
          counts[w.id] = (counts[w.id] || 0) + 1;
          changed = true;
        }
      });
      if (changed) {
        persistentState.set("startupWarningCounts", counts);
      }
      hasIncrementedRef.current = true;
    }
  }, [visibleWarnings]);
  const handleKeyPress = (0, import_react41.useCallback)(() => {
    if (showStartupWarnings) {
      setDismissed(true);
    }
    return false;
  }, [showStartupWarnings]);
  useKeypress(handleKeyPress, {
    isActive: showStartupWarnings,
    priority: 200 /* Critical */
  });
  (0, import_react41.useEffect)(() => {
    const checkLegacyScreenReaderNudge = async () => {
      if (hasSeenScreenReaderNudge !== void 0) return;
      try {
        await fs.access(screenReaderNudgeFilePath);
        persistentState.set("hasSeenScreenReaderNudge", true);
        setHasSeenScreenReaderNudge(true);
        await fs.unlink(screenReaderNudgeFilePath).catch(() => {
        });
      } catch {
        setHasSeenScreenReaderNudge(false);
      }
    };
    if (isScreenReaderEnabled) {
      checkLegacyScreenReaderNudge();
    }
  }, [isScreenReaderEnabled, hasSeenScreenReaderNudge]);
  const showScreenReaderNudge = isScreenReaderEnabled && hasSeenScreenReaderNudge === false;
  (0, import_react41.useEffect)(() => {
    if (showScreenReaderNudge) {
      persistentState.set("hasSeenScreenReaderNudge", true);
    }
  }, [showScreenReaderNudge]);
  if (!showStartupWarnings && !showInitError && !updateInfo && !showScreenReaderNudge) {
    return null;
  }
  return /* @__PURE__ */ (0, import_jsx_runtime63.jsxs)(import_jsx_runtime63.Fragment, { children: [
    showScreenReaderNudge && /* @__PURE__ */ (0, import_jsx_runtime63.jsxs)(Text, { children: [
      "You are currently in screen reader-friendly view. To switch out, open",
      " ",
      settingsPath,
      " and remove the entry for ",
      '"screenReader"',
      ". This will disappear on next run."
    ] }),
    updateInfo && /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(UpdateNotification, { message: updateInfo.message }),
    showStartupWarnings && /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(Box_default, { marginY: 1, flexDirection: "column", children: visibleWarnings.map((warning, index) => /* @__PURE__ */ (0, import_jsx_runtime63.jsxs)(Box_default, { flexDirection: "row", children: [
      /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(Box_default, { width: 3, children: /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(Text, { color: theme.status.warning, children: "\u26A0 " }) }),
      /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(Box_default, { flexGrow: 1, children: /* @__PURE__ */ (0, import_jsx_runtime63.jsx)(Text, { color: theme.status.warning, children: warning.message }) })
    ] }, index)) }),
    showInitError && /* @__PURE__ */ (0, import_jsx_runtime63.jsxs)(
      Box_default,
      {
        borderStyle: "round",
        borderColor: theme.status.error,
        paddingX: 1,
        marginBottom: 1,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime63.jsxs)(Text, { color: theme.status.error, children: [
            "Initialization Error: ",
            initError
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime63.jsxs)(Text, { color: theme.status.error, children: [
            " ",
            "Please check API key and configuration."
          ] })
        ]
      }
    )
  ] });
};

// packages/cli/src/ui/components/UserIdentity.tsx
var import_react42 = __toESM(require_react(), 1);
var import_jsx_runtime64 = __toESM(require_jsx_runtime(), 1);
var UserIdentity = ({ config }) => {
  const authType = config.getContentGeneratorConfig()?.authType;
  const [email, setEmail] = (0, import_react42.useState)();
  (0, import_react42.useEffect)(() => {
    if (authType) {
      const userAccountManager = new UserAccountManager();
      setEmail(userAccountManager.getCachedGoogleAccount() ?? void 0);
    } else {
      setEmail(void 0);
    }
  }, [authType]);
  const tierName = (0, import_react42.useMemo)(
    () => authType ? config.getUserTierName() : void 0,
    [config, authType]
  );
  const isUltra = (0, import_react42.useMemo)(() => isUltraTier(tierName), [tierName]);
  if (!authType) {
    return null;
  }
  return /* @__PURE__ */ (0, import_jsx_runtime64.jsxs)(Box_default, { flexDirection: "column", children: [
    /* @__PURE__ */ (0, import_jsx_runtime64.jsxs)(Box_default, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime64.jsx)(Text, { color: theme.text.primary, wrap: "truncate-end", children: authType === AuthType.LOGIN_WITH_GOOGLE ? /* @__PURE__ */ (0, import_jsx_runtime64.jsxs)(Text, { children: [
        /* @__PURE__ */ (0, import_jsx_runtime64.jsxs)(Text, { bold: true, children: [
          "Signed in with Google",
          email ? ":" : ""
        ] }),
        email ? ` ${email}` : ""
      ] }) : `Authenticated with ${authType}` }),
      /* @__PURE__ */ (0, import_jsx_runtime64.jsx)(Text, { color: theme.text.secondary, children: " /auth" })
    ] }),
    tierName && /* @__PURE__ */ (0, import_jsx_runtime64.jsxs)(Box_default, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime64.jsxs)(Text, { color: theme.text.primary, wrap: "truncate-end", children: [
        /* @__PURE__ */ (0, import_jsx_runtime64.jsx)(Text, { bold: true, children: "Plan:" }),
        " ",
        tierName
      ] }),
      !isUltra && /* @__PURE__ */ (0, import_jsx_runtime64.jsx)(Text, { color: theme.text.secondary, children: " /upgrade" })
    ] })
  ] });
};

// packages/cli/src/ui/components/Tips.tsx
var import_jsx_runtime65 = __toESM(require_jsx_runtime(), 1);
var Tips = ({ config }) => {
  const geminiMdFileCount = config.getGeminiMdFileCount();
  return /* @__PURE__ */ (0, import_jsx_runtime65.jsxs)(Box_default, { flexDirection: "column", marginTop: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime65.jsx)(Text, { color: theme.text.primary, children: "Tips for getting started:" }),
    geminiMdFileCount === 0 && /* @__PURE__ */ (0, import_jsx_runtime65.jsxs)(Text, { color: theme.text.primary, children: [
      "1. Create ",
      /* @__PURE__ */ (0, import_jsx_runtime65.jsx)(Text, { bold: true, children: "GEMINI.md" }),
      " files to customize your interactions"
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime65.jsxs)(Text, { color: theme.text.primary, children: [
      geminiMdFileCount === 0 ? "2." : "1.",
      " ",
      /* @__PURE__ */ (0, import_jsx_runtime65.jsx)(Text, { color: theme.text.secondary, children: "/help" }),
      " for more information"
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime65.jsxs)(Text, { color: theme.text.primary, children: [
      geminiMdFileCount === 0 ? "3." : "2.",
      " Ask coding questions, edit code or run commands"
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime65.jsxs)(Text, { color: theme.text.primary, children: [
      geminiMdFileCount === 0 ? "4." : "3.",
      " Be specific for the best results"
    ] })
  ] });
};

// packages/cli/src/ui/components/Banner.tsx
var import_jsx_runtime66 = __toESM(require_jsx_runtime(), 1);
function getFormattedBannerContent(rawText, isWarning, subsequentLineColor) {
  const text = rawText.replace(/\\n/g, "\n");
  const lines = text.split("\n");
  return lines.map((line, index) => {
    if (index === 0) {
      if (isWarning) {
        return /* @__PURE__ */ (0, import_jsx_runtime66.jsx)(Text, { bold: true, color: theme.status.warning, children: line }, index);
      }
      return /* @__PURE__ */ (0, import_jsx_runtime66.jsx)(ThemedGradient, { children: /* @__PURE__ */ (0, import_jsx_runtime66.jsx)(Text, { bold: true, children: line }) }, index);
    }
    return /* @__PURE__ */ (0, import_jsx_runtime66.jsx)(Text, { color: subsequentLineColor, children: line }, index);
  });
}
var Banner = ({ bannerText, isWarning, width }) => {
  const subsequentLineColor = theme.text.primary;
  const formattedBannerContent = getFormattedBannerContent(
    bannerText,
    isWarning,
    subsequentLineColor
  );
  return /* @__PURE__ */ (0, import_jsx_runtime66.jsx)(
    Box_default,
    {
      flexDirection: "column",
      borderStyle: "round",
      borderColor: isWarning ? theme.status.warning : theme.border.default,
      width,
      paddingLeft: 1,
      paddingRight: 1,
      children: formattedBannerContent
    }
  );
};

// packages/cli/src/ui/hooks/useBanner.ts
var import_react43 = __toESM(require_react(), 1);
import crypto from "node:crypto";
var DEFAULT_MAX_BANNER_SHOWN_COUNT = 5;
var sessionIncrementedBanners = /* @__PURE__ */ new Set();
function useBanner(bannerData) {
  const { defaultText, warningText } = bannerData;
  const [bannerCounts] = (0, import_react43.useState)(
    () => persistentState.get("defaultBannerShownCount") || {}
  );
  const activeText = warningText ? warningText : defaultText;
  const hashedText = crypto.createHash("sha256").update(activeText).digest("hex");
  const currentBannerCount = bannerCounts[hashedText] || 0;
  const showBanner = activeText !== "" && currentBannerCount < DEFAULT_MAX_BANNER_SHOWN_COUNT;
  const rawBannerText = showBanner ? activeText : "";
  const bannerText = rawBannerText.replace(/\\n/g, "\n");
  (0, import_react43.useEffect)(() => {
    if (showBanner && activeText) {
      if (!sessionIncrementedBanners.has(activeText)) {
        sessionIncrementedBanners.add(activeText);
        const allCounts = persistentState.get("defaultBannerShownCount") || {};
        const current = allCounts[hashedText] || 0;
        persistentState.set("defaultBannerShownCount", {
          ...allCounts,
          [hashedText]: current + 1
        });
      }
    }
  }, [showBanner, activeText, hashedText]);
  return {
    bannerText
  };
}

// packages/cli/src/ui/hooks/useTips.ts
var import_react44 = __toESM(require_react(), 1);
function useTips() {
  const [tipsCount] = (0, import_react44.useState)(() => persistentState.get("tipsShown") ?? 0);
  const showTips = tipsCount < 10;
  (0, import_react44.useEffect)(() => {
    if (showTips) {
      persistentState.set("tipsShown", tipsCount + 1);
    }
  }, [tipsCount, showTips]);
  return { showTips };
}

// packages/cli/src/ui/components/AsciiArt.ts
var longAsciiLogoCompactText = `
\u2597\u2588\u2580\u2580\u259C\u2599\u259D\u2588\u259B\u2580\u2580\u258C\u259C\u2588\u2588\u2596\u259F\u2588\u2588\u2598\u259C\u2588\u2598\u259C\u2588\u2588\u2596\u259D\u2588\u259B\u259D\u2588\u259B
\u2588\u258C     \u2588\u2599\u259F  \u2590\u2588\u259D\u2588\u259B\u2590\u2588 \u2590\u2588 \u2590\u2588\u259D\u2588\u2596\u2588\u258C \u2588\u258C
\u259C\u2599 \u259D\u2588\u259B \u2588\u258C\u259D \u2596\u2590\u2588   \u2590\u2588 \u2590\u2588 \u2590\u2588 \u259D\u2588\u2588\u258C \u2588\u258C
 \u2580\u2580\u2580\u2580\u2598\u259D\u2580\u2580\u2580\u2580\u2598\u2580\u2580\u2598  \u2580\u2580\u2598\u2580\u2580\u2598\u2580\u2580\u2598 \u259D\u2580\u2580\u259D\u2580\u2580
`;

// packages/cli/src/ui/components/AppHeader.tsx
var import_jsx_runtime67 = __toESM(require_jsx_runtime(), 1);
var DEFAULT_ICON = `\u259D\u259C\u2584  
  \u259D\u259C\u2584
 \u2597\u259F\u2580 
\u259D\u2580    `;
var MAC_TERMINAL_ICON = `\u259D\u259C\u2584  
  \u259D\u259C\u2584
  \u2597\u259F\u2580
\u2597\u259F\u2580  `;
var LOGO_METADATA_PADDING = 20;
var NARROW_TERMINAL_BREAKPOINT = 60;
var AppHeader = ({ version, showDetails = true }) => {
  const settings = useSettings();
  const config = useConfig();
  const {
    terminalWidth,
    bannerData,
    bannerVisible,
    updateInfo,
    isConfigInitialized,
    isAuthenticating
  } = useUIState();
  const { bannerText } = useBanner(bannerData);
  const { showTips } = useTips();
  const authType = config.getContentGeneratorConfig()?.authType;
  const loggedOut = isConfigInitialized && !isAuthenticating && !authType;
  const showHeader = !(settings.merged.ui.hideBanner || config.getScreenReader());
  const ICON = isAppleTerminal() ? MAC_TERMINAL_ICON : DEFAULT_ICON;
  let logoTextArt = "";
  if (loggedOut) {
    const widthOfLongLogo = getAsciiArtWidth(longAsciiLogoCompactText) + LOGO_METADATA_PADDING;
    if (terminalWidth >= widthOfLongLogo) {
      logoTextArt = longAsciiLogoCompactText.trim();
    }
  }
  const isNarrow = terminalWidth < NARROW_TERMINAL_BREAKPOINT;
  const renderLogo = () => /* @__PURE__ */ (0, import_jsx_runtime67.jsxs)(Box_default, { flexDirection: "row", children: [
    /* @__PURE__ */ (0, import_jsx_runtime67.jsx)(Box_default, { flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime67.jsx)(ThemedGradient, { children: ICON }) }),
    logoTextArt && /* @__PURE__ */ (0, import_jsx_runtime67.jsx)(Box_default, { marginLeft: 3, children: /* @__PURE__ */ (0, import_jsx_runtime67.jsx)(Text, { color: theme.text.primary, children: logoTextArt }) })
  ] });
  const renderMetadata = (isBelow = false) => /* @__PURE__ */ (0, import_jsx_runtime67.jsxs)(Box_default, { marginLeft: isBelow ? 0 : 2, flexDirection: "column", children: [
    /* @__PURE__ */ (0, import_jsx_runtime67.jsxs)(Box_default, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime67.jsx)(Text, { bold: true, color: theme.text.primary, children: "Gemini CLI" }),
      /* @__PURE__ */ (0, import_jsx_runtime67.jsxs)(Text, { color: theme.text.secondary, children: [
        " v",
        version
      ] }),
      updateInfo?.isUpdating && /* @__PURE__ */ (0, import_jsx_runtime67.jsx)(Box_default, { marginLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime67.jsxs)(Text, { color: theme.text.secondary, children: [
        /* @__PURE__ */ (0, import_jsx_runtime67.jsx)(CliSpinner, {}),
        " Updating"
      ] }) })
    ] }),
    showDetails && /* @__PURE__ */ (0, import_jsx_runtime67.jsxs)(import_jsx_runtime67.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime67.jsx)(Box_default, { height: 1 }),
      settings.merged.ui.showUserIdentity !== false && /* @__PURE__ */ (0, import_jsx_runtime67.jsx)(UserIdentity, { config })
    ] })
  ] });
  const useColumnLayout = !!logoTextArt || isNarrow;
  return /* @__PURE__ */ (0, import_jsx_runtime67.jsxs)(Box_default, { flexDirection: "column", children: [
    showHeader && /* @__PURE__ */ (0, import_jsx_runtime67.jsxs)(
      Box_default,
      {
        flexDirection: useColumnLayout ? "column" : "row",
        marginTop: 1,
        marginBottom: 1,
        paddingLeft: 1,
        children: [
          renderLogo(),
          useColumnLayout ? /* @__PURE__ */ (0, import_jsx_runtime67.jsx)(Box_default, { marginTop: 1, children: renderMetadata(true) }) : renderMetadata(false)
        ]
      }
    ),
    bannerVisible && bannerText && /* @__PURE__ */ (0, import_jsx_runtime67.jsx)(
      Banner,
      {
        width: terminalWidth,
        bannerText,
        isWarning: bannerData.warningText !== ""
      }
    ),
    !(settings.merged.ui.hideTips || config.getScreenReader()) && showTips && /* @__PURE__ */ (0, import_jsx_runtime67.jsx)(Tips, { config })
  ] });
};

// packages/cli/src/ui/components/MainContent.tsx
var import_react51 = __toESM(require_react(), 1);

// packages/cli/src/ui/hooks/useConfirmingTool.ts
var import_react45 = __toESM(require_react(), 1);

// packages/cli/src/ui/utils/historyUtils.ts
function getLastTurnToolCallIds(history, pendingHistoryItems) {
  const targetToolCallIds = [];
  let lastUserPromptIndex = -1;
  for (let i = history.length - 1; i >= 0; i--) {
    const type = history[i].type;
    if (type === "user" || type === "user_shell") {
      lastUserPromptIndex = i;
      break;
    }
  }
  history.forEach((item, index) => {
    if (index > lastUserPromptIndex && item.type === "tool_group") {
      item.tools.forEach((t) => {
        if (t.callId) targetToolCallIds.push(t.callId);
      });
    }
  });
  pendingHistoryItems.forEach((item) => {
    if (item.type === "tool_group") {
      item.tools.forEach((t) => {
        if (t.callId) targetToolCallIds.push(t.callId);
      });
    }
  });
  return targetToolCallIds;
}
function isToolExecuting(pendingHistoryItems) {
  return pendingHistoryItems.some((item) => {
    if (item && item.type === "tool_group") {
      return item.tools.some(
        (tool) => CoreToolCallStatus.Executing === tool.status
      );
    }
    return false;
  });
}
function isToolAwaitingConfirmation(pendingHistoryItems) {
  return pendingHistoryItems.filter((item) => item.type === "tool_group").some(
    (item) => item.tools.some(
      (tool) => CoreToolCallStatus.AwaitingApproval === tool.status
    )
  );
}
function getAllToolCalls(historyItems) {
  return historyItems.filter((item) => item.type === "tool_group").flatMap((group) => group.tools);
}

// packages/cli/src/ui/utils/confirmingTool.ts
function getConfirmingToolState(pendingHistoryItems) {
  const allPendingTools = getAllToolCalls(pendingHistoryItems);
  const confirmingTools = allPendingTools.filter(
    (tool) => tool.status === CoreToolCallStatus.AwaitingApproval
  );
  if (confirmingTools.length === 0) {
    return null;
  }
  const head = confirmingTools[0];
  const headIndexInFullList = allPendingTools.findIndex(
    (tool) => tool.callId === head.callId
  );
  return {
    tool: head,
    index: headIndexInFullList + 1,
    total: allPendingTools.length
  };
}

// packages/cli/src/ui/hooks/useConfirmingTool.ts
function useConfirmingTool() {
  const { pendingHistoryItems } = useUIState();
  return (0, import_react45.useMemo)(
    () => getConfirmingToolState(pendingHistoryItems),
    [pendingHistoryItems]
  );
}

// packages/cli/src/ui/components/messages/ToolConfirmationMessage.tsx
var import_react50 = __toESM(require_react(), 1);

// packages/cli/src/ui/components/AskUserDialog.tsx
var import_react48 = __toESM(require_react(), 1);

// packages/cli/src/ui/components/shared/TabHeader.tsx
var import_react46 = __toESM(require_react(), 1);
var import_jsx_runtime68 = __toESM(require_jsx_runtime(), 1);
function TabHeader({
  tabs,
  currentIndex,
  completedIndices = /* @__PURE__ */ new Set(),
  showArrows = true,
  showStatusIcons = true,
  renderStatusIcon
}) {
  if (tabs.length <= 1) return null;
  const getStatusIcon = (tab, index) => {
    const isCompleted = completedIndices.has(index);
    if (renderStatusIcon) {
      const customIcon = renderStatusIcon(tab, index, isCompleted);
      if (customIcon !== void 0) return customIcon;
    }
    if (tab.statusIcon) return tab.statusIcon;
    if (tab.isSpecial) return "\u2261";
    return isCompleted ? "\u2713" : "\u25A1";
  };
  return /* @__PURE__ */ (0, import_jsx_runtime68.jsxs)(Box_default, { flexDirection: "row", marginBottom: 1, "aria-role": "tablist", children: [
    showArrows && /* @__PURE__ */ (0, import_jsx_runtime68.jsx)(Text, { color: theme.text.secondary, children: "\u2190 " }),
    tabs.map((tab, i) => /* @__PURE__ */ (0, import_jsx_runtime68.jsxs)(import_react46.default.Fragment, { children: [
      i > 0 && /* @__PURE__ */ (0, import_jsx_runtime68.jsx)(Text, { color: theme.text.secondary, children: " \u2502 " }),
      showStatusIcons && /* @__PURE__ */ (0, import_jsx_runtime68.jsxs)(Text, { color: theme.text.secondary, children: [
        getStatusIcon(tab, i),
        " "
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime68.jsx)(Box_default, { maxWidth: i !== currentIndex ? 16 : 100, children: /* @__PURE__ */ (0, import_jsx_runtime68.jsx)(
        Text,
        {
          color: i === currentIndex ? theme.status.success : theme.text.secondary,
          bold: i === currentIndex,
          underline: i === currentIndex,
          "aria-current": i === currentIndex ? "step" : void 0,
          wrap: "truncate",
          children: tab.header
        }
      ) })
    ] }, tab.key)),
    showArrows && /* @__PURE__ */ (0, import_jsx_runtime68.jsx)(Text, { color: theme.text.secondary, children: " \u2192" })
  ] });
}

// packages/cli/src/ui/hooks/useTabbedNavigation.ts
var import_react47 = __toESM(require_react(), 1);
function tabbedNavigationReducer(state, action) {
  switch (action.type) {
    case "NEXT_TAB": {
      const { tabCount, wrapAround, currentIndex } = state;
      if (tabCount === 0) return state;
      let nextIndex = currentIndex + 1;
      if (nextIndex >= tabCount) {
        nextIndex = wrapAround ? 0 : tabCount - 1;
      }
      if (nextIndex === currentIndex) return state;
      return { ...state, currentIndex: nextIndex, pendingTabChange: true };
    }
    case "PREV_TAB": {
      const { tabCount, wrapAround, currentIndex } = state;
      if (tabCount === 0) return state;
      let nextIndex = currentIndex - 1;
      if (nextIndex < 0) {
        nextIndex = wrapAround ? tabCount - 1 : 0;
      }
      if (nextIndex === currentIndex) return state;
      return { ...state, currentIndex: nextIndex, pendingTabChange: true };
    }
    case "SET_INDEX": {
      const { index } = action.payload;
      const { tabCount, currentIndex } = state;
      if (index === currentIndex) return state;
      if (index < 0 || index >= tabCount) return state;
      return { ...state, currentIndex: index, pendingTabChange: true };
    }
    case "INITIALIZE": {
      const { tabCount, initialIndex, wrapAround } = action.payload;
      const validIndex = Math.max(0, Math.min(initialIndex, tabCount - 1));
      return {
        ...state,
        tabCount,
        wrapAround,
        currentIndex: tabCount > 0 ? validIndex : 0,
        pendingTabChange: false
      };
    }
    case "CLEAR_PENDING": {
      return { ...state, pendingTabChange: false };
    }
    default: {
      return state;
    }
  }
}
function useTabbedNavigation({
  tabCount,
  initialIndex = 0,
  wrapAround = false,
  enableArrowNavigation = true,
  enableTabKey = true,
  isNavigationBlocked,
  isActive = true,
  onTabChange
}) {
  const keyMatchers = useKeyMatchers();
  const [state, dispatch] = (0, import_react47.useReducer)(tabbedNavigationReducer, {
    currentIndex: Math.max(0, Math.min(initialIndex, tabCount - 1)),
    tabCount,
    wrapAround,
    pendingTabChange: false
  });
  const prevTabCountRef = (0, import_react47.useRef)(tabCount);
  const prevInitialIndexRef = (0, import_react47.useRef)(initialIndex);
  const prevWrapAroundRef = (0, import_react47.useRef)(wrapAround);
  (0, import_react47.useEffect)(() => {
    const tabCountChanged = prevTabCountRef.current !== tabCount;
    const initialIndexChanged = prevInitialIndexRef.current !== initialIndex;
    const wrapAroundChanged = prevWrapAroundRef.current !== wrapAround;
    if (tabCountChanged || initialIndexChanged || wrapAroundChanged) {
      dispatch({
        type: "INITIALIZE",
        payload: { tabCount, initialIndex, wrapAround }
      });
      prevTabCountRef.current = tabCount;
      prevInitialIndexRef.current = initialIndex;
      prevWrapAroundRef.current = wrapAround;
    }
  }, [tabCount, initialIndex, wrapAround]);
  (0, import_react47.useEffect)(() => {
    if (state.pendingTabChange) {
      onTabChange?.(state.currentIndex);
      dispatch({ type: "CLEAR_PENDING" });
    }
  }, [state.pendingTabChange, state.currentIndex, onTabChange]);
  const goToNextTab = (0, import_react47.useCallback)(() => {
    if (isNavigationBlocked?.()) return;
    dispatch({ type: "NEXT_TAB" });
  }, [isNavigationBlocked]);
  const goToPrevTab = (0, import_react47.useCallback)(() => {
    if (isNavigationBlocked?.()) return;
    dispatch({ type: "PREV_TAB" });
  }, [isNavigationBlocked]);
  const setCurrentIndex = (0, import_react47.useCallback)(
    (index) => {
      if (isNavigationBlocked?.()) return;
      dispatch({ type: "SET_INDEX", payload: { index } });
    },
    [isNavigationBlocked]
  );
  const handleKeypress = (0, import_react47.useCallback)(
    (key) => {
      if (isNavigationBlocked?.()) return;
      if (enableArrowNavigation) {
        if (keyMatchers["cursor.right" /* MOVE_RIGHT */](key)) {
          goToNextTab();
          return;
        }
        if (keyMatchers["cursor.left" /* MOVE_LEFT */](key)) {
          goToPrevTab();
          return;
        }
      }
      if (enableTabKey) {
        if (keyMatchers["nav.dialog.next" /* DIALOG_NEXT */](key)) {
          goToNextTab();
          return;
        }
        if (keyMatchers["nav.dialog.previous" /* DIALOG_PREV */](key)) {
          goToPrevTab();
          return;
        }
      }
    },
    [
      enableArrowNavigation,
      enableTabKey,
      goToNextTab,
      goToPrevTab,
      isNavigationBlocked,
      keyMatchers
    ]
  );
  useKeypress(handleKeypress, { isActive: isActive && tabCount > 1 });
  return {
    currentIndex: state.currentIndex,
    setCurrentIndex,
    goToNextTab,
    goToPrevTab,
    isFirstTab: state.currentIndex === 0,
    isLastTab: state.currentIndex === tabCount - 1
  };
}

// packages/cli/src/ui/components/AskUserDialog.tsx
var import_jsx_runtime69 = __toESM(require_jsx_runtime(), 1);
var DIALOG_PADDING = 4;
function isPlainSingleLine(text) {
  if (text.includes("\n") || text.includes("\r")) {
    return false;
  }
  const markdownPatterns = [
    /^#{1,6}\s/,
    // Headers
    /^[`~]{3,}/,
    // Code fences
    /^[-*+]\s/,
    // Unordered lists
    /^\d+\.\s/,
    // Ordered lists
    /^[-*_]{3,}$/,
    // Horizontal rules
    /\|/,
    // Tables
    /\*\*|__/,
    // Bold
    /(?<!\*)\*(?!\*)/,
    // Italic (single asterisk not part of bold)
    /(?<!_)_(?!_)/,
    // Italic (single underscore not part of bold)
    /`[^`]+`/,
    // Inline code
    /\[.*?\]\(.*?\)/,
    // Links
    /!\[/
    // Images
  ];
  for (const pattern of markdownPatterns) {
    if (pattern.test(text)) {
      return false;
    }
  }
  return true;
}
function autoBoldIfPlain(text) {
  if (isPlainSingleLine(text)) {
    return `**${text}**`;
  }
  return text;
}
var initialState = {
  answers: {},
  isEditingCustomOption: false,
  submitted: false
};
function askUserDialogReducerLogic(state, action) {
  if (state.submitted) {
    return state;
  }
  switch (action.type) {
    case "SET_ANSWER": {
      const { index, answer, submit } = action.payload;
      const hasAnswer = answer !== void 0 && answer !== null && answer.trim() !== "";
      const newAnswers = { ...state.answers };
      if (hasAnswer) {
        newAnswers[index] = answer;
      } else {
        delete newAnswers[index];
      }
      return {
        ...state,
        answers: newAnswers,
        submitted: submit ? true : state.submitted
      };
    }
    case "SET_EDITING_CUSTOM": {
      if (state.isEditingCustomOption === action.payload.isEditing) {
        return state;
      }
      return {
        ...state,
        isEditingCustomOption: action.payload.isEditing
      };
    }
    case "SUBMIT": {
      return {
        ...state,
        submitted: true
      };
    }
    default:
      checkExhaustive(action);
      return state;
  }
}
var ReviewView = ({
  questions,
  answers,
  onSubmit,
  progressHeader,
  extraParts
}) => {
  const keyMatchers = useKeyMatchers();
  const unansweredCount = questions.length - Object.keys(answers).length;
  const hasUnanswered = unansweredCount > 0;
  useKeypress(
    (key) => {
      if (keyMatchers["basic.confirm" /* RETURN */](key)) {
        onSubmit();
        return true;
      }
      return false;
    },
    { isActive: true }
  );
  return /* @__PURE__ */ (0, import_jsx_runtime69.jsxs)(Box_default, { flexDirection: "column", children: [
    progressHeader,
    /* @__PURE__ */ (0, import_jsx_runtime69.jsx)(Box_default, { marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime69.jsx)(Text, { bold: true, color: theme.text.primary, children: "Review your answers:" }) }),
    hasUnanswered && /* @__PURE__ */ (0, import_jsx_runtime69.jsx)(Box_default, { marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime69.jsxs)(Text, { color: theme.status.warning, children: [
      "\u26A0 You have ",
      unansweredCount,
      " unanswered question",
      unansweredCount > 1 ? "s" : ""
    ] }) }),
    /* @__PURE__ */ (0, import_jsx_runtime69.jsx)(Box_default, { flexDirection: "column", children: questions.map((q, i) => /* @__PURE__ */ (0, import_jsx_runtime69.jsxs)(Box_default, { marginBottom: 0, children: [
      /* @__PURE__ */ (0, import_jsx_runtime69.jsx)(Text, { color: theme.text.secondary, children: q.header }),
      /* @__PURE__ */ (0, import_jsx_runtime69.jsx)(Text, { color: theme.text.secondary, children: " \u2192 " }),
      /* @__PURE__ */ (0, import_jsx_runtime69.jsx)(
        Text,
        {
          color: answers[i] ? theme.text.primary : theme.status.warning,
          children: answers[i] || "(not answered)"
        }
      )
    ] }, i)) }),
    /* @__PURE__ */ (0, import_jsx_runtime69.jsx)(
      DialogFooter,
      {
        primaryAction: "Enter to submit",
        navigationActions: `${formatCommand("nav.dialog.next" /* DIALOG_NEXT */)}/${formatCommand("nav.dialog.previous" /* DIALOG_PREV */)} to edit answers`,
        extraParts
      }
    )
  ] });
};
var TextQuestionView = ({
  question,
  onAnswer,
  onSelectionChange,
  onEditingCustomOption,
  availableWidth,
  availableHeight,
  initialAnswer,
  progressHeader,
  keyboardHints
}) => {
  const keyMatchers = useKeyMatchers();
  const isAlternateBuffer = useAlternateBuffer();
  const prefix = "> ";
  const horizontalPadding = 1;
  const bufferWidth = availableWidth - getCachedStringWidth(prefix) - horizontalPadding;
  const buffer = useTextBuffer({
    initialText: initialAnswer,
    viewport: { width: Math.max(1, bufferWidth), height: 3 },
    singleLine: false
  });
  const { text: textValue } = buffer;
  const lastTextValueRef = (0, import_react48.useRef)(textValue);
  (0, import_react48.useEffect)(() => {
    if (textValue !== lastTextValueRef.current) {
      onSelectionChange?.(
        expandPastePlaceholders(textValue, buffer.pastedContent)
      );
      lastTextValueRef.current = textValue;
    }
  }, [textValue, onSelectionChange, buffer.pastedContent]);
  const handleExtraKeys = (0, import_react48.useCallback)(
    (key) => {
      if (keyMatchers["basic.quit" /* QUIT */](key)) {
        if (textValue === "") {
          return false;
        }
        buffer.setText("");
        return true;
      }
      return false;
    },
    [buffer, textValue, keyMatchers]
  );
  useKeypress(handleExtraKeys, { isActive: true, priority: true });
  const handleSubmit = (0, import_react48.useCallback)(
    (val) => {
      onAnswer(val.trim());
    },
    [onAnswer]
  );
  (0, import_react48.useEffect)(() => {
    onEditingCustomOption?.(true);
    return () => {
      onEditingCustomOption?.(false);
    };
  }, [onEditingCustomOption]);
  const placeholder = question.placeholder || "Enter your response";
  const HEADER_HEIGHT2 = progressHeader ? 2 : 0;
  const INPUT_HEIGHT = 2;
  const FOOTER_HEIGHT2 = 2;
  const overhead = HEADER_HEIGHT2 + INPUT_HEIGHT + FOOTER_HEIGHT2;
  const questionHeight = availableHeight && !isAlternateBuffer ? Math.max(1, availableHeight - overhead) : void 0;
  return /* @__PURE__ */ (0, import_jsx_runtime69.jsxs)(Box_default, { flexDirection: "column", children: [
    progressHeader,
    /* @__PURE__ */ (0, import_jsx_runtime69.jsx)(Box_default, { marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime69.jsx)(
      MaxSizedBox,
      {
        maxHeight: questionHeight,
        maxWidth: availableWidth,
        overflowDirection: "bottom",
        children: /* @__PURE__ */ (0, import_jsx_runtime69.jsx)(
          MarkdownDisplay,
          {
            text: autoBoldIfPlain(question.question),
            terminalWidth: availableWidth - DIALOG_PADDING,
            isPending: false
          }
        )
      }
    ) }),
    /* @__PURE__ */ (0, import_jsx_runtime69.jsxs)(Box_default, { flexDirection: "row", marginBottom: 1, children: [
      /* @__PURE__ */ (0, import_jsx_runtime69.jsx)(Text, { color: theme.status.success, children: "> " }),
      /* @__PURE__ */ (0, import_jsx_runtime69.jsx)(
        TextInput,
        {
          buffer,
          placeholder,
          onSubmit: handleSubmit
        }
      )
    ] }),
    keyboardHints
  ] });
};
function choiceQuestionReducer(state, action) {
  switch (action.type) {
    case "TOGGLE_ALL": {
      const { totalOptions } = action.payload;
      const allSelected = state.selectedIndices.size === totalOptions;
      if (allSelected) {
        return {
          ...state,
          selectedIndices: /* @__PURE__ */ new Set()
        };
      } else {
        const newIndices = /* @__PURE__ */ new Set();
        for (let i = 0; i < totalOptions; i++) {
          newIndices.add(i);
        }
        return {
          ...state,
          selectedIndices: newIndices
        };
      }
    }
    case "TOGGLE_INDEX": {
      const { index, multiSelect } = action.payload;
      const newIndices = new Set(multiSelect ? state.selectedIndices : []);
      if (newIndices.has(index)) {
        newIndices.delete(index);
      } else {
        newIndices.add(index);
      }
      return {
        ...state,
        selectedIndices: newIndices,
        // In single select, selecting an option deselects custom
        isCustomOptionSelected: multiSelect ? state.isCustomOptionSelected : false
      };
    }
    case "SET_CUSTOM_SELECTED": {
      const { selected, multiSelect } = action.payload;
      return {
        ...state,
        isCustomOptionSelected: selected,
        // In single-select, selecting custom deselects others
        selectedIndices: multiSelect ? state.selectedIndices : /* @__PURE__ */ new Set()
      };
    }
    case "TOGGLE_CUSTOM_SELECTED": {
      const { multiSelect } = action.payload;
      if (!multiSelect) return state;
      return {
        ...state,
        isCustomOptionSelected: !state.isCustomOptionSelected
      };
    }
    case "SET_CUSTOM_FOCUSED": {
      return {
        ...state,
        isCustomOptionFocused: action.payload.focused
      };
    }
    default:
      checkExhaustive(action);
      return state;
  }
}
var ChoiceQuestionView = ({
  question,
  onAnswer,
  onSelectionChange,
  onEditingCustomOption,
  availableWidth,
  availableHeight,
  initialAnswer,
  progressHeader,
  keyboardHints
}) => {
  const keyMatchers = useKeyMatchers();
  const isAlternateBuffer = useAlternateBuffer();
  const hasAll = question.multiSelect && (question.options?.length ?? 0) > 1;
  const numOptions = (question.options?.length ?? 0) + (hasAll ? 1 : 0) + 1;
  const numLen = String(numOptions).length;
  const radioWidth = 2;
  const numberWidth = numLen + 2;
  const checkboxWidth = question.multiSelect ? 4 : 1;
  const checkmarkWidth = question.multiSelect ? 0 : 2;
  const cursorPadding = 1;
  const horizontalPadding = radioWidth + numberWidth + checkboxWidth + checkmarkWidth + cursorPadding;
  const bufferWidth = availableWidth - horizontalPadding;
  const questionOptions = (0, import_react48.useMemo)(
    () => question.options ?? [],
    [question.options]
  );
  const initialReducerState = (0, import_react48.useMemo)(() => {
    if (!initialAnswer) {
      return {
        selectedIndices: /* @__PURE__ */ new Set(),
        isCustomOptionSelected: false,
        isCustomOptionFocused: false
      };
    }
    const selectedIndices2 = /* @__PURE__ */ new Set();
    let isCustomOptionSelected2 = false;
    if (question.multiSelect) {
      const answers = initialAnswer.split(", ");
      answers.forEach((answer) => {
        const index = questionOptions.findIndex((opt) => opt.label === answer);
        if (index !== -1) {
          selectedIndices2.add(index);
        } else {
          isCustomOptionSelected2 = true;
        }
      });
    } else {
      const index = questionOptions.findIndex(
        (opt) => opt.label === initialAnswer
      );
      if (index !== -1) {
        selectedIndices2.add(index);
      } else {
        isCustomOptionSelected2 = true;
      }
    }
    return {
      selectedIndices: selectedIndices2,
      isCustomOptionSelected: isCustomOptionSelected2,
      isCustomOptionFocused: false
    };
  }, [initialAnswer, questionOptions, question.multiSelect]);
  const [state, dispatch] = (0, import_react48.useReducer)(
    choiceQuestionReducer,
    initialReducerState
  );
  const { selectedIndices, isCustomOptionSelected, isCustomOptionFocused } = state;
  const initialCustomText = (0, import_react48.useMemo)(() => {
    if (!initialAnswer) return "";
    if (question.multiSelect) {
      const answers = initialAnswer.split(", ");
      const custom = answers.find(
        (a) => !questionOptions.some((opt) => opt.label === a)
      );
      return custom || "";
    } else {
      const isPredefined = questionOptions.some(
        (opt) => opt.label === initialAnswer
      );
      return isPredefined ? "" : initialAnswer;
    }
  }, [initialAnswer, questionOptions, question.multiSelect]);
  const customBuffer = useTextBuffer({
    initialText: initialCustomText,
    viewport: { width: Math.max(1, bufferWidth), height: 3 },
    singleLine: false
  });
  const customOptionText = customBuffer.text;
  const buildAnswerString = (0, import_react48.useCallback)(
    (indices, includeCustomOption, customOption) => {
      const answers = [];
      questionOptions.forEach((opt, i) => {
        if (indices.has(i)) {
          answers.push(opt.label);
        }
      });
      if (includeCustomOption && customOption.trim()) {
        const expanded = expandPastePlaceholders(
          customOption,
          customBuffer.pastedContent
        );
        answers.push(expanded.trim());
      }
      return answers.join(", ");
    },
    [questionOptions, customBuffer.pastedContent]
  );
  const lastBuiltAnswerRef = (0, import_react48.useRef)("");
  (0, import_react48.useEffect)(() => {
    const newAnswer = buildAnswerString(
      selectedIndices,
      isCustomOptionSelected,
      customOptionText
    );
    if (newAnswer !== lastBuiltAnswerRef.current) {
      onSelectionChange?.(newAnswer);
      lastBuiltAnswerRef.current = newAnswer;
    }
  }, [
    selectedIndices,
    isCustomOptionSelected,
    customOptionText,
    buildAnswerString,
    onSelectionChange
  ]);
  const handleExtraKeys = (0, import_react48.useCallback)(
    (key) => {
      if (isCustomOptionFocused && keyMatchers["basic.quit" /* QUIT */](key)) {
        if (customOptionText === "") {
          return false;
        }
        customBuffer.setText("");
        return true;
      }
      if (keyMatchers["nav.dialog.up" /* DIALOG_NAVIGATION_UP */](key) || keyMatchers["nav.dialog.down" /* DIALOG_NAVIGATION_DOWN */](key) || keyMatchers["nav.dialog.next" /* DIALOG_NEXT */](key) || keyMatchers["nav.dialog.previous" /* DIALOG_PREV */](key) || keyMatchers["cursor.left" /* MOVE_LEFT */](key) || keyMatchers["cursor.right" /* MOVE_RIGHT */](key) || keyMatchers["basic.confirm" /* RETURN */](key) || keyMatchers["basic.cancel" /* ESCAPE */](key) || keyMatchers["basic.quit" /* QUIT */](key)) {
        return false;
      }
      const isNumeric = /^[0-9]$/.test(key.sequence);
      if (isNumeric) {
        return false;
      }
      const isPrintable = key.sequence && !key.ctrl && !key.alt && (key.sequence.length > 1 || key.sequence.charCodeAt(0) >= 32);
      if (isPrintable && !isCustomOptionFocused) {
        dispatch({ type: "SET_CUSTOM_FOCUSED", payload: { focused: true } });
        onEditingCustomOption?.(true);
        customBuffer.setText(key.sequence);
        return true;
      }
      return false;
    },
    [
      isCustomOptionFocused,
      customBuffer,
      onEditingCustomOption,
      customOptionText,
      keyMatchers
    ]
  );
  useKeypress(handleExtraKeys, { isActive: true, priority: true });
  const selectionItems = (0, import_react48.useMemo)(() => {
    const list = questionOptions.map(
      (opt, i) => {
        const item = {
          key: `opt-${i}`,
          label: opt.label,
          description: opt.description,
          type: "option",
          index: i
        };
        return { key: item.key, value: item };
      }
    );
    if (question.multiSelect && questionOptions.length > 1) {
      const allItem = {
        key: "all",
        label: "All of the above",
        description: "Select all options",
        type: "all",
        index: list.length
      };
      list.push({ key: "all", value: allItem });
    }
    const otherItem = {
      key: "other",
      label: customOptionText || "",
      description: "",
      type: "other",
      index: list.length
    };
    list.push({ key: "other", value: otherItem });
    if (question.multiSelect) {
      const doneItem = {
        key: "done",
        label: "Done",
        description: "Finish selection",
        type: "done",
        index: list.length
      };
      list.push({ key: doneItem.key, value: doneItem, hideNumber: true });
    }
    return list;
  }, [questionOptions, question.multiSelect, customOptionText]);
  const handleHighlight = (0, import_react48.useCallback)(
    (itemValue) => {
      const nowFocusingCustomOption = itemValue.type === "other";
      dispatch({
        type: "SET_CUSTOM_FOCUSED",
        payload: { focused: nowFocusingCustomOption }
      });
      onEditingCustomOption?.(nowFocusingCustomOption);
    },
    [onEditingCustomOption]
  );
  const handleSelect = (0, import_react48.useCallback)(
    (itemValue) => {
      if (question.multiSelect) {
        if (itemValue.type === "option") {
          dispatch({
            type: "TOGGLE_INDEX",
            payload: { index: itemValue.index, multiSelect: true }
          });
        } else if (itemValue.type === "other") {
          dispatch({
            type: "TOGGLE_CUSTOM_SELECTED",
            payload: { multiSelect: true }
          });
        } else if (itemValue.type === "all") {
          dispatch({
            type: "TOGGLE_ALL",
            payload: { totalOptions: questionOptions.length }
          });
        } else if (itemValue.type === "done") {
          onAnswer(
            buildAnswerString(
              selectedIndices,
              isCustomOptionSelected,
              customOptionText
            )
          );
        }
      } else {
        if (itemValue.type === "option") {
          onAnswer(itemValue.label);
        } else if (itemValue.type === "other") {
          if (customOptionText.trim()) {
            onAnswer(
              expandPastePlaceholders(
                customOptionText,
                customBuffer.pastedContent
              ).trim()
            );
          }
        }
      }
    },
    [
      question.multiSelect,
      questionOptions.length,
      selectedIndices,
      isCustomOptionSelected,
      customOptionText,
      customBuffer.pastedContent,
      onAnswer,
      buildAnswerString
    ]
  );
  (0, import_react48.useEffect)(() => {
    if (customOptionText.trim() && !isCustomOptionSelected) {
      dispatch({
        type: "SET_CUSTOM_SELECTED",
        payload: { selected: true, multiSelect: !!question.multiSelect }
      });
    }
  }, [customOptionText, isCustomOptionSelected, question.multiSelect]);
  const HEADER_HEIGHT2 = progressHeader ? 2 : 0;
  const TITLE_MARGIN = 1;
  const FOOTER_HEIGHT2 = 2;
  const overhead = HEADER_HEIGHT2 + TITLE_MARGIN + FOOTER_HEIGHT2;
  const listHeight = availableHeight ? Math.max(1, availableHeight - overhead) : void 0;
  const reservedListHeight = Math.min(selectionItems.length * 2, 6);
  const questionHeightLimit = listHeight && !isAlternateBuffer ? question.unconstrainedHeight ? Math.max(1, listHeight - selectionItems.length * 2) : Math.max(1, listHeight - Math.max(DIALOG_PADDING, reservedListHeight)) : void 0;
  const maxItemsToShow = listHeight && (!isAlternateBuffer || availableHeight !== void 0) ? Math.min(
    selectionItems.length,
    Math.max(
      1,
      Math.floor((listHeight - (questionHeightLimit ?? 0)) / 2)
    )
  ) : selectionItems.length;
  return /* @__PURE__ */ (0, import_jsx_runtime69.jsxs)(Box_default, { flexDirection: "column", children: [
    progressHeader,
    /* @__PURE__ */ (0, import_jsx_runtime69.jsx)(Box_default, { marginBottom: TITLE_MARGIN, children: /* @__PURE__ */ (0, import_jsx_runtime69.jsx)(
      MaxSizedBox,
      {
        maxHeight: questionHeightLimit,
        maxWidth: availableWidth,
        overflowDirection: "bottom",
        children: /* @__PURE__ */ (0, import_jsx_runtime69.jsxs)(Box_default, { flexDirection: "column", children: [
          /* @__PURE__ */ (0, import_jsx_runtime69.jsx)(
            MarkdownDisplay,
            {
              text: autoBoldIfPlain(question.question),
              terminalWidth: availableWidth - DIALOG_PADDING,
              isPending: false
            }
          ),
          question.multiSelect && /* @__PURE__ */ (0, import_jsx_runtime69.jsx)(Text, { color: theme.text.secondary, italic: true, children: "(Select all that apply)" })
        ] })
      }
    ) }),
    /* @__PURE__ */ (0, import_jsx_runtime69.jsx)(
      BaseSelectionList,
      {
        items: selectionItems,
        onSelect: handleSelect,
        onHighlight: handleHighlight,
        focusKey: isCustomOptionFocused ? "other" : void 0,
        maxItemsToShow,
        showScrollArrows: true,
        renderItem: (item, context) => {
          const optionItem = item.value;
          const isChecked = optionItem.type === "option" && selectedIndices.has(optionItem.index) || optionItem.type === "other" && isCustomOptionSelected || optionItem.type === "all" && selectedIndices.size === questionOptions.length;
          const showCheck = question.multiSelect && (optionItem.type === "option" || optionItem.type === "other" || optionItem.type === "all");
          if (optionItem.type === "other") {
            const placeholder = question.placeholder || "Enter a custom value";
            return /* @__PURE__ */ (0, import_jsx_runtime69.jsxs)(Box_default, { flexDirection: "row", children: [
              showCheck && /* @__PURE__ */ (0, import_jsx_runtime69.jsxs)(
                Text,
                {
                  color: isChecked ? theme.status.success : theme.text.secondary,
                  children: [
                    "[",
                    isChecked ? "x" : " ",
                    "]"
                  ]
                }
              ),
              /* @__PURE__ */ (0, import_jsx_runtime69.jsx)(Text, { color: theme.text.primary, children: " " }),
              /* @__PURE__ */ (0, import_jsx_runtime69.jsx)(
                TextInput,
                {
                  buffer: customBuffer,
                  placeholder,
                  focus: context.isSelected,
                  onSubmit: (val) => {
                    if (question.multiSelect) {
                      const fullAnswer = buildAnswerString(
                        selectedIndices,
                        true,
                        val
                      );
                      if (fullAnswer) {
                        onAnswer(fullAnswer);
                      }
                    } else if (val.trim()) {
                      onAnswer(val.trim());
                    }
                  }
                }
              ),
              isChecked && !question.multiSelect && !context.isSelected && /* @__PURE__ */ (0, import_jsx_runtime69.jsx)(Text, { color: theme.status.success, children: " \u2713" })
            ] });
          }
          const labelColor = isChecked && !question.multiSelect ? theme.status.success : context.isSelected ? context.titleColor : theme.text.primary;
          return /* @__PURE__ */ (0, import_jsx_runtime69.jsxs)(Box_default, { flexDirection: "column", children: [
            /* @__PURE__ */ (0, import_jsx_runtime69.jsxs)(Box_default, { flexDirection: "row", children: [
              showCheck && /* @__PURE__ */ (0, import_jsx_runtime69.jsxs)(
                Text,
                {
                  color: isChecked ? theme.status.success : theme.text.secondary,
                  children: [
                    "[",
                    isChecked ? "x" : " ",
                    "]"
                  ]
                }
              ),
              /* @__PURE__ */ (0, import_jsx_runtime69.jsxs)(Text, { color: labelColor, bold: optionItem.type === "done", children: [
                " ",
                optionItem.label
              ] }),
              isChecked && !question.multiSelect && /* @__PURE__ */ (0, import_jsx_runtime69.jsx)(Text, { color: theme.status.success, children: " \u2713" })
            ] }),
            optionItem.description && /* @__PURE__ */ (0, import_jsx_runtime69.jsxs)(Text, { color: theme.text.secondary, wrap: "wrap", children: [
              " ",
              /* @__PURE__ */ (0, import_jsx_runtime69.jsx)(
                RenderInline,
                {
                  text: optionItem.description,
                  defaultColor: theme.text.secondary
                }
              )
            ] })
          ] });
        }
      }
    ),
    keyboardHints
  ] });
};
var AskUserDialog = ({
  questions,
  onSubmit,
  onCancel,
  onActiveTextInputChange,
  width,
  availableHeight: availableHeightProp,
  extraParts
}) => {
  const keyMatchers = useKeyMatchers();
  const uiState = (0, import_react48.useContext)(UIStateContext);
  const availableHeight = availableHeightProp ?? (uiState?.constrainHeight !== false ? uiState?.availableTerminalHeight : void 0);
  const [state, dispatch] = (0, import_react48.useReducer)(askUserDialogReducerLogic, initialState);
  const { answers, isEditingCustomOption, submitted } = state;
  const reviewTabIndex = questions.length;
  const tabCount = questions.length > 1 ? questions.length + 1 : questions.length;
  const { currentIndex, goToNextTab, goToPrevTab } = useTabbedNavigation({
    tabCount,
    isActive: !submitted && questions.length > 1,
    enableArrowNavigation: false,
    // We'll handle arrows via textBuffer callbacks or manually
    enableTabKey: false
    // We'll handle tab manually to match existing behavior
  });
  const currentQuestionIndex = currentIndex;
  const handleEditingCustomOption = (0, import_react48.useCallback)((isEditing) => {
    dispatch({ type: "SET_EDITING_CUSTOM", payload: { isEditing } });
  }, []);
  (0, import_react48.useEffect)(() => {
    onActiveTextInputChange?.(isEditingCustomOption);
    return () => {
      onActiveTextInputChange?.(false);
    };
  }, [isEditingCustomOption, onActiveTextInputChange]);
  const handleCancel = (0, import_react48.useCallback)(
    (key) => {
      if (submitted) return false;
      if (keyMatchers["basic.cancel" /* ESCAPE */](key)) {
        onCancel();
        return true;
      } else if (keyMatchers["basic.quit" /* QUIT */](key)) {
        if (!isEditingCustomOption) {
          onCancel();
        }
        return false;
      }
      return false;
    },
    [onCancel, submitted, isEditingCustomOption, keyMatchers]
  );
  useKeypress(handleCancel, {
    isActive: !submitted
  });
  const isOnReviewTab = currentQuestionIndex === reviewTabIndex;
  const handleNavigation = (0, import_react48.useCallback)(
    (key) => {
      if (submitted || questions.length <= 1) return false;
      const isNextKey = keyMatchers["nav.dialog.next" /* DIALOG_NEXT */](key);
      const isPrevKey = keyMatchers["nav.dialog.previous" /* DIALOG_PREV */](key);
      const isRight = keyMatchers["cursor.right" /* MOVE_RIGHT */](key);
      const isLeft = keyMatchers["cursor.left" /* MOVE_LEFT */](key);
      const shouldGoNext = isNextKey || isRight;
      const shouldGoPrev = isPrevKey || isLeft;
      if (shouldGoNext) {
        goToNextTab();
        return true;
      } else if (shouldGoPrev) {
        goToPrevTab();
        return true;
      }
      return false;
    },
    [questions.length, submitted, goToNextTab, goToPrevTab, keyMatchers]
  );
  useKeypress(handleNavigation, {
    isActive: questions.length > 1 && !submitted
  });
  (0, import_react48.useEffect)(() => {
    if (submitted) {
      onSubmit(answers);
    }
  }, [submitted, answers, onSubmit]);
  const handleAnswer = (0, import_react48.useCallback)(
    (answer) => {
      if (submitted) return;
      if (questions.length > 1) {
        dispatch({
          type: "SET_ANSWER",
          payload: {
            index: currentQuestionIndex,
            answer
          }
        });
        goToNextTab();
      } else {
        dispatch({
          type: "SET_ANSWER",
          payload: {
            index: currentQuestionIndex,
            answer,
            submit: true
          }
        });
      }
    },
    [currentQuestionIndex, questions, submitted, goToNextTab]
  );
  const handleReviewSubmit = (0, import_react48.useCallback)(() => {
    if (submitted) return;
    dispatch({ type: "SUBMIT" });
  }, [submitted]);
  const handleSelectionChange = (0, import_react48.useCallback)(
    (answer) => {
      if (submitted) return;
      dispatch({
        type: "SET_ANSWER",
        payload: {
          index: currentQuestionIndex,
          answer
        }
      });
    },
    [submitted, currentQuestionIndex]
  );
  const answeredIndices = (0, import_react48.useMemo)(
    () => new Set(Object.keys(answers).map(Number)),
    [answers]
  );
  const currentQuestion = questions[currentQuestionIndex];
  const effectiveQuestion = (0, import_react48.useMemo)(() => {
    if (currentQuestion?.type === "yesno") {
      return {
        ...currentQuestion,
        options: [
          { label: "Yes", description: "" },
          { label: "No", description: "" }
        ],
        multiSelect: false
      };
    }
    return currentQuestion;
  }, [currentQuestion]);
  const tabs = (0, import_react48.useMemo)(() => {
    const questionTabs = questions.map((q, i) => ({
      key: String(i),
      header: q.header
    }));
    if (questions.length > 1) {
      questionTabs.push({
        key: "review",
        header: "Review",
        isSpecial: true
      });
    }
    return questionTabs;
  }, [questions]);
  const progressHeader = questions.length > 1 ? /* @__PURE__ */ (0, import_jsx_runtime69.jsx)(
    TabHeader,
    {
      tabs,
      currentIndex: currentQuestionIndex,
      completedIndices: answeredIndices
    }
  ) : null;
  if (isOnReviewTab) {
    return /* @__PURE__ */ (0, import_jsx_runtime69.jsx)(Box_default, { "aria-label": "Review your answers", children: /* @__PURE__ */ (0, import_jsx_runtime69.jsx)(
      ReviewView,
      {
        questions,
        answers,
        onSubmit: handleReviewSubmit,
        progressHeader,
        extraParts
      }
    ) });
  }
  if (!currentQuestion) return null;
  const keyboardHints = /* @__PURE__ */ (0, import_jsx_runtime69.jsx)(
    DialogFooter,
    {
      primaryAction: currentQuestion.type === "text" || isEditingCustomOption ? "Enter to submit" : "Enter to select",
      navigationActions: questions.length > 1 ? currentQuestion.type === "text" || isEditingCustomOption ? `${formatCommand("nav.dialog.next" /* DIALOG_NEXT */)}/${formatCommand("nav.dialog.previous" /* DIALOG_PREV */)} to switch questions` : "\u2190/\u2192 to switch questions" : currentQuestion.type === "text" || isEditingCustomOption ? void 0 : "\u2191/\u2193 to navigate",
      extraParts
    }
  );
  const questionView = currentQuestion.type === "text" ? /* @__PURE__ */ (0, import_jsx_runtime69.jsx)(
    TextQuestionView,
    {
      question: currentQuestion,
      onAnswer: handleAnswer,
      onSelectionChange: handleSelectionChange,
      onEditingCustomOption: handleEditingCustomOption,
      availableWidth: width,
      availableHeight,
      initialAnswer: answers[currentQuestionIndex],
      progressHeader,
      keyboardHints
    },
    currentQuestionIndex
  ) : /* @__PURE__ */ (0, import_jsx_runtime69.jsx)(
    ChoiceQuestionView,
    {
      question: effectiveQuestion,
      onAnswer: handleAnswer,
      onSelectionChange: handleSelectionChange,
      onEditingCustomOption: handleEditingCustomOption,
      availableWidth: width,
      availableHeight,
      initialAnswer: answers[currentQuestionIndex],
      progressHeader,
      keyboardHints
    },
    currentQuestionIndex
  );
  return /* @__PURE__ */ (0, import_jsx_runtime69.jsx)(
    Box_default,
    {
      flexDirection: "column",
      width,
      "aria-label": `Question ${currentQuestionIndex + 1} of ${questions.length}: ${currentQuestion.question}`,
      children: questionView
    }
  );
};

// packages/cli/src/ui/components/ExitPlanModeDialog.tsx
var import_react49 = __toESM(require_react(), 1);
var import_jsx_runtime70 = __toESM(require_jsx_runtime(), 1);
var StatusMessage = ({ children }) => /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(Box_default, { paddingX: 1, children });
function usePlanContent(planPath, config) {
  const [version, setVersion] = (0, import_react49.useState)(0);
  const [state, setState] = (0, import_react49.useState)({
    status: "loading" /* Loading */
  });
  const refresh = (0, import_react49.useCallback)(() => {
    setVersion((v) => v + 1);
  }, []);
  (0, import_react49.useEffect)(() => {
    let ignore = false;
    setState({ status: "loading" /* Loading */ });
    const load = async () => {
      try {
        const pathError = await validatePlanPath(
          planPath,
          config.storage.getPlansDir()
        );
        if (ignore) return;
        if (pathError) {
          setState({ status: "error" /* Error */, error: pathError });
          return;
        }
        const contentError = await validatePlanContent(planPath);
        if (ignore) return;
        if (contentError) {
          setState({ status: "error" /* Error */, error: contentError });
          return;
        }
        const result = await processSingleFileContent(
          planPath,
          config.storage.getPlansDir(),
          config.getFileSystemService()
        );
        if (ignore) return;
        if (result.error) {
          setState({ status: "error" /* Error */, error: result.error });
          return;
        }
        if (typeof result.llmContent !== "string") {
          setState({
            status: "error" /* Error */,
            error: "Plan file format not supported (binary or image)."
          });
          return;
        }
        const content = result.llmContent;
        if (!content) {
          setState({ status: "error" /* Error */, error: "Plan file is empty." });
          return;
        }
        setState({ status: "loaded" /* Loaded */, content });
      } catch (err) {
        if (ignore) return;
        const errorMessage = err instanceof Error ? err.message : String(err);
        setState({ status: "error" /* Error */, error: errorMessage });
      }
    };
    void load();
    return () => {
      ignore = true;
    };
  }, [planPath, config, version]);
  return { ...state, refresh };
}
var ExitPlanModeDialog = ({
  planPath,
  onApprove,
  onFeedback,
  onCancel,
  getPreferredEditor,
  width,
  availableHeight
}) => {
  const keyMatchers = useKeyMatchers();
  const config = useConfig();
  const { stdin, setRawMode } = use_stdin_default();
  const planState = usePlanContent(planPath, config);
  const { refresh } = planState;
  const [showLoading, setShowLoading] = (0, import_react49.useState)(false);
  const handleOpenEditor = (0, import_react49.useCallback)(async () => {
    try {
      await openFileInEditor(planPath, stdin, setRawMode, getPreferredEditor());
      onFeedback(
        "I have edited the plan or annotated it with feedback. Review the edited plan, update if necessary, and present it again for approval."
      );
      refresh();
    } catch (err) {
      debugLogger.error("Failed to open plan in editor:", err);
    }
  }, [planPath, stdin, setRawMode, getPreferredEditor, refresh, onFeedback]);
  useKeypress(
    (key) => {
      if (keyMatchers["input.openExternalEditor" /* OPEN_EXTERNAL_EDITOR */](key)) {
        void handleOpenEditor();
        return true;
      }
      if (keyMatchers["input.deprecatedOpenExternalEditor" /* DEPRECATED_OPEN_EXTERNAL_EDITOR */](key)) {
        const cmdKey = formatCommand("input.openExternalEditor" /* OPEN_EXTERNAL_EDITOR */);
        appEvents.emit("transient-message" /* TransientMessage */, {
          message: `Use ${cmdKey} to open the external editor.`,
          type: "hint" /* Hint */
        });
        return true;
      }
      return false;
    },
    { isActive: true, priority: true }
  );
  (0, import_react49.useEffect)(() => {
    if (planState.status !== "loading" /* Loading */) {
      setShowLoading(false);
      return;
    }
    const timer = setTimeout(() => {
      setShowLoading(true);
    }, 200);
    return () => clearTimeout(timer);
  }, [planState.status]);
  if (planState.status === "loading" /* Loading */) {
    if (!showLoading) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(StatusMessage, { children: /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(Text, { color: theme.text.secondary, italic: true, children: "Loading plan..." }) });
  }
  if (planState.status === "error" /* Error */) {
    return /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(StatusMessage, { children: /* @__PURE__ */ (0, import_jsx_runtime70.jsxs)(Text, { color: theme.status.error, children: [
      "Error reading plan: ",
      planState.error
    ] }) });
  }
  const planContent = planState.content?.trim();
  if (!planContent) {
    return /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(StatusMessage, { children: /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(Text, { color: theme.status.error, children: "Error: Plan content is empty." }) });
  }
  const editHint = formatCommand("input.openExternalEditor" /* OPEN_EXTERNAL_EDITOR */);
  return /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(Box_default, { flexDirection: "column", width, children: /* @__PURE__ */ (0, import_jsx_runtime70.jsx)(
    AskUserDialog,
    {
      questions: [
        {
          type: QuestionType.CHOICE,
          header: "Approval",
          question: planContent,
          options: [
            {
              label: "Yes, automatically accept edits" /* Auto */,
              description: "Approves plan and allows tools to run automatically"
            },
            {
              label: "Yes, manually accept edits" /* Manual */,
              description: "Approves plan but requires confirmation for each tool"
            }
          ],
          placeholder: "Type your feedback...",
          multiSelect: false,
          unconstrainedHeight: false
        }
      ],
      onSubmit: (answers) => {
        const answer = answers["0"];
        if (answer === "Yes, automatically accept edits" /* Auto */) {
          onApprove(ApprovalMode.AUTO_EDIT);
        } else if (answer === "Yes, manually accept edits" /* Manual */) {
          onApprove(ApprovalMode.DEFAULT);
        } else if (answer) {
          onFeedback(answer);
        }
      },
      onCancel,
      width,
      availableHeight,
      extraParts: [`${editHint} to edit plan`]
    }
  ) });
};

// packages/cli/src/ui/utils/urlSecurityUtils.ts
import url from "node:url";
function containsDeceptiveMarkers(hostname) {
  return (
    // eslint-disable-next-line no-control-regex
    hostname.toLowerCase().includes("xn--") || /[^\x00-\x7F]/.test(hostname)
  );
}
function toUnicodeUrl(urlInput) {
  try {
    const urlObj = typeof urlInput === "string" ? new URL(urlInput) : urlInput;
    const punycodeHost = urlObj.hostname;
    const unicodeHost = url.domainToUnicode(punycodeHost);
    const protocol = urlObj.protocol + "//";
    const credentials = urlObj.username ? `${urlObj.username}${urlObj.password ? ":" + urlObj.password : ""}@` : "";
    const port = urlObj.port ? ":" + urlObj.port : "";
    return `${protocol}${credentials}${unicodeHost}${port}${urlObj.pathname}${urlObj.search}${urlObj.hash}`;
  } catch {
    return typeof urlInput === "string" ? urlInput : urlInput.href;
  }
}
function getDeceptiveUrlDetails(urlString) {
  try {
    if (!urlString.includes("://")) {
      return null;
    }
    const urlObj = new URL(urlString);
    if (!containsDeceptiveMarkers(urlObj.hostname)) {
      return null;
    }
    return {
      originalUrl: toUnicodeUrl(urlObj),
      punycodeUrl: urlObj.href
    };
  } catch {
    return null;
  }
}

// packages/cli/src/ui/components/messages/ToolConfirmationMessage.tsx
var import_jsx_runtime71 = __toESM(require_jsx_runtime(), 1);
var ToolConfirmationMessage = ({
  callId,
  confirmationDetails,
  config,
  getPreferredEditor,
  isFocused = true,
  availableTerminalHeight,
  terminalWidth,
  toolName
}) => {
  const keyMatchers = useKeyMatchers();
  const { confirm, isDiffingEnabled } = useToolActions();
  const [mcpDetailsExpansionState, setMcpDetailsExpansionState] = (0, import_react50.useState)({
    callId,
    expanded: false
  });
  const [isCancelling, setIsCancelling] = (0, import_react50.useState)(false);
  const isMcpToolDetailsExpanded = mcpDetailsExpansionState.callId === callId ? mcpDetailsExpansionState.expanded : false;
  const [measuredSecurityWarningsHeight, setMeasuredSecurityWarningsHeight] = (0, import_react50.useState)(0);
  const observerRef = (0, import_react50.useRef)(null);
  (0, import_react50.useEffect)(
    () => () => {
      observerRef.current?.disconnect();
    },
    []
  );
  const deceptiveUrlWarnings = (0, import_react50.useMemo)(() => {
    const urls = [];
    if (confirmationDetails.type === "info" && confirmationDetails.urls) {
      urls.push(...confirmationDetails.urls);
    } else if (confirmationDetails.type === "exec") {
      const commands = confirmationDetails.commands && confirmationDetails.commands.length > 0 ? confirmationDetails.commands : [confirmationDetails.command];
      for (const cmd of commands) {
        const matches = cmd.match(/https?:\/\/[^\s"'`<>;&|()]+/g);
        if (matches) urls.push(...matches);
      }
    }
    const uniqueUrls = Array.from(new Set(urls));
    return uniqueUrls.map(getDeceptiveUrlDetails).filter((d) => d !== null);
  }, [confirmationDetails]);
  const deceptiveUrlWarningText = (0, import_react50.useMemo)(() => {
    if (deceptiveUrlWarnings.length === 0) return null;
    return `**Warning:** Deceptive URL(s) detected:

${deceptiveUrlWarnings.map(
      (w) => `   **Original:** ${w.originalUrl}
   **Actual Host (Punycode):** ${w.punycodeUrl}`
    ).join("\n\n")}`;
  }, [deceptiveUrlWarnings]);
  const onSecurityWarningsRefChange = (0, import_react50.useCallback)((node) => {
    if (observerRef.current) {
      observerRef.current.disconnect();
      observerRef.current = null;
    }
    if (node) {
      const observer = new ResizeObserver((entries) => {
        const entry = entries[0];
        if (entry) {
          const newHeight = Math.round(entry.contentRect.height);
          setMeasuredSecurityWarningsHeight(
            (prev) => newHeight !== prev ? newHeight : prev
          );
        }
      });
      observer.observe(node);
      observerRef.current = observer;
    } else {
      setMeasuredSecurityWarningsHeight((prev) => prev !== 0 ? 0 : prev);
    }
  }, []);
  const settings = useSettings();
  const activeTheme = themeManager.getActiveTheme();
  const allowPermanentApproval = settings.merged.security.enablePermanentToolApproval && !config.getDisableAlwaysAllow();
  const handlesOwnUI = confirmationDetails.type === "ask_user" || confirmationDetails.type === "exit_plan_mode";
  const isTrustedFolder = config.isTrustedFolder() && !config.getDisableAlwaysAllow();
  const handleConfirm = (0, import_react50.useCallback)(
    (outcome, payload) => {
      void confirm(callId, outcome, payload).catch((error) => {
        debugLogger.error(
          `Failed to handle tool confirmation for ${callId}:`,
          error
        );
      });
    },
    [confirm, callId]
  );
  const mcpToolDetailsText = (0, import_react50.useMemo)(() => {
    if (confirmationDetails.type !== "mcp") {
      return null;
    }
    const detailsLines = [];
    const hasNonEmptyToolArgs = confirmationDetails.toolArgs !== void 0 && !(typeof confirmationDetails.toolArgs === "object" && confirmationDetails.toolArgs !== null && Object.keys(confirmationDetails.toolArgs).length === 0);
    if (hasNonEmptyToolArgs) {
      let argsText;
      try {
        argsText = stripUnsafeCharacters(
          JSON.stringify(confirmationDetails.toolArgs, null, 2)
        );
      } catch {
        argsText = "[unserializable arguments]";
      }
      detailsLines.push("Invocation Arguments:");
      detailsLines.push(argsText);
    }
    const description = confirmationDetails.toolDescription?.trim();
    if (description) {
      if (detailsLines.length > 0) {
        detailsLines.push("");
      }
      detailsLines.push("Description:");
      detailsLines.push(stripUnsafeCharacters(description));
    }
    if (confirmationDetails.toolParameterSchema !== void 0) {
      let schemaText;
      try {
        schemaText = stripUnsafeCharacters(
          JSON.stringify(confirmationDetails.toolParameterSchema, null, 2)
        );
      } catch {
        schemaText = "[unserializable schema]";
      }
      if (detailsLines.length > 0) {
        detailsLines.push("");
      }
      detailsLines.push("Input Schema:");
      detailsLines.push(schemaText);
    }
    if (detailsLines.length === 0) {
      return null;
    }
    return detailsLines.join("\n");
  }, [confirmationDetails]);
  const hasMcpToolDetails = !!mcpToolDetailsText;
  const expandDetailsHintKey = formatCommand("app.showMoreLines" /* SHOW_MORE_LINES */);
  useKeypress(
    (key) => {
      if (!isFocused) return false;
      if (confirmationDetails.type === "mcp" && hasMcpToolDetails && keyMatchers["app.showMoreLines" /* SHOW_MORE_LINES */](key)) {
        setMcpDetailsExpansionState({
          callId,
          expanded: !isMcpToolDetailsExpanded
        });
        return true;
      }
      if (keyMatchers["basic.cancel" /* ESCAPE */](key)) {
        setIsCancelling(true);
        return true;
      }
      if (keyMatchers["basic.quit" /* QUIT */](key)) {
        return false;
      }
      return false;
    },
    { isActive: isFocused, priority: true }
  );
  (0, import_react50.useEffect)(() => {
    if (isCancelling) {
      handleConfirm(ToolConfirmationOutcome.Cancel);
    }
  }, [isCancelling, handleConfirm]);
  const handleSelect = (0, import_react50.useCallback)(
    (item) => handleConfirm(item),
    [handleConfirm]
  );
  const getOptions = (0, import_react50.useCallback)(() => {
    const options2 = [];
    if (confirmationDetails.type === "edit") {
      if (!confirmationDetails.isModifying) {
        options2.push({
          label: "Allow once",
          value: ToolConfirmationOutcome.ProceedOnce,
          key: "Allow once"
        });
        if (isTrustedFolder) {
          options2.push({
            label: "Allow for this session",
            value: ToolConfirmationOutcome.ProceedAlways,
            key: "Allow for this session"
          });
          if (allowPermanentApproval) {
            options2.push({
              label: "Allow for this file in all future sessions",
              value: ToolConfirmationOutcome.ProceedAlwaysAndSave,
              key: "Allow for this file in all future sessions"
            });
          }
        }
        if (!config.getIdeMode() || !isDiffingEnabled) {
          options2.push({
            label: "Modify with external editor",
            value: ToolConfirmationOutcome.ModifyWithEditor,
            key: "Modify with external editor"
          });
        }
        options2.push({
          label: "No, suggest changes (esc)",
          value: ToolConfirmationOutcome.Cancel,
          key: "No, suggest changes (esc)"
        });
      }
    } else if (confirmationDetails.type === "sandbox_expansion") {
      options2.push({
        label: "Allow once",
        value: ToolConfirmationOutcome.ProceedOnce,
        key: "Allow once"
      });
      if (isTrustedFolder) {
        options2.push({
          label: "Allow for this session",
          value: ToolConfirmationOutcome.ProceedAlways,
          key: "Allow for this session"
        });
        if (allowPermanentApproval) {
          options2.push({
            label: "Allow for all future sessions",
            value: ToolConfirmationOutcome.ProceedAlwaysAndSave,
            key: "Allow for all future sessions"
          });
        }
      }
      options2.push({
        label: "No, suggest changes (esc)",
        value: ToolConfirmationOutcome.Cancel,
        key: "No, suggest changes (esc)"
      });
    } else if (confirmationDetails.type === "exec") {
      options2.push({
        label: "Allow once",
        value: ToolConfirmationOutcome.ProceedOnce,
        key: "Allow once"
      });
      if (isTrustedFolder) {
        options2.push({
          label: `Allow for this session`,
          value: ToolConfirmationOutcome.ProceedAlways,
          key: `Allow for this session`
        });
        if (allowPermanentApproval) {
          options2.push({
            label: `Allow this command for all future sessions`,
            value: ToolConfirmationOutcome.ProceedAlwaysAndSave,
            key: `Allow for all future sessions`
          });
        }
      }
      options2.push({
        label: "No, suggest changes (esc)",
        value: ToolConfirmationOutcome.Cancel,
        key: "No, suggest changes (esc)"
      });
    } else if (confirmationDetails.type === "info") {
      options2.push({
        label: "Allow once",
        value: ToolConfirmationOutcome.ProceedOnce,
        key: "Allow once"
      });
      if (isTrustedFolder) {
        options2.push({
          label: "Allow for this session",
          value: ToolConfirmationOutcome.ProceedAlways,
          key: "Allow for this session"
        });
        if (allowPermanentApproval) {
          options2.push({
            label: "Allow for all future sessions",
            value: ToolConfirmationOutcome.ProceedAlwaysAndSave,
            key: "Allow for all future sessions"
          });
        }
      }
      options2.push({
        label: "No, suggest changes (esc)",
        value: ToolConfirmationOutcome.Cancel,
        key: "No, suggest changes (esc)"
      });
    } else if (confirmationDetails.type === "mcp") {
      options2.push({
        label: "Allow once",
        value: ToolConfirmationOutcome.ProceedOnce,
        key: "Allow once"
      });
      if (isTrustedFolder) {
        options2.push({
          label: "Allow tool for this session",
          value: ToolConfirmationOutcome.ProceedAlwaysTool,
          key: "Allow tool for this session"
        });
        options2.push({
          label: "Allow all server tools for this session",
          value: ToolConfirmationOutcome.ProceedAlwaysServer,
          key: "Allow all server tools for this session"
        });
        if (allowPermanentApproval) {
          options2.push({
            label: "Allow tool for all future sessions",
            value: ToolConfirmationOutcome.ProceedAlwaysAndSave,
            key: "Allow tool for all future sessions"
          });
        }
      }
      options2.push({
        label: "No, suggest changes (esc)",
        value: ToolConfirmationOutcome.Cancel,
        key: "No, suggest changes (esc)"
      });
    }
    return options2;
  }, [
    confirmationDetails,
    isTrustedFolder,
    allowPermanentApproval,
    config,
    isDiffingEnabled
  ]);
  const availableBodyContentHeight = (0, import_react50.useCallback)(() => {
    if (availableTerminalHeight === void 0) {
      return void 0;
    }
    if (handlesOwnUI) {
      return availableTerminalHeight;
    }
    const PADDING_OUTER_Y = 0;
    const HEIGHT_QUESTION = 1;
    const MARGIN_QUESTION_TOP = 0;
    const MARGIN_QUESTION_BOTTOM = 1;
    const SECURITY_WARNING_BOTTOM_MARGIN = 1;
    const SHOW_MORE_LINES_HEIGHT = 1;
    const optionsCount = getOptions().length;
    const securityWarningsHeight = deceptiveUrlWarningText ? measuredSecurityWarningsHeight + SECURITY_WARNING_BOTTOM_MARGIN : 0;
    let extraInfoLines = 0;
    if (confirmationDetails.type === "sandbox_expansion") {
      const { additionalPermissions } = confirmationDetails;
      if (additionalPermissions?.network) extraInfoLines++;
      extraInfoLines += additionalPermissions?.fileSystem?.read?.length || 0;
      extraInfoLines += additionalPermissions?.fileSystem?.write?.length || 0;
    } else if (confirmationDetails.type === "exec") {
      const executionProps = confirmationDetails;
      const commandsToDisplay = executionProps.commands && executionProps.commands.length > 0 ? executionProps.commands : [executionProps.command];
      const containsRedirection = commandsToDisplay.some(
        (cmd) => hasRedirection(cmd)
      );
      const isAutoEdit = config.getApprovalMode() === ApprovalMode.YOLO || config.getApprovalMode() === ApprovalMode.AUTO_EDIT;
      if (containsRedirection && !isAutoEdit) {
        extraInfoLines = 1;
      }
    }
    const surroundingElementsHeight = PADDING_OUTER_Y + HEIGHT_QUESTION + MARGIN_QUESTION_TOP + MARGIN_QUESTION_BOTTOM + SHOW_MORE_LINES_HEIGHT + optionsCount + securityWarningsHeight + extraInfoLines;
    return Math.max(availableTerminalHeight - surroundingElementsHeight, 2);
  }, [
    availableTerminalHeight,
    handlesOwnUI,
    getOptions,
    measuredSecurityWarningsHeight,
    deceptiveUrlWarningText,
    confirmationDetails,
    config
  ]);
  const { question, bodyContent, options, securityWarnings, initialIndex } = (0, import_react50.useMemo)(() => {
    let bodyContent2 = null;
    let securityWarnings2 = null;
    let question2 = "";
    const options2 = getOptions();
    let initialIndex2 = 0;
    if (isTrustedFolder && allowPermanentApproval) {
      const isSafeToPersist = confirmationDetails.type === "info" || confirmationDetails.type === "edit" || confirmationDetails.type === "mcp";
      if (isSafeToPersist && settings.merged.security.autoAddToPolicyByDefault) {
        const alwaysAndSaveIndex = options2.findIndex(
          (o) => o.value === ToolConfirmationOutcome.ProceedAlwaysAndSave
        );
        if (alwaysAndSaveIndex !== -1) {
          initialIndex2 = alwaysAndSaveIndex;
        }
      }
    }
    if (deceptiveUrlWarningText) {
      securityWarnings2 = /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(WarningMessage, { text: deceptiveUrlWarningText });
    }
    const bodyHeight = availableBodyContentHeight();
    if (confirmationDetails.type === "ask_user") {
      bodyContent2 = /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(
        AskUserDialog,
        {
          questions: confirmationDetails.questions,
          onSubmit: (answers) => {
            handleConfirm(ToolConfirmationOutcome.ProceedOnce, { answers });
          },
          onCancel: () => {
            handleConfirm(ToolConfirmationOutcome.Cancel);
          },
          width: terminalWidth,
          availableHeight: bodyHeight
        }
      );
      return {
        question: "",
        bodyContent: bodyContent2,
        options: [],
        securityWarnings: null,
        initialIndex: 0
      };
    }
    if (confirmationDetails.type === "exit_plan_mode") {
      bodyContent2 = /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(
        ExitPlanModeDialog,
        {
          planPath: confirmationDetails.planPath,
          getPreferredEditor,
          onApprove: (approvalMode) => {
            handleConfirm(ToolConfirmationOutcome.ProceedOnce, {
              approved: true,
              approvalMode
            });
          },
          onFeedback: (feedback) => {
            handleConfirm(ToolConfirmationOutcome.ProceedOnce, {
              approved: false,
              feedback
            });
          },
          onCancel: () => {
            handleConfirm(ToolConfirmationOutcome.Cancel);
          },
          width: terminalWidth,
          availableHeight: bodyHeight
        }
      );
      return {
        question: "",
        bodyContent: bodyContent2,
        options: [],
        securityWarnings: null,
        initialIndex: 0
      };
    }
    if (confirmationDetails.type === "edit") {
      if (!confirmationDetails.isModifying) {
        question2 = `Apply this change?`;
        bodyContent2 = /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(import_jsx_runtime71.Fragment, { children: /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(
          Box_default,
          {
            borderStyle: "round",
            borderColor: theme.border.default,
            paddingX: 1,
            paddingY: 0,
            marginBottom: 0,
            children: /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(
              DiffRenderer,
              {
                diffContent: stripUnsafeCharacters(
                  confirmationDetails.fileDiff
                ),
                filename: sanitizeForDisplay(confirmationDetails.fileName),
                availableTerminalHeight: bodyHeight !== void 0 ? Math.max(bodyHeight - 2, 2) : void 0,
                terminalWidth: Math.max(terminalWidth, 1) - 4
              }
            )
          }
        ) });
      }
    } else if (confirmationDetails.type === "sandbox_expansion") {
      const { additionalPermissions, command, rootCommand } = confirmationDetails;
      const readPaths = additionalPermissions?.fileSystem?.read || [];
      const writePaths = additionalPermissions?.fileSystem?.write || [];
      const network = additionalPermissions?.network;
      const isShell = isShellTool(toolName);
      const rootCmds = rootCommand.split(",").map((c2) => c2.trim().split(/\s+/)[0]).filter((c2) => c2 && !c2.startsWith("redirection"));
      const commandNames = Array.from(new Set(rootCmds)).join(", ");
      question2 = "";
      bodyContent2 = /* @__PURE__ */ (0, import_jsx_runtime71.jsxs)(import_jsx_runtime71.Fragment, { children: [
        /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(
          Box_default,
          {
            borderStyle: "round",
            borderColor: theme.border.default,
            paddingX: 1,
            paddingY: 0,
            marginBottom: 0,
            children: colorizeCode({
              code: command.trim(),
              language: "bash",
              maxWidth: Math.max(terminalWidth, 1) - 6,
              settings,
              theme: activeTheme,
              hideLineNumbers: true,
              availableHeight: bodyHeight !== void 0 ? Math.max(bodyHeight - 2, 2) : void 0
            })
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime71.jsxs)(Box_default, { flexDirection: "column", children: [
          /* @__PURE__ */ (0, import_jsx_runtime71.jsxs)(Text, { children: [
            "To run",
            " ",
            /* @__PURE__ */ (0, import_jsx_runtime71.jsxs)(
              Text,
              {
                color: isShell ? theme.status.warning : void 0,
                bold: isShell,
                children: [
                  "[",
                  sanitizeForDisplay(commandNames),
                  "]"
                ]
              }
            ),
            ", allow access to the following?"
          ] }),
          network && /* @__PURE__ */ (0, import_jsx_runtime71.jsxs)(Text, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(Text, { color: isShell ? theme.status.warning : void 0, bold: true, children: "\u2022 Network:" }),
            " ",
            "All Urls"
          ] }),
          writePaths.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime71.jsxs)(Text, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(Text, { color: isShell ? theme.status.warning : void 0, bold: true, children: "\u2022 Write:" }),
            " ",
            writePaths.map((p) => sanitizeForDisplay(p)).join(", ")
          ] }),
          readPaths.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime71.jsxs)(Text, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(Text, { color: isShell ? theme.status.warning : void 0, bold: true, children: "\u2022 Read:" }),
            " ",
            readPaths.map((p) => sanitizeForDisplay(p)).join(", ")
          ] })
        ] })
      ] });
    } else if (confirmationDetails.type === "exec") {
      const executionProps = confirmationDetails;
      const isShell = isShellTool(toolName);
      const commandsToDisplay = executionProps.commands && executionProps.commands.length > 1 ? executionProps.commands : [executionProps.command];
      const containsRedirection = commandsToDisplay.some(
        (cmd) => hasRedirection(cmd)
      );
      const isAutoEdit = config.getApprovalMode() === ApprovalMode.YOLO || config.getApprovalMode() === ApprovalMode.AUTO_EDIT;
      let warnings = null;
      if (containsRedirection && !isAutoEdit) {
        const tipText = `To auto-accept, press ${formatCommand("app.cycleApprovalMode" /* CYCLE_APPROVAL_MODE */)}`;
        warnings = /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(Box_default, { flexDirection: "column", marginBottom: 0, children: /* @__PURE__ */ (0, import_jsx_runtime71.jsxs)(Text, { color: theme.text.primary, children: [
          "Redirection detected.",
          " ",
          /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(Text, { color: theme.text.secondary, children: tipText })
        ] }) });
      }
      const commandNames = Array.from(
        new Set(
          commandsToDisplay.map((cmd) => cmd.trim().split(/\s+/)[0]).filter(Boolean)
        )
      ).join(", ");
      const allowQuestion = /* @__PURE__ */ (0, import_jsx_runtime71.jsxs)(Text, { children: [
        "Allow execution of",
        " ",
        /* @__PURE__ */ (0, import_jsx_runtime71.jsxs)(
          Text,
          {
            color: isShell ? theme.status.warning : void 0,
            bold: isShell,
            children: [
              "[",
              sanitizeForDisplay(commandNames),
              "]"
            ]
          }
        ),
        "?"
      ] });
      question2 = /* @__PURE__ */ (0, import_jsx_runtime71.jsxs)(Box_default, { flexDirection: "column", children: [
        allowQuestion,
        warnings
      ] });
      bodyContent2 = /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(import_jsx_runtime71.Fragment, { children: /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(
        Box_default,
        {
          borderStyle: "round",
          borderColor: theme.border.default,
          paddingX: 1,
          paddingY: 0,
          marginBottom: 0,
          children: /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(
            MaxSizedBox,
            {
              maxHeight: bodyHeight !== void 0 ? Math.max(bodyHeight - 2, 2) : void 0,
              maxWidth: Math.max(terminalWidth, 1) - 4,
              children: /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(Box_default, { flexDirection: "column", children: commandsToDisplay.map((cmd, idx) => /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(
                Box_default,
                {
                  flexDirection: "column",
                  paddingBottom: idx < commandsToDisplay.length - 1 ? 1 : 0,
                  children: colorizeCode({
                    code: cmd.trim(),
                    language: "bash",
                    maxWidth: Math.max(terminalWidth, 1) - 6,
                    settings,
                    theme: activeTheme,
                    hideLineNumbers: true,
                    availableHeight: bodyHeight !== void 0 ? Math.max(bodyHeight - 2, 2) : void 0
                  })
                },
                idx
              )) })
            }
          )
        }
      ) });
    } else if (confirmationDetails.type === "info") {
      question2 = `Do you want to proceed?`;
      const infoProps = confirmationDetails;
      const displayUrls = infoProps.urls && !(infoProps.urls.length === 1 && infoProps.urls[0] === infoProps.prompt);
      bodyContent2 = /* @__PURE__ */ (0, import_jsx_runtime71.jsxs)(Box_default, { flexDirection: "column", children: [
        /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(Text, { color: theme.text.link, children: /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(
          RenderInline,
          {
            text: infoProps.prompt,
            defaultColor: theme.text.link
          }
        ) }),
        displayUrls && infoProps.urls && infoProps.urls.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime71.jsxs)(Box_default, { flexDirection: "column", marginTop: 1, children: [
          /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(Text, { color: theme.text.primary, children: "URLs to fetch:" }),
          infoProps.urls.map((urlString) => /* @__PURE__ */ (0, import_jsx_runtime71.jsxs)(Text, { children: [
            " ",
            "- ",
            /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(RenderInline, { text: toUnicodeUrl(urlString) })
          ] }, urlString))
        ] })
      ] });
    } else if (confirmationDetails.type === "mcp") {
      const mcpProps = confirmationDetails;
      question2 = `Allow execution of MCP tool "${sanitizeForDisplay(mcpProps.toolName)}" from server "${sanitizeForDisplay(mcpProps.serverName)}"?`;
      bodyContent2 = /* @__PURE__ */ (0, import_jsx_runtime71.jsxs)(Box_default, { flexDirection: "column", children: [
        /* @__PURE__ */ (0, import_jsx_runtime71.jsxs)(import_jsx_runtime71.Fragment, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime71.jsxs)(Text, { color: theme.text.link, children: [
            "MCP Server: ",
            sanitizeForDisplay(mcpProps.serverName)
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime71.jsxs)(Text, { color: theme.text.link, children: [
            "Tool: ",
            sanitizeForDisplay(mcpProps.toolName)
          ] })
        ] }),
        hasMcpToolDetails && /* @__PURE__ */ (0, import_jsx_runtime71.jsxs)(Box_default, { flexDirection: "column", marginTop: 1, children: [
          /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(Text, { color: theme.text.primary, children: "MCP Tool Details:" }),
          isMcpToolDetailsExpanded ? /* @__PURE__ */ (0, import_jsx_runtime71.jsxs)(import_jsx_runtime71.Fragment, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime71.jsxs)(Text, { color: theme.text.secondary, children: [
              "(press ",
              expandDetailsHintKey,
              " to collapse MCP tool details)"
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(
              Box_default,
              {
                borderStyle: "round",
                borderColor: theme.border.default,
                paddingX: 1,
                paddingY: 0,
                marginBottom: 0,
                children: colorizeCode({
                  code: mcpToolDetailsText || "",
                  language: "json",
                  maxWidth: Math.max(terminalWidth, 1) - 4,
                  settings,
                  theme: activeTheme,
                  hideLineNumbers: true,
                  availableHeight: bodyHeight !== void 0 ? Math.max(bodyHeight - 2, 2) : void 0
                })
              }
            )
          ] }) : /* @__PURE__ */ (0, import_jsx_runtime71.jsxs)(Text, { color: theme.text.secondary, children: [
            "(press ",
            expandDetailsHintKey,
            " to expand MCP tool details)"
          ] })
        ] })
      ] });
    }
    return { question: question2, bodyContent: bodyContent2, options: options2, securityWarnings: securityWarnings2, initialIndex: initialIndex2 };
  }, [
    confirmationDetails,
    getOptions,
    availableBodyContentHeight,
    terminalWidth,
    handleConfirm,
    deceptiveUrlWarningText,
    isMcpToolDetailsExpanded,
    hasMcpToolDetails,
    mcpToolDetailsText,
    expandDetailsHintKey,
    getPreferredEditor,
    isTrustedFolder,
    allowPermanentApproval,
    settings,
    activeTheme,
    config,
    toolName
  ]);
  const bodyOverflowDirection = confirmationDetails.type === "mcp" && isMcpToolDetailsExpanded ? "bottom" : "top";
  const renderRadioItem = (0, import_react50.useCallback)(
    (item, { titleColor }) => {
      if (item.value === ToolConfirmationOutcome.ProceedAlwaysAndSave) {
        return /* @__PURE__ */ (0, import_jsx_runtime71.jsxs)(Text, { color: titleColor, wrap: "truncate", children: [
          item.label,
          " ",
          /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(Text, { color: theme.text.secondary, children: "~/.gemini/policies/auto-saved.toml" })
        ] });
      }
      return /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(Text, { color: titleColor, wrap: "truncate", children: item.label });
    },
    []
  );
  if (confirmationDetails.type === "edit") {
    if (confirmationDetails.isModifying) {
      return /* @__PURE__ */ (0, import_jsx_runtime71.jsxs)(
        Box_default,
        {
          width: terminalWidth,
          borderStyle: "round",
          borderColor: theme.border.default,
          justifyContent: "space-around",
          paddingTop: 1,
          paddingBottom: 1,
          overflow: "hidden",
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(Text, { color: theme.text.primary, children: "Modify in progress: " }),
            /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(Text, { color: theme.status.success, children: "Save and close external editor to continue" })
          ]
        }
      );
    }
  }
  return /* @__PURE__ */ (0, import_jsx_runtime71.jsxs)(Box_default, { flexDirection: "column", paddingTop: 0, paddingBottom: 0, children: [
    !!confirmationDetails.systemMessage && /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(Box_default, { marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(Text, { color: theme.status.warning, children: confirmationDetails.systemMessage }) }),
    handlesOwnUI ? bodyContent : /* @__PURE__ */ (0, import_jsx_runtime71.jsxs)(import_jsx_runtime71.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(
        Box_default,
        {
          flexShrink: 1,
          overflow: "hidden",
          marginBottom: !question && !securityWarnings ? 1 : 0,
          children: /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(
            MaxSizedBox,
            {
              maxHeight: availableBodyContentHeight(),
              maxWidth: terminalWidth,
              overflowDirection: bodyOverflowDirection,
              children: bodyContent
            }
          )
        }
      ),
      securityWarnings && /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(
        Box_default,
        {
          flexShrink: 0,
          marginBottom: 1,
          ref: onSecurityWarningsRefChange,
          children: securityWarnings
        }
      ),
      !!question && /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(Box_default, { marginBottom: 1, flexShrink: 0, children: typeof question === "string" ? /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(Text, { color: theme.text.primary, children: question }) : question }),
      /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(Box_default, { flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime71.jsx)(
        RadioButtonSelect,
        {
          items: options,
          onSelect: handleSelect,
          isFocused,
          initialIndex,
          renderItem: renderRadioItem
        }
      ) })
    ] })
  ] });
};

// packages/cli/src/ui/components/ToolConfirmationQueue.tsx
var import_jsx_runtime72 = __toESM(require_jsx_runtime(), 1);
function getConfirmationHeader(details) {
  const headers = {
    ask_user: "Answer Questions",
    exit_plan_mode: "Ready to start implementation?"
  };
  if (!details?.type) {
    return "Action Required";
  }
  return headers[details.type] ?? "Action Required";
}
function getConfirmationLabel(toolName, details) {
  if (details?.type === "ask_user") return "Questions";
  if (details?.type === "exit_plan_mode") return "Implementation";
  if (isShellTool(toolName)) return "Shell";
  return toolName;
}
var ToolConfirmationQueue = ({
  confirmingTool
}) => {
  const config = useConfig();
  const { getPreferredEditor } = useUIActions();
  const {
    mainAreaWidth,
    terminalHeight,
    constrainHeight,
    availableTerminalHeight: uiAvailableHeight
  } = useUIState();
  const { tool, index, total } = confirmingTool;
  if (!tool.confirmationDetails) return null;
  const maxHeight = uiAvailableHeight !== void 0 ? Math.max(uiAvailableHeight, 4) : Math.floor(terminalHeight * 0.5);
  const isShell = isShellTool(tool.name);
  const isEdit = tool.confirmationDetails?.type === "edit";
  if (isShell || isEdit) {
    const borderColor2 = theme.border.default;
    const availableContentHeight2 = constrainHeight ? Math.max(maxHeight - 3, 4) : void 0;
    const toolLabel = getConfirmationLabel(tool.name, tool.confirmationDetails);
    return /* @__PURE__ */ (0, import_jsx_runtime72.jsxs)(
      Box_default,
      {
        flexDirection: "column",
        width: mainAreaWidth,
        flexShrink: 0,
        borderStyle: "round",
        borderColor: borderColor2,
        paddingX: 1,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime72.jsxs)(Box_default, { justifyContent: "space-between", marginBottom: 0, children: [
            /* @__PURE__ */ (0, import_jsx_runtime72.jsxs)(Box_default, { flexDirection: "row", flexShrink: 1, overflow: "hidden", children: [
              /* @__PURE__ */ (0, import_jsx_runtime72.jsxs)(Text, { color: theme.status.warning, bold: true, children: [
                "? ",
                toolLabel,
                !!tool.description && "  "
              ] }),
              !!tool.description && /* @__PURE__ */ (0, import_jsx_runtime72.jsx)(Box_default, { flexShrink: 1, overflow: "hidden", children: /* @__PURE__ */ (0, import_jsx_runtime72.jsx)(Text, { color: theme.text.primary, wrap: "truncate-end", children: tool.description }) })
            ] }),
            total > 1 && /* @__PURE__ */ (0, import_jsx_runtime72.jsxs)(Text, { color: theme.text.secondary, children: [
              index,
              " of ",
              total
            ] })
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime72.jsx)(Box_default, { flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime72.jsx)(
            ToolConfirmationMessage,
            {
              callId: tool.callId,
              confirmationDetails: tool.confirmationDetails,
              config,
              getPreferredEditor,
              terminalWidth: mainAreaWidth - 4,
              availableTerminalHeight: availableContentHeight2,
              toolName: tool.name,
              isFocused: true
            }
          ) })
        ]
      }
    );
  }
  const isRoutine = tool.confirmationDetails?.type === "ask_user" || tool.confirmationDetails?.type === "exit_plan_mode";
  const borderColor = isRoutine ? theme.status.success : theme.status.warning;
  const hideToolIdentity = isRoutine;
  const availableContentHeight = constrainHeight ? Math.max(maxHeight - (hideToolIdentity ? 4 : 6), 4) : void 0;
  return /* @__PURE__ */ (0, import_jsx_runtime72.jsxs)(Box_default, { flexDirection: "column", width: mainAreaWidth, flexShrink: 0, children: [
    /* @__PURE__ */ (0, import_jsx_runtime72.jsx)(
      StickyHeader,
      {
        width: mainAreaWidth,
        isFirst: true,
        borderColor,
        borderDimColor: false,
        children: /* @__PURE__ */ (0, import_jsx_runtime72.jsxs)(Box_default, { flexDirection: "column", width: mainAreaWidth - 4, children: [
          /* @__PURE__ */ (0, import_jsx_runtime72.jsxs)(
            Box_default,
            {
              marginBottom: hideToolIdentity ? 0 : 1,
              justifyContent: "space-between",
              children: [
                /* @__PURE__ */ (0, import_jsx_runtime72.jsx)(Text, { color: borderColor, bold: true, children: getConfirmationHeader(tool.confirmationDetails) }),
                total > 1 && /* @__PURE__ */ (0, import_jsx_runtime72.jsxs)(Text, { color: theme.text.secondary, children: [
                  index,
                  " of ",
                  total
                ] })
              ]
            }
          ),
          !hideToolIdentity && /* @__PURE__ */ (0, import_jsx_runtime72.jsxs)(Box_default, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime72.jsx)(ToolStatusIndicator, { status: tool.status, name: tool.name }),
            /* @__PURE__ */ (0, import_jsx_runtime72.jsx)(
              ToolInfo,
              {
                name: tool.name,
                status: tool.status,
                description: tool.description,
                emphasis: "high"
              }
            )
          ] })
        ] })
      }
    ),
    /* @__PURE__ */ (0, import_jsx_runtime72.jsx)(
      Box_default,
      {
        width: mainAreaWidth,
        borderStyle: "round",
        borderColor,
        borderTop: false,
        borderBottom: false,
        borderLeft: true,
        borderRight: true,
        paddingX: 1,
        flexDirection: "column",
        children: /* @__PURE__ */ (0, import_jsx_runtime72.jsx)(
          ToolConfirmationMessage,
          {
            callId: tool.callId,
            confirmationDetails: tool.confirmationDetails,
            config,
            getPreferredEditor,
            terminalWidth: mainAreaWidth - 4,
            availableTerminalHeight: availableContentHeight,
            toolName: tool.name,
            isFocused: true
          }
        )
      }
    ),
    /* @__PURE__ */ (0, import_jsx_runtime72.jsx)(
      Box_default,
      {
        height: 1,
        width: mainAreaWidth,
        borderLeft: true,
        borderRight: true,
        borderTop: false,
        borderBottom: true,
        borderColor,
        borderStyle: "round"
      }
    )
  ] });
};

// packages/cli/src/ui/components/MainContent.tsx
var import_jsx_runtime73 = __toESM(require_jsx_runtime(), 1);
var MemoizedHistoryItemDisplay = (0, import_react51.memo)(HistoryItemDisplay);
var MemoizedAppHeader = (0, import_react51.memo)(AppHeader);
var MainContent = () => {
  const { version } = useAppContext();
  const uiState = useUIState();
  const isAlternateBufferOrTerminalBuffer = useAlternateBuffer();
  const config = useConfig();
  const useTerminalBuffer = config.getUseTerminalBuffer();
  const isAlternateBuffer = config.getUseAlternateBuffer();
  const confirmingTool = useConfirmingTool();
  const showConfirmationQueue = confirmingTool !== null;
  const confirmingToolCallId = confirmingTool?.tool.callId;
  const scrollableListRef = (0, import_react51.useRef)(null);
  (0, import_react51.useEffect)(() => {
    if (showConfirmationQueue) {
      scrollableListRef.current?.scrollToEnd();
    }
  }, [showConfirmationQueue, confirmingToolCallId]);
  (0, import_react51.useEffect)(() => {
    const handleScroll = () => {
      scrollableListRef.current?.scrollToEnd();
    };
    appEvents.on("scroll-to-bottom" /* ScrollToBottom */, handleScroll);
    return () => {
      appEvents.off("scroll-to-bottom" /* ScrollToBottom */, handleScroll);
    };
  }, []);
  const {
    pendingHistoryItems,
    mainAreaWidth,
    staticAreaMaxItemHeight,
    availableTerminalHeight,
    cleanUiDetailsVisible,
    mouseMode
  } = uiState;
  const showHeaderDetails = cleanUiDetailsVisible;
  const lastUserPromptIndex = (0, import_react51.useMemo)(() => {
    for (let i = uiState.history.length - 1; i >= 0; i--) {
      const type = uiState.history[i].type;
      if (type === "user" || type === "user_shell") {
        return i;
      }
    }
    return -1;
  }, [uiState.history]);
  const settings = useSettings();
  const topicUpdateNarrationEnabled = settings.merged.experimental?.topicUpdateNarration === true;
  const suppressNarrationFlags = (0, import_react51.useMemo)(() => {
    const combinedHistory = [...uiState.history, ...pendingHistoryItems];
    const flags = new Array(combinedHistory.length).fill(false);
    if (topicUpdateNarrationEnabled) {
      let toolGroupInTurn = false;
      for (let i = combinedHistory.length - 1; i >= 0; i--) {
        const item = combinedHistory[i];
        if (item.type === "user" || item.type === "user_shell") {
          toolGroupInTurn = false;
        } else if (item.type === "tool_group") {
          toolGroupInTurn = item.tools.some((t) => isTopicTool(t.name));
        } else if ((item.type === "thinking" || item.type === "gemini" || item.type === "gemini_content") && toolGroupInTurn) {
          flags[i] = true;
        }
      }
    }
    return flags;
  }, [uiState.history, pendingHistoryItems, topicUpdateNarrationEnabled]);
  const augmentedHistory = (0, import_react51.useMemo)(
    () => uiState.history.map((item, i) => {
      const prevType = i > 0 ? uiState.history[i - 1]?.type : void 0;
      const isFirstThinking = item.type === "thinking" && prevType !== "thinking";
      const isFirstAfterThinking = item.type !== "thinking" && prevType === "thinking";
      const isToolGroupBoundary = item.type !== "tool_group" && prevType === "tool_group" || item.type === "tool_group" && prevType !== "tool_group";
      return {
        item,
        isExpandable: i > lastUserPromptIndex,
        isFirstThinking,
        isFirstAfterThinking,
        isToolGroupBoundary,
        suppressNarration: suppressNarrationFlags[i] ?? false
      };
    }),
    [uiState.history, lastUserPromptIndex, suppressNarrationFlags]
  );
  const historyItems = (0, import_react51.useMemo)(
    () => augmentedHistory.map(
      ({
        item,
        isExpandable,
        isFirstThinking,
        isFirstAfterThinking,
        isToolGroupBoundary,
        suppressNarration
      }) => /* @__PURE__ */ (0, import_jsx_runtime73.jsx)(
        MemoizedHistoryItemDisplay,
        {
          terminalWidth: mainAreaWidth,
          availableTerminalHeight: uiState.constrainHeight || !isExpandable ? staticAreaMaxItemHeight : void 0,
          availableTerminalHeightGemini: MAX_GEMINI_MESSAGE_LINES,
          item,
          isPending: false,
          commands: uiState.slashCommands,
          isExpandable,
          isFirstThinking,
          isFirstAfterThinking,
          isToolGroupBoundary,
          suppressNarration
        },
        item.id
      )
    ),
    [
      augmentedHistory,
      mainAreaWidth,
      staticAreaMaxItemHeight,
      uiState.slashCommands,
      uiState.constrainHeight
    ]
  );
  const staticHistoryItems = (0, import_react51.useMemo)(
    () => historyItems.slice(0, lastUserPromptIndex + 1),
    [historyItems, lastUserPromptIndex]
  );
  const lastResponseHistoryItems = (0, import_react51.useMemo)(
    () => historyItems.slice(lastUserPromptIndex + 1),
    [historyItems, lastUserPromptIndex]
  );
  const pendingItems = (0, import_react51.useMemo)(
    () => /* @__PURE__ */ (0, import_jsx_runtime73.jsxs)(Box_default, { flexDirection: "column", children: [
      pendingHistoryItems.map((item, i) => {
        const prevType = i === 0 ? uiState.history.at(-1)?.type : pendingHistoryItems[i - 1]?.type;
        const isFirstThinking = item.type === "thinking" && prevType !== "thinking";
        const isFirstAfterThinking = item.type !== "thinking" && prevType === "thinking";
        const isToolGroupBoundary = item.type !== "tool_group" && prevType === "tool_group" || item.type === "tool_group" && prevType !== "tool_group";
        const suppressNarration = suppressNarrationFlags[uiState.history.length + i] ?? false;
        return /* @__PURE__ */ (0, import_jsx_runtime73.jsx)(
          HistoryItemDisplay,
          {
            availableTerminalHeight: uiState.constrainHeight ? availableTerminalHeight : void 0,
            terminalWidth: mainAreaWidth,
            item: { ...item, id: -(i + 1) },
            isPending: true,
            isExpandable: true,
            isFirstThinking,
            isFirstAfterThinking,
            isToolGroupBoundary,
            suppressNarration
          },
          `pending-${i}`
        );
      }),
      showConfirmationQueue && confirmingTool && /* @__PURE__ */ (0, import_jsx_runtime73.jsx)(
        ToolConfirmationQueue,
        {
          confirmingTool
        },
        "confirmation-queue"
      )
    ] }, "pending-items-group"),
    [
      pendingHistoryItems,
      uiState.constrainHeight,
      availableTerminalHeight,
      mainAreaWidth,
      showConfirmationQueue,
      confirmingTool,
      uiState.history,
      suppressNarrationFlags
    ]
  );
  const virtualizedData = (0, import_react51.useMemo)(
    () => [
      { type: "header" },
      ...augmentedHistory.map((data, index) => ({
        type: "history",
        item: data.item,
        element: historyItems[index]
      })),
      { type: "pending" }
    ],
    [augmentedHistory, historyItems]
  );
  const renderItem = (0, import_react51.useCallback)(
    ({ item }) => {
      if (item.type === "header") {
        return /* @__PURE__ */ (0, import_jsx_runtime73.jsx)(
          MemoizedAppHeader,
          {
            version,
            showDetails: showHeaderDetails
          },
          "app-header"
        );
      } else if (item.type === "history") {
        return item.element;
      } else {
        return pendingItems;
      }
    },
    [showHeaderDetails, version, pendingItems]
  );
  const estimatedItemHeight = (0, import_react51.useCallback)(() => 100, []);
  const keyExtractor = (0, import_react51.useCallback)(
    (item, _index) => {
      if (item.type === "header") return "header";
      if (item.type === "history") return item.item.id.toString();
      return "pending";
    },
    []
  );
  const isStaticItem = (0, import_react51.useCallback)(
    (item) => item.type === "header",
    []
  );
  const scrollableList = (0, import_react51.useMemo)(() => {
    if (isAlternateBufferOrTerminalBuffer) {
      return /* @__PURE__ */ (0, import_jsx_runtime73.jsx)(
        ScrollableListWithForwardRef,
        {
          ref: scrollableListRef,
          hasFocus: !uiState.isEditorDialogOpen && !uiState.embeddedShellFocused,
          width: uiState.terminalWidth,
          data: virtualizedData,
          renderItem,
          estimatedItemHeight,
          keyExtractor,
          initialScrollIndex: SCROLL_TO_ITEM_END,
          initialScrollOffsetInIndex: SCROLL_TO_ITEM_END,
          renderStatic: useTerminalBuffer,
          isStaticItem: useTerminalBuffer ? isStaticItem : void 0,
          overflowToBackbuffer: useTerminalBuffer && !isAlternateBuffer,
          scrollbar: mouseMode
        }
      );
    }
    return null;
  }, [
    isAlternateBufferOrTerminalBuffer,
    uiState.isEditorDialogOpen,
    uiState.embeddedShellFocused,
    uiState.terminalWidth,
    virtualizedData,
    renderItem,
    estimatedItemHeight,
    keyExtractor,
    useTerminalBuffer,
    isStaticItem,
    mouseMode,
    isAlternateBuffer
  ]);
  if (!uiState.isConfigInitialized) {
    return null;
  }
  if (isAlternateBufferOrTerminalBuffer) {
    return scrollableList;
  }
  return /* @__PURE__ */ (0, import_jsx_runtime73.jsxs)(import_jsx_runtime73.Fragment, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime73.jsx)(
      Static,
      {
        items: [
          /* @__PURE__ */ (0, import_jsx_runtime73.jsx)(AppHeader, { version }, "app-header"),
          ...staticHistoryItems,
          ...lastResponseHistoryItems
        ],
        children: (item) => item
      },
      uiState.historyRemountKey
    ),
    pendingItems
  ] });
};

// packages/cli/src/ui/components/LoopDetectionConfirmation.tsx
var import_jsx_runtime74 = __toESM(require_jsx_runtime(), 1);
function LoopDetectionConfirmation({
  onComplete
}) {
  useKeypress(
    (key) => {
      if (key.name === "escape") {
        onComplete({
          userSelection: "keep"
        });
        return true;
      }
      return false;
    },
    { isActive: true }
  );
  const OPTIONS = [
    {
      label: "Keep loop detection enabled (esc)",
      value: {
        userSelection: "keep"
      },
      key: "Keep loop detection enabled (esc)"
    },
    {
      label: "Disable loop detection for this session",
      value: {
        userSelection: "disable"
      },
      key: "Disable loop detection for this session"
    }
  ];
  return /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(Box_default, { width: "100%", flexDirection: "row", children: /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(
    Box_default,
    {
      flexDirection: "column",
      borderStyle: "round",
      borderColor: theme.status.warning,
      flexGrow: 1,
      marginLeft: 1,
      children: /* @__PURE__ */ (0, import_jsx_runtime74.jsxs)(Box_default, { paddingX: 1, paddingY: 0, flexDirection: "column", children: [
        /* @__PURE__ */ (0, import_jsx_runtime74.jsxs)(Box_default, { minHeight: 1, children: [
          /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(Box_default, { minWidth: 3, children: /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(Text, { color: theme.status.warning, "aria-label": "Loop detected:", children: "?" }) }),
          /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime74.jsxs)(Text, { wrap: "truncate-end", children: [
            /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(Text, { color: theme.text.primary, bold: true, children: "A potential loop was detected" }),
            " "
          ] }) })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime74.jsxs)(Box_default, { flexDirection: "column", children: [
          /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(Text, { color: theme.text.secondary, children: "This can happen due to repetitive tool calls or other model behavior. Do you want to keep loop detection enabled or disable it for this session?" }),
          /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime74.jsx)(RadioButtonSelect, { items: OPTIONS, onSelect: onComplete }) })
        ] }) })
      ] })
    }
  ) });
}

// packages/cli/src/ui/components/ConsentPrompt.tsx
var import_react52 = __toESM(require_react(), 1);
var import_jsx_runtime75 = __toESM(require_jsx_runtime(), 1);
var ConsentPrompt = (props) => {
  const { prompt, onConfirm, terminalWidth } = props;
  return /* @__PURE__ */ (0, import_jsx_runtime75.jsxs)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: theme.border.default,
      flexDirection: "column",
      paddingTop: 1,
      paddingX: 2,
      children: [
        typeof prompt === "string" ? /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(
          MarkdownDisplay,
          {
            isPending: true,
            text: prompt,
            terminalWidth
          }
        ) : prompt,
        /* @__PURE__ */ (0, import_jsx_runtime75.jsxs)(Box_default, { marginTop: 1, flexDirection: "column", children: [
          /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(
            RadioButtonSelect,
            {
              items: [
                { label: "Yes", value: true, key: "Yes" },
                { label: "No", value: false, key: "No" }
              ],
              onSelect: onConfirm
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime75.jsx)(
            DialogFooter,
            {
              primaryAction: "Enter to select",
              navigationActions: "\u2191/\u2193 to navigate"
            }
          )
        ] })
      ]
    }
  );
};

// packages/cli/src/ui/components/ThemeDialog.tsx
var import_react53 = __toESM(require_react(), 1);

// packages/cli/src/utils/settingsUtils.ts
function flattenSchema(schema, prefix = "") {
  let result = {};
  for (const key in schema) {
    const newKey = prefix ? `${prefix}.${key}` : key;
    const definition = schema[key];
    result[newKey] = { ...definition, key: newKey };
    if (definition.properties) {
      result = { ...result, ...flattenSchema(definition.properties, newKey) };
    }
  }
  return result;
}
var _FLATTENED_SCHEMA;
function getFlattenedSchema() {
  return _FLATTENED_SCHEMA ?? (_FLATTENED_SCHEMA = flattenSchema(getSettingsSchema()));
}
function getSettingDefinition(key) {
  return getFlattenedSchema()[key];
}
function getDefaultValue(key) {
  return getFlattenedSchema()[key]?.default;
}
function getDialogRestartRequiredSettings() {
  return Object.values(getFlattenedSchema()).filter(
    (definition) => definition.requiresRestart && definition.showInDialog !== false
  ).map((definition) => definition.key);
}
function isRecord(value) {
  return typeof value === "object" && value !== null;
}
function isSettingsValue(value) {
  if (value === void 0) return true;
  if (value === null) return false;
  const type = typeof value;
  return type === "string" || type === "number" || type === "boolean" || type === "object";
}
function getNestedValue(obj, path16) {
  let current = obj;
  for (const key of path16) {
    if (!isRecord(current) || !(key in current)) {
      return void 0;
    }
    current = current[key];
  }
  return current;
}
function getEffectiveValue(key, settings) {
  const definition = getSettingDefinition(key);
  if (!definition) {
    return void 0;
  }
  const path16 = key.split(".");
  const value = getNestedValue(settings, path16);
  if (value !== void 0 && isSettingsValue(value)) {
    return value;
  }
  return definition.default;
}
function getDialogSettingKeys() {
  return Object.values(getFlattenedSchema()).filter((definition) => definition.showInDialog !== false).map((definition) => definition.key);
}
function isInSettingsScope(key, scopeSettings) {
  const path16 = key.split(".");
  const value = getNestedValue(scopeSettings, path16);
  return value !== void 0;
}
function getDisplayValue(key, scopeSettings, _mergedSettings) {
  const definition = getSettingDefinition(key);
  const existsInScope = isInSettingsScope(key, scopeSettings);
  let value;
  if (existsInScope) {
    value = getEffectiveValue(key, scopeSettings);
  } else {
    value = getDefaultValue(key);
  }
  let valueString = String(value);
  if (definition?.type === "object" && value !== null && typeof value === "object") {
    valueString = JSON.stringify(value);
  } else if (definition?.type === "enum" && definition.options) {
    const option = definition.options?.find((option2) => option2.value === value);
    valueString = option?.label ?? `${value}`;
  }
  if (definition?.unit === "%" && typeof value === "number") {
    valueString = `${value} (${Math.round(value * 100)}%)`;
  } else if (definition?.unit) {
    valueString = `${valueString}${definition.unit}`;
  }
  if (existsInScope) {
    return `${valueString}*`;
  }
  return valueString;
}
function tryParseJsonStringArray(input) {
  try {
    const parsed = JSON.parse(input);
    if (Array.isArray(parsed) && parsed.every((item) => typeof item === "string")) {
      return parsed;
    }
    return null;
  } catch {
    return null;
  }
}
function tryParseJsonObject(input) {
  try {
    const parsed = JSON.parse(input);
    if (isRecord(parsed) && !Array.isArray(parsed)) {
      return parsed;
    }
    return null;
  } catch {
    return null;
  }
}
function parseStringArrayValue(input) {
  const trimmed = input.trim();
  if (trimmed === "") return [];
  return tryParseJsonStringArray(trimmed) ?? input.split(",").map((p) => p.trim()).filter((p) => p.length > 0);
}
function parseObjectValue(input) {
  const trimmed = input.trim();
  if (trimmed === "") {
    return null;
  }
  return tryParseJsonObject(trimmed);
}
function parseEditedValue(type, newValue) {
  if (type === "number") {
    if (newValue.trim() === "") {
      return null;
    }
    const numParsed = Number(newValue.trim());
    if (Number.isNaN(numParsed)) {
      return null;
    }
    return numParsed;
  }
  if (type === "array") {
    return parseStringArrayValue(newValue);
  }
  if (type === "object") {
    return parseObjectValue(newValue);
  }
  return newValue;
}
function getEditValue(type, rawValue) {
  if (rawValue === void 0) {
    return void 0;
  }
  if (type === "array" && Array.isArray(rawValue)) {
    return rawValue.join(", ");
  }
  if (type === "object" && rawValue !== null && typeof rawValue === "object") {
    return JSON.stringify(rawValue);
  }
  return void 0;
}

// packages/cli/src/utils/dialogScopeUtils.ts
var SCOPE_LABELS = {
  ["User" /* User */]: "User Settings",
  ["Workspace" /* Workspace */]: "Workspace Settings",
  ["System" /* System */]: "System Settings"
};
function getScopeItems() {
  return [
    { label: SCOPE_LABELS["User" /* User */], value: "User" /* User */ },
    {
      label: SCOPE_LABELS["Workspace" /* Workspace */],
      value: "Workspace" /* Workspace */
    },
    { label: SCOPE_LABELS["System" /* System */], value: "System" /* System */ }
  ];
}
function getScopeMessageForSetting(settingKey, selectedScope, settings) {
  const otherScopes = Object.values(SettingScope).filter(isLoadableSettingScope).filter((scope) => scope !== selectedScope);
  const modifiedInOtherScopes = otherScopes.filter((scope) => {
    const scopeSettings = settings.forScope(scope).settings;
    return isInSettingsScope(settingKey, scopeSettings);
  });
  if (modifiedInOtherScopes.length === 0) {
    return "";
  }
  const modifiedScopesStr = modifiedInOtherScopes.join(", ");
  const currentScopeSettings = settings.forScope(selectedScope).settings;
  const existsInCurrentScope = isInSettingsScope(
    settingKey,
    currentScopeSettings
  );
  return existsInCurrentScope ? `(Also modified in ${modifiedScopesStr})` : `(Modified in ${modifiedScopesStr})`;
}

// packages/cli/src/ui/components/shared/ScopeSelector.tsx
var import_jsx_runtime76 = __toESM(require_jsx_runtime(), 1);
function ScopeSelector({
  onSelect,
  onHighlight,
  isFocused,
  initialScope
}) {
  const scopeItems = getScopeItems().map((item) => ({
    ...item,
    key: item.value
  }));
  const initialIndex = scopeItems.findIndex(
    (item) => item.value === initialScope
  );
  const safeInitialIndex = initialIndex >= 0 ? initialIndex : 0;
  return /* @__PURE__ */ (0, import_jsx_runtime76.jsxs)(Box_default, { flexDirection: "column", children: [
    /* @__PURE__ */ (0, import_jsx_runtime76.jsxs)(Text, { bold: isFocused, wrap: "truncate", children: [
      isFocused ? "> " : "  ",
      "Apply To"
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime76.jsx)(
      RadioButtonSelect,
      {
        items: scopeItems,
        initialIndex: safeInitialIndex,
        onSelect,
        onHighlight,
        isFocused,
        showNumbers: isFocused
      }
    )
  ] });
}

// packages/cli/src/ui/components/ColorsDisplay.tsx
var import_jsx_runtime77 = __toESM(require_jsx_runtime(), 1);
var VALUE_COLUMN_WIDTH = 10;
var COLOR_DESCRIPTIONS = {
  "text.primary": "Primary text color (uses terminal default if blank)",
  "text.secondary": "Secondary/dimmed text color",
  "text.link": "Hyperlink and highlighting color",
  "text.accent": "Accent color for emphasis",
  "text.response": "Color for model response text (uses terminal default if blank)",
  "background.primary": "Main terminal background color",
  "background.message": "Subtle background for message blocks",
  "background.input": "Background for the input prompt",
  "background.focus": "Background highlight for selected/focused items",
  "background.diff.added": "Background for added lines in diffs",
  "background.diff.removed": "Background for removed lines in diffs",
  "border.default": "Standard border color",
  "ui.comment": "Color for code comments and metadata",
  "ui.symbol": "Color for technical symbols and UI icons",
  "ui.active": "Border color for active or running elements",
  "ui.dark": "Deeply dimmed color for subtle UI elements",
  "ui.focus": "Color for focused elements (e.g. selected menu items, focused borders)",
  "status.error": "Color for error messages and critical status",
  "status.success": "Color for success messages and positive status",
  "status.warning": "Color for warnings and cautionary status"
};
function getContrastingTextColor(hex) {
  if (!hex || !hex.startsWith("#") || hex.length < 7) {
    return theme.text.primary;
  }
  const r2 = parseInt(hex.slice(1, 3), 16);
  const g = parseInt(hex.slice(3, 5), 16);
  const b = parseInt(hex.slice(5, 7), 16);
  const yiq = (r2 * 299 + g * 587 + b * 114) / 1e3;
  return yiq >= 128 ? "#000000" : "#FFFFFF";
}
var ColorsDisplay = ({
  activeTheme
}) => {
  const semanticColors = activeTheme.semanticColors;
  const backgroundRows = [];
  const standardRows = [];
  let gradientRow = null;
  if (semanticColors.ui.gradient && semanticColors.ui.gradient.length > 0) {
    gradientRow = {
      type: "gradient",
      name: "ui.gradient",
      value: semanticColors.ui.gradient
    };
  }
  const flattenColors = (obj, path16 = "") => {
    for (const [key, value] of Object.entries(obj)) {
      if (value === void 0 || value === null) continue;
      const newPath = path16 ? `${path16}.${key}` : key;
      if (key === "gradient" && Array.isArray(value)) {
        continue;
      }
      if (typeof value === "object" && !Array.isArray(value)) {
        flattenColors(value, newPath);
      } else if (typeof value === "string") {
        if (newPath.startsWith("background.")) {
          backgroundRows.push({
            type: "background",
            name: newPath,
            value
          });
        } else {
          standardRows.push({
            type: "standard",
            name: newPath,
            value
          });
        }
      }
    }
  };
  flattenColors(semanticColors);
  const allRows = [
    ...backgroundRows,
    ...standardRows,
    ...gradientRow ? [gradientRow] : []
  ];
  return /* @__PURE__ */ (0, import_jsx_runtime77.jsxs)(
    Box_default,
    {
      flexDirection: "column",
      paddingX: 1,
      paddingY: 0,
      borderStyle: "round",
      borderColor: theme.border.default,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime77.jsxs)(Box_default, { marginBottom: 1, flexDirection: "column", children: [
          /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(Text, { bold: true, color: theme.text.accent, children: "DEVELOPER TOOLS (Not visible to users)" }),
          /* @__PURE__ */ (0, import_jsx_runtime77.jsxs)(Box_default, { marginTop: 1, flexDirection: "column", children: [
            /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(Text, { color: theme.text.primary, children: /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(Text, { bold: true, children: "How do colors get applied?" }) }),
            /* @__PURE__ */ (0, import_jsx_runtime77.jsxs)(Box_default, { marginLeft: 2, flexDirection: "column", children: [
              /* @__PURE__ */ (0, import_jsx_runtime77.jsxs)(Text, { color: theme.text.primary, children: [
                "\u2022 ",
                /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(Text, { bold: true, children: "Hex:" }),
                " Rendered exactly by modern terminals. Not overridden by app themes."
              ] }),
              /* @__PURE__ */ (0, import_jsx_runtime77.jsxs)(Text, { color: theme.text.primary, children: [
                "\u2022 ",
                /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(Text, { bold: true, children: "Blank:" }),
                " Uses your terminal's default foreground/background."
              ] }),
              /* @__PURE__ */ (0, import_jsx_runtime77.jsxs)(Text, { color: theme.text.primary, children: [
                "\u2022 ",
                /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(Text, { bold: true, children: "Compatibility:" }),
                " On older terminals, hex is approximated to the nearest ANSI color."
              ] }),
              /* @__PURE__ */ (0, import_jsx_runtime77.jsxs)(Text, { color: theme.text.primary, children: [
                "\u2022 ",
                /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(Text, { bold: true, children: "ANSI Names:" }),
                " 'red', 'green', etc. are mapped to your terminal app's palette."
              ] })
            ] })
          ] })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime77.jsxs)(Box_default, { flexDirection: "row", marginBottom: 0, paddingX: 1, children: [
          /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(Box_default, { width: VALUE_COLUMN_WIDTH, children: /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(Text, { bold: true, color: theme.text.link, dimColor: true, children: "Value" }) }),
          /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(Box_default, { flexGrow: 1, children: /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(Text, { bold: true, color: theme.text.link, dimColor: true, children: "Name" }) })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(Box_default, { flexDirection: "column", children: allRows.map((row) => {
          if (row.type === "standard") return renderStandardRow(row);
          if (row.type === "gradient") return renderGradientRow(row);
          if (row.type === "background") return renderBackgroundRow(row);
          return null;
        }) })
      ]
    }
  );
};
function renderStandardRow({ name, value }) {
  const isHex = value.startsWith("#");
  const displayColor = isHex ? value : theme.text.primary;
  const description = COLOR_DESCRIPTIONS[name] || "";
  return /* @__PURE__ */ (0, import_jsx_runtime77.jsxs)(Box_default, { flexDirection: "row", paddingX: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(Box_default, { width: VALUE_COLUMN_WIDTH, children: /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(Text, { color: displayColor, children: value || "(blank)" }) }),
    /* @__PURE__ */ (0, import_jsx_runtime77.jsxs)(Box_default, { flexGrow: 1, flexDirection: "row", children: [
      /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(Box_default, { width: "30%", children: /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(Text, { color: displayColor, children: name }) }),
      /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(Box_default, { flexGrow: 1, paddingLeft: 1, children: /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(Text, { color: theme.text.secondary, children: description }) })
    ] })
  ] }, name);
}
function renderGradientRow({ name, value }) {
  const description = COLOR_DESCRIPTIONS[name] || "";
  return /* @__PURE__ */ (0, import_jsx_runtime77.jsxs)(Box_default, { flexDirection: "row", paddingX: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(Box_default, { width: VALUE_COLUMN_WIDTH, flexDirection: "column", children: value.map((c2, i) => /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(Text, { color: c2, children: c2 }, i)) }),
    /* @__PURE__ */ (0, import_jsx_runtime77.jsxs)(Box_default, { flexGrow: 1, flexDirection: "row", children: [
      /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(Box_default, { width: "30%", children: /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(dist_default, { colors: value, children: /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(Text, { children: name }) }) }),
      /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(Box_default, { flexGrow: 1, paddingLeft: 1, children: /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(Text, { color: theme.text.secondary, children: description }) })
    ] })
  ] }, name);
}
function renderBackgroundRow({ name, value }) {
  const description = COLOR_DESCRIPTIONS[name] || "";
  return /* @__PURE__ */ (0, import_jsx_runtime77.jsxs)(Box_default, { flexDirection: "row", paddingX: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(
      Box_default,
      {
        width: VALUE_COLUMN_WIDTH,
        backgroundColor: value,
        justifyContent: "center",
        paddingX: 1,
        children: /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(Text, { color: getContrastingTextColor(value), bold: true, wrap: "truncate", children: value || "default" })
      }
    ),
    /* @__PURE__ */ (0, import_jsx_runtime77.jsxs)(Box_default, { flexGrow: 1, flexDirection: "row", paddingLeft: 1, children: [
      /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(Box_default, { width: "30%", children: /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(Text, { color: theme.text.primary, children: name }) }),
      /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(Box_default, { flexGrow: 1, paddingLeft: 1, children: /* @__PURE__ */ (0, import_jsx_runtime77.jsx)(Text, { color: theme.text.secondary, children: description }) })
    ] })
  ] }, name);
}

// packages/cli/src/ui/components/ThemeDialog.tsx
var import_jsx_runtime78 = __toESM(require_jsx_runtime(), 1);
function generateThemeItem(name, typeDisplay, fullTheme, terminalBackgroundColor) {
  const isCompatible = fullTheme ? themeManager.isThemeCompatible(fullTheme, terminalBackgroundColor) : true;
  const themeBackground = fullTheme ? resolveColor(fullTheme.colors.Background) : void 0;
  const isBackgroundMatch = terminalBackgroundColor && themeBackground && terminalBackgroundColor.toLowerCase() === themeBackground.toLowerCase();
  return {
    label: name,
    value: name,
    themeNameDisplay: name,
    themeTypeDisplay: typeDisplay,
    themeWarning: isCompatible ? "" : " (Incompatible)",
    themeMatch: isBackgroundMatch ? " (Matches terminal)" : "",
    key: name,
    isCompatible
  };
}
function ThemeDialog({
  onSelect,
  onCancel,
  onHighlight,
  settings,
  availableTerminalHeight,
  terminalWidth
}) {
  const isAlternateBuffer = useAlternateBuffer();
  const { terminalBackgroundColor } = useUIState();
  const [selectedScope, setSelectedScope] = (0, import_react53.useState)(
    "User" /* User */
  );
  const [highlightedThemeName, setHighlightedThemeName] = (0, import_react53.useState)(
    () => {
      if (settings.merged.ui.theme) {
        return settings.merged.ui.theme;
      }
      return pickDefaultThemeName(
        terminalBackgroundColor,
        themeManager.getAllThemes(),
        DEFAULT_THEME.name,
        "Default Light"
      );
    }
  );
  const capitalize = (s) => s.charAt(0).toUpperCase() + s.slice(1);
  const themeItems = themeManager.getAvailableThemes().map((theme2) => {
    const fullTheme = themeManager.getTheme(theme2.name);
    const capitalizedType = capitalize(theme2.type);
    const typeDisplay = theme2.name.endsWith(capitalizedType) ? "" : capitalizedType;
    return generateThemeItem(
      theme2.name,
      typeDisplay,
      fullTheme,
      terminalBackgroundColor
    );
  }).sort((a, b) => {
    if (a.isCompatible && !b.isCompatible) return -1;
    if (!a.isCompatible && b.isCompatible) return 1;
    return a.label.localeCompare(b.label);
  });
  const initialThemeIndex = themeItems.findIndex(
    (item) => item.value === highlightedThemeName
  );
  const safeInitialThemeIndex = initialThemeIndex >= 0 ? initialThemeIndex : 0;
  const handleThemeSelect = (0, import_react53.useCallback)(
    async (themeName) => {
      await onSelect(themeName, selectedScope);
    },
    [onSelect, selectedScope]
  );
  const handleThemeHighlight = (themeName) => {
    setHighlightedThemeName(themeName);
    onHighlight(themeName);
  };
  const handleScopeHighlight = (0, import_react53.useCallback)((scope) => {
    setSelectedScope(scope);
  }, []);
  const handleScopeSelect = (0, import_react53.useCallback)(
    async (scope) => {
      await onSelect(highlightedThemeName, scope);
    },
    [onSelect, highlightedThemeName]
  );
  const [mode, setMode] = (0, import_react53.useState)("theme");
  useKeypress(
    (key) => {
      if (key.name === "tab") {
        setMode((prev) => prev === "theme" ? "scope" : "theme");
        return true;
      }
      if (key.name === "escape") {
        onCancel();
        return true;
      }
      return false;
    },
    { isActive: true }
  );
  const otherScopeModifiedMessage = getScopeMessageForSetting(
    "ui.theme",
    selectedScope,
    settings
  );
  const PREVIEW_PANE_WIDTH_PERCENTAGE = 0.55;
  const PREVIEW_PANE_WIDTH_SAFETY_MARGIN = 0.9;
  const TOTAL_HORIZONTAL_PADDING = 4;
  const colorizeCodeWidth = Math.max(
    Math.floor(
      (terminalWidth - TOTAL_HORIZONTAL_PADDING) * PREVIEW_PANE_WIDTH_PERCENTAGE * PREVIEW_PANE_WIDTH_SAFETY_MARGIN
    ),
    1
  );
  const DIALOG_PADDING2 = 2;
  const selectThemeHeight = themeItems.length + 1;
  const TAB_TO_SELECT_HEIGHT = 2;
  availableTerminalHeight = availableTerminalHeight ?? Number.MAX_SAFE_INTEGER;
  availableTerminalHeight -= 2;
  availableTerminalHeight -= TAB_TO_SELECT_HEIGHT;
  let totalLeftHandSideHeight = DIALOG_PADDING2 + selectThemeHeight;
  let includePadding = true;
  if (totalLeftHandSideHeight > availableTerminalHeight) {
    includePadding = false;
    totalLeftHandSideHeight -= DIALOG_PADDING2;
  }
  const PREVIEW_PANE_FIXED_VERTICAL_SPACE = 8;
  availableTerminalHeight = Math.max(
    availableTerminalHeight,
    totalLeftHandSideHeight
  );
  const availableTerminalHeightCodeBlock = availableTerminalHeight - PREVIEW_PANE_FIXED_VERTICAL_SPACE - (includePadding ? 2 : 0) * 2;
  const availableHeightForPanes = Math.max(
    0,
    availableTerminalHeightCodeBlock - 1
  );
  const codeBlockHeight = Math.ceil(availableHeightForPanes * 0.6);
  const diffHeight = Math.floor(availableHeightForPanes * 0.4);
  const previewTheme = themeManager.getTheme(highlightedThemeName || DEFAULT_THEME.name) || DEFAULT_THEME;
  return /* @__PURE__ */ (0, import_jsx_runtime78.jsxs)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: theme.border.default,
      flexDirection: "column",
      paddingTop: includePadding ? 1 : 0,
      paddingBottom: includePadding ? 1 : 0,
      paddingLeft: 1,
      paddingRight: 1,
      width: "100%",
      children: [
        mode === "theme" ? /* @__PURE__ */ (0, import_jsx_runtime78.jsxs)(Box_default, { flexDirection: "row", children: [
          /* @__PURE__ */ (0, import_jsx_runtime78.jsxs)(Box_default, { flexDirection: "column", width: "45%", paddingRight: 2, children: [
            /* @__PURE__ */ (0, import_jsx_runtime78.jsxs)(Text, { bold: mode === "theme", wrap: "truncate", children: [
              mode === "theme" ? "> " : "  ",
              "Select Theme",
              " ",
              /* @__PURE__ */ (0, import_jsx_runtime78.jsx)(Text, { color: theme.text.secondary, children: otherScopeModifiedMessage })
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime78.jsx)(
              RadioButtonSelect,
              {
                items: themeItems,
                initialIndex: safeInitialThemeIndex,
                onSelect: handleThemeSelect,
                onHighlight: handleThemeHighlight,
                isFocused: mode === "theme",
                maxItemsToShow: 12,
                showScrollArrows: true,
                showNumbers: mode === "theme",
                renderItem: (item, { titleColor }) => {
                  const itemWithExtras = item;
                  if (item.themeNameDisplay && item.themeTypeDisplay) {
                    const match = item.themeNameDisplay.match(/^(.*) \((.*)\)$/);
                    let themeNamePart = item.themeNameDisplay;
                    if (match) {
                      themeNamePart = /* @__PURE__ */ (0, import_jsx_runtime78.jsxs)(import_jsx_runtime78.Fragment, { children: [
                        match[1],
                        " ",
                        /* @__PURE__ */ (0, import_jsx_runtime78.jsxs)(Text, { color: theme.text.secondary, children: [
                          "(",
                          match[2],
                          ")"
                        ] })
                      ] });
                    }
                    return /* @__PURE__ */ (0, import_jsx_runtime78.jsxs)(Text, { color: titleColor, wrap: "truncate", children: [
                      themeNamePart,
                      " ",
                      /* @__PURE__ */ (0, import_jsx_runtime78.jsx)(Text, { color: theme.text.secondary, children: item.themeTypeDisplay }),
                      itemWithExtras.themeMatch && /* @__PURE__ */ (0, import_jsx_runtime78.jsx)(Text, { color: theme.status.success, children: itemWithExtras.themeMatch }),
                      itemWithExtras.themeWarning && /* @__PURE__ */ (0, import_jsx_runtime78.jsx)(Text, { color: theme.status.warning, children: itemWithExtras.themeWarning })
                    ] }, item.key);
                  }
                  return /* @__PURE__ */ (0, import_jsx_runtime78.jsx)(Text, { color: titleColor, wrap: "truncate", children: item.label });
                }
              }
            )
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime78.jsxs)(Box_default, { flexDirection: "column", width: "55%", paddingLeft: 2, children: [
            /* @__PURE__ */ (0, import_jsx_runtime78.jsx)(Text, { bold: true, color: theme.text.primary, children: "Preview" }),
            /* @__PURE__ */ (0, import_jsx_runtime78.jsxs)(
              Box_default,
              {
                borderStyle: "single",
                borderColor: theme.border.default,
                paddingTop: includePadding ? 1 : 0,
                paddingBottom: includePadding ? 1 : 0,
                paddingLeft: 1,
                paddingRight: 1,
                flexDirection: "column",
                children: [
                  colorizeCode({
                    code: `# function
def fibonacci(n):
    a, b = 0, 1
    for _ in range(n):
        a, b = b, a + b
    return a`,
                    language: "python",
                    availableHeight: isAlternateBuffer === false ? codeBlockHeight : void 0,
                    maxWidth: colorizeCodeWidth,
                    settings
                  }),
                  /* @__PURE__ */ (0, import_jsx_runtime78.jsx)(Box_default, { marginTop: 1 }),
                  /* @__PURE__ */ (0, import_jsx_runtime78.jsx)(
                    DiffRenderer,
                    {
                      diffContent: `--- a/util.py
+++ b/util.py
@@ -1,2 +1,2 @@
- print("Hello, " + name)
+ print(f"Hello, {name}!")
`,
                      availableTerminalHeight: isAlternateBuffer === false ? diffHeight : void 0,
                      terminalWidth: colorizeCodeWidth,
                      theme: previewTheme
                    }
                  )
                ]
              }
            ),
            isDevelopment && /* @__PURE__ */ (0, import_jsx_runtime78.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime78.jsx)(ColorsDisplay, { activeTheme: previewTheme }) })
          ] })
        ] }) : /* @__PURE__ */ (0, import_jsx_runtime78.jsx)(
          ScopeSelector,
          {
            onSelect: handleScopeSelect,
            onHighlight: handleScopeHighlight,
            isFocused: mode === "scope",
            initialScope: selectedScope
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime78.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime78.jsxs)(Text, { color: theme.text.secondary, wrap: "truncate", children: [
          "(Use Enter to ",
          mode === "theme" ? "select" : "apply scope",
          ", Tab to",
          " ",
          mode === "theme" ? "configure scope" : "select theme",
          ", Esc to close)"
        ] }) })
      ]
    }
  );
}

// packages/cli/src/ui/components/SettingsDialog.tsx
var import_react57 = __toESM(require_react(), 1);

// packages/cli/src/ui/components/shared/BaseSettingsDialog.tsx
var import_react56 = __toESM(require_react(), 1);
var import_chalk2 = __toESM(require_source(), 1);

// packages/cli/src/ui/hooks/useSettingsNavigation.ts
var import_react54 = __toESM(require_react(), 1);
function calculateSlidingWindow(start, activeIndex, itemCount, windowSize) {
  if (activeIndex < start) {
    start = activeIndex;
  } else if (activeIndex >= start + windowSize) {
    start = activeIndex - windowSize + 1;
  }
  const maxScroll = Math.max(0, itemCount - windowSize);
  const bounded = Math.min(start, maxScroll);
  return Math.max(0, bounded);
}
function createNavReducer(items, maxItemsToShow) {
  return function navReducer(state, action) {
    if (items.length === 0) return state;
    const currentIndex = items.findIndex((i) => i.key === state.activeItemKey);
    const activeIndex = currentIndex !== -1 ? currentIndex : 0;
    switch (action.type) {
      case "MOVE_UP": {
        const newIndex = activeIndex > 0 ? activeIndex - 1 : items.length - 1;
        return {
          activeItemKey: items[newIndex].key,
          windowStart: calculateSlidingWindow(
            state.windowStart,
            newIndex,
            items.length,
            maxItemsToShow
          )
        };
      }
      case "MOVE_DOWN": {
        const newIndex = activeIndex < items.length - 1 ? activeIndex + 1 : 0;
        return {
          activeItemKey: items[newIndex].key,
          windowStart: calculateSlidingWindow(
            state.windowStart,
            newIndex,
            items.length,
            maxItemsToShow
          )
        };
      }
      default: {
        return state;
      }
    }
  };
}
function useSettingsNavigation({
  items,
  maxItemsToShow
}) {
  const reducer = (0, import_react54.useMemo)(
    () => createNavReducer(items, maxItemsToShow),
    [items, maxItemsToShow]
  );
  const [state, dispatch] = (0, import_react54.useReducer)(reducer, {
    activeItemKey: items[0]?.key ?? null,
    windowStart: 0
  });
  const activeIndex = (0, import_react54.useMemo)(() => {
    if (items.length === 0) return 0;
    const idx = items.findIndex((i) => i.key === state.activeItemKey);
    return idx !== -1 ? idx : 0;
  }, [items, state.activeItemKey]);
  const windowStart = (0, import_react54.useMemo)(
    () => calculateSlidingWindow(
      state.windowStart,
      activeIndex,
      items.length,
      maxItemsToShow
    ),
    [state.windowStart, activeIndex, items.length, maxItemsToShow]
  );
  const moveUp = (0, import_react54.useCallback)(() => dispatch({ type: "MOVE_UP" }), []);
  const moveDown = (0, import_react54.useCallback)(() => dispatch({ type: "MOVE_DOWN" }), []);
  return {
    activeItemKey: state.activeItemKey,
    activeIndex,
    windowStart,
    moveUp,
    moveDown
  };
}

// packages/cli/src/ui/hooks/useInlineEditBuffer.ts
var import_react55 = __toESM(require_react(), 1);
var initialState2 = {
  editingKey: null,
  buffer: "",
  cursorPos: 0
};
function editBufferReducer(state, action) {
  switch (action.type) {
    case "START_EDIT":
      return {
        editingKey: action.key,
        buffer: action.initialValue,
        cursorPos: cpLen(action.initialValue)
      };
    case "COMMIT_EDIT":
      return initialState2;
    case "MOVE_LEFT":
      return {
        ...state,
        cursorPos: Math.max(0, state.cursorPos - 1)
      };
    case "MOVE_RIGHT":
      return {
        ...state,
        cursorPos: Math.min(cpLen(state.buffer), state.cursorPos + 1)
      };
    case "HOME":
      return { ...state, cursorPos: 0 };
    case "END":
      return { ...state, cursorPos: cpLen(state.buffer) };
    case "DELETE_LEFT": {
      if (state.cursorPos === 0) return state;
      const before = cpSlice(state.buffer, 0, state.cursorPos - 1);
      const after = cpSlice(state.buffer, state.cursorPos);
      return {
        ...state,
        buffer: before + after,
        cursorPos: state.cursorPos - 1
      };
    }
    case "DELETE_RIGHT": {
      if (state.cursorPos === cpLen(state.buffer)) return state;
      const before = cpSlice(state.buffer, 0, state.cursorPos);
      const after = cpSlice(state.buffer, state.cursorPos + 1);
      return {
        ...state,
        buffer: before + after
      };
    }
    case "INSERT_CHAR": {
      let ch = action.char;
      let isValidChar = false;
      if (action.isNumberType) {
        isValidChar = /[0-9\-+.]/.test(ch);
      } else {
        isValidChar = ch.length === 1 && ch.charCodeAt(0) >= 32;
        ch = stripUnsafeCharacters(ch);
      }
      if (!isValidChar || ch.length === 0) return state;
      const before = cpSlice(state.buffer, 0, state.cursorPos);
      const after = cpSlice(state.buffer, state.cursorPos);
      return {
        ...state,
        buffer: before + ch + after,
        cursorPos: state.cursorPos + 1
      };
    }
    default:
      return state;
  }
}
function useInlineEditBuffer({ onCommit }) {
  const [state, dispatch] = (0, import_react55.useReducer)(editBufferReducer, initialState2);
  const [cursorVisible, setCursorVisible] = (0, import_react55.useState)(true);
  (0, import_react55.useEffect)(() => {
    if (!state.editingKey) {
      setCursorVisible(true);
      return;
    }
    setCursorVisible(true);
    const interval = setInterval(() => {
      setCursorVisible((v) => !v);
    }, 500);
    return () => clearInterval(interval);
  }, [state.editingKey, state.buffer, state.cursorPos]);
  const startEditing = (0, import_react55.useCallback)((key, initialValue) => {
    dispatch({ type: "START_EDIT", key, initialValue });
  }, []);
  const commitEdit = (0, import_react55.useCallback)(() => {
    if (state.editingKey) {
      onCommit(state.editingKey, state.buffer);
    }
    dispatch({ type: "COMMIT_EDIT" });
  }, [state.editingKey, state.buffer, onCommit]);
  return {
    editState: state,
    editDispatch: dispatch,
    startEditing,
    commitEdit,
    cursorVisible
  };
}

// packages/cli/src/ui/components/shared/BaseSettingsDialog.tsx
var import_jsx_runtime79 = __toESM(require_jsx_runtime(), 1);
function BaseSettingsDialog({
  title,
  borderColor,
  searchEnabled = true,
  searchPlaceholder = "Search to filter",
  searchBuffer,
  items,
  showScopeSelector = true,
  selectedScope,
  onScopeChange,
  maxItemsToShow,
  maxLabelWidth,
  onItemToggle,
  onEditCommit,
  onItemClear,
  onClose,
  onKeyPress,
  keyMatchers: customKeyMatchers,
  availableHeight,
  footer
}) {
  const globalKeyMatchers = useKeyMatchers();
  const keyMatchers = customKeyMatchers ?? globalKeyMatchers;
  const { effectiveMaxItemsToShow, finalShowScopeSelector } = (0, import_react56.useMemo)(() => {
    const initialShowScope = showScopeSelector;
    const initialMaxItems = maxItemsToShow;
    if (!availableHeight) {
      return {
        effectiveMaxItemsToShow: initialMaxItems,
        finalShowScopeSelector: initialShowScope
      };
    }
    const DIALOG_PADDING2 = 4;
    const SETTINGS_TITLE_HEIGHT = 1;
    const SEARCH_SECTION_HEIGHT = searchEnabled ? 5 : 1;
    const SCROLL_ARROWS_HEIGHT = 2;
    const ITEMS_SPACING_AFTER = 1;
    const SCOPE_SECTION_HEIGHT = 5;
    const HELP_TEXT_HEIGHT = 1;
    const FOOTER_CONTENT_HEIGHT = footer?.height ?? 0;
    const ITEM_HEIGHT = 3;
    const currentAvailableHeight = availableHeight - DIALOG_PADDING2;
    const baseFixedHeight = SETTINGS_TITLE_HEIGHT + SEARCH_SECTION_HEIGHT + SCROLL_ARROWS_HEIGHT + ITEMS_SPACING_AFTER + HELP_TEXT_HEIGHT + FOOTER_CONTENT_HEIGHT;
    const heightWithScope = baseFixedHeight + SCOPE_SECTION_HEIGHT;
    const availableForItemsWithScope = currentAvailableHeight - heightWithScope;
    const maxItemsWithScope = Math.max(
      1,
      Math.floor(availableForItemsWithScope / ITEM_HEIGHT)
    );
    const availableForItemsWithoutScope = currentAvailableHeight - baseFixedHeight;
    const maxItemsWithoutScope = Math.max(
      1,
      Math.floor(availableForItemsWithoutScope / ITEM_HEIGHT)
    );
    let shouldShowScope = initialShowScope;
    let maxItems = initialShowScope ? maxItemsWithScope : maxItemsWithoutScope;
    if (initialShowScope && availableHeight < 25) {
      if (maxItemsWithoutScope > maxItemsWithScope + 1) {
        shouldShowScope = false;
        maxItems = maxItemsWithoutScope;
      }
    }
    return {
      effectiveMaxItemsToShow: Math.min(maxItems, items.length),
      finalShowScopeSelector: shouldShowScope
    };
  }, [
    availableHeight,
    maxItemsToShow,
    items.length,
    searchEnabled,
    showScopeSelector,
    footer
  ]);
  const { activeIndex, windowStart, moveUp, moveDown } = useSettingsNavigation({
    items,
    maxItemsToShow: effectiveMaxItemsToShow
  });
  const { editState, editDispatch, startEditing, commitEdit, cursorVisible } = useInlineEditBuffer({
    onCommit: (key, value) => {
      const itemToCommit = items.find((i) => i.key === key);
      if (itemToCommit) {
        onEditCommit(key, value, itemToCommit);
      }
    }
  });
  const {
    editingKey,
    buffer: editBuffer,
    cursorPos: editCursorPos
  } = editState;
  const [focusSection, setFocusSection] = (0, import_react56.useState)(
    "settings"
  );
  const effectiveFocusSection = !finalShowScopeSelector && focusSection === "scope" ? "settings" : focusSection;
  const scopeItems = getScopeItems().map((item) => ({
    ...item,
    key: item.value
  }));
  const visibleItems = items.slice(
    windowStart,
    windowStart + effectiveMaxItemsToShow
  );
  const showScrollUp = items.length > effectiveMaxItemsToShow;
  const showScrollDown = items.length > effectiveMaxItemsToShow;
  const currentItem = items[activeIndex];
  const handleScopeChange = (0, import_react56.useCallback)(
    (scope) => {
      onScopeChange?.(scope);
    },
    [onScopeChange]
  );
  useKeypress(
    (key) => {
      if (!editingKey && onKeyPress?.(key, currentItem)) {
        return;
      }
      if (editingKey) {
        const item = items.find((i) => i.key === editingKey);
        const type = item?.type ?? "string";
        if (keyMatchers["cursor.left" /* MOVE_LEFT */](key)) {
          editDispatch({ type: "MOVE_LEFT" });
          return;
        }
        if (keyMatchers["cursor.right" /* MOVE_RIGHT */](key)) {
          editDispatch({ type: "MOVE_RIGHT" });
          return;
        }
        if (keyMatchers["cursor.home" /* HOME */](key)) {
          editDispatch({ type: "HOME" });
          return;
        }
        if (keyMatchers["cursor.end" /* END */](key)) {
          editDispatch({ type: "END" });
          return;
        }
        if (keyMatchers["edit.deleteLeft" /* DELETE_CHAR_LEFT */](key)) {
          editDispatch({ type: "DELETE_LEFT" });
          return;
        }
        if (keyMatchers["edit.deleteRight" /* DELETE_CHAR_RIGHT */](key)) {
          editDispatch({ type: "DELETE_RIGHT" });
          return;
        }
        if (keyMatchers["basic.cancel" /* ESCAPE */](key)) {
          commitEdit();
          return;
        }
        if (keyMatchers["basic.confirm" /* RETURN */](key)) {
          commitEdit();
          return;
        }
        if (keyMatchers["nav.dialog.up" /* DIALOG_NAVIGATION_UP */](key) && !key.insertable) {
          commitEdit();
          moveUp();
          return;
        }
        if (keyMatchers["nav.dialog.down" /* DIALOG_NAVIGATION_DOWN */](key) && !key.insertable) {
          commitEdit();
          moveDown();
          return;
        }
        if (key.sequence) {
          editDispatch({
            type: "INSERT_CHAR",
            char: key.sequence,
            isNumberType: type === "number"
          });
        }
        return;
      }
      if (effectiveFocusSection === "settings") {
        if (keyMatchers["nav.dialog.up" /* DIALOG_NAVIGATION_UP */](key)) {
          moveUp();
          return true;
        }
        if (keyMatchers["nav.dialog.down" /* DIALOG_NAVIGATION_DOWN */](key)) {
          moveDown();
          return true;
        }
        if (keyMatchers["basic.confirm" /* RETURN */](key) && currentItem) {
          if (currentItem.type === "boolean" || currentItem.type === "enum") {
            onItemToggle(currentItem.key, currentItem);
          } else {
            const rawVal = currentItem.rawValue;
            const initialValue = currentItem.editValue ?? (rawVal !== void 0 ? String(rawVal) : "");
            startEditing(currentItem.key, initialValue);
          }
          return true;
        }
        if (keyMatchers["app.clearScreen" /* CLEAR_SCREEN */](key) && currentItem) {
          onItemClear(currentItem.key, currentItem);
          return true;
        }
        if (currentItem?.type === "number" && /^[0-9]$/.test(key.sequence)) {
          startEditing(currentItem.key, key.sequence);
          return true;
        }
      }
      if (key.name === "tab" && finalShowScopeSelector) {
        setFocusSection((s) => s === "settings" ? "scope" : "settings");
        return;
      }
      if (keyMatchers["basic.cancel" /* ESCAPE */](key)) {
        onClose();
        return;
      }
      return;
    },
    {
      isActive: true,
      priority: effectiveFocusSection === "settings"
    }
  );
  return /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: borderColor ?? theme.border.default,
      flexDirection: "row",
      padding: 1,
      width: "100%",
      height: "100%",
      children: /* @__PURE__ */ (0, import_jsx_runtime79.jsxs)(Box_default, { flexDirection: "column", flexGrow: 1, children: [
        /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(Box_default, { marginX: 1, children: /* @__PURE__ */ (0, import_jsx_runtime79.jsxs)(
          Text,
          {
            bold: effectiveFocusSection === "settings" && !editingKey,
            wrap: "truncate",
            children: [
              effectiveFocusSection === "settings" ? "> " : "  ",
              title,
              " "
            ]
          }
        ) }),
        searchEnabled && searchBuffer && /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(
          Box_default,
          {
            borderStyle: "round",
            borderColor: editingKey ? theme.border.default : effectiveFocusSection === "settings" ? theme.ui.focus : theme.border.default,
            paddingX: 1,
            height: 3,
            marginTop: 1,
            children: /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(
              TextInput,
              {
                focus: effectiveFocusSection === "settings" && !editingKey,
                buffer: searchBuffer,
                placeholder: searchPlaceholder
              }
            )
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(Box_default, { height: 1 }),
        visibleItems.length === 0 ? /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(Box_default, { marginX: 1, height: 1, flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(Text, { color: theme.text.secondary, children: "No matches found." }) }) : /* @__PURE__ */ (0, import_jsx_runtime79.jsxs)(import_jsx_runtime79.Fragment, { children: [
          showScrollUp && /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(Box_default, { marginX: 1, children: /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(Text, { color: theme.text.secondary, children: "\u25B2" }) }),
          visibleItems.map((item, idx) => {
            const globalIndex = idx + windowStart;
            const isActive = effectiveFocusSection === "settings" && activeIndex === globalIndex;
            let displayValue;
            if (editingKey === item.key) {
              if (cursorVisible && editCursorPos < cpLen(editBuffer)) {
                const beforeCursor = cpSlice(editBuffer, 0, editCursorPos);
                const atCursor = cpSlice(
                  editBuffer,
                  editCursorPos,
                  editCursorPos + 1
                );
                const afterCursor = cpSlice(editBuffer, editCursorPos + 1);
                displayValue = beforeCursor + import_chalk2.default.inverse(atCursor) + afterCursor;
              } else if (editCursorPos >= cpLen(editBuffer)) {
                displayValue = editBuffer + (cursorVisible ? import_chalk2.default.inverse(" ") : " ");
              } else {
                displayValue = editBuffer;
              }
            } else {
              displayValue = item.displayValue;
            }
            return /* @__PURE__ */ (0, import_jsx_runtime79.jsxs)(import_react56.default.Fragment, { children: [
              /* @__PURE__ */ (0, import_jsx_runtime79.jsxs)(
                Box_default,
                {
                  marginX: 1,
                  flexDirection: "row",
                  alignItems: "flex-start",
                  backgroundColor: isActive ? theme.background.focus : void 0,
                  children: [
                    /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(Box_default, { minWidth: 2, flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(
                      Text,
                      {
                        color: isActive ? theme.ui.focus : theme.text.secondary,
                        children: isActive ? "\u25CF" : ""
                      }
                    ) }),
                    /* @__PURE__ */ (0, import_jsx_runtime79.jsxs)(
                      Box_default,
                      {
                        flexDirection: "row",
                        flexGrow: 1,
                        minWidth: 0,
                        alignItems: "flex-start",
                        children: [
                          /* @__PURE__ */ (0, import_jsx_runtime79.jsxs)(
                            Box_default,
                            {
                              flexDirection: "column",
                              width: maxLabelWidth,
                              minWidth: 0,
                              children: [
                                /* @__PURE__ */ (0, import_jsx_runtime79.jsxs)(
                                  Text,
                                  {
                                    color: isActive ? theme.ui.focus : theme.text.primary,
                                    children: [
                                      item.label,
                                      item.scopeMessage && /* @__PURE__ */ (0, import_jsx_runtime79.jsxs)(Text, { color: theme.text.secondary, children: [
                                        " ",
                                        item.scopeMessage
                                      ] })
                                    ]
                                  }
                                ),
                                /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(Text, { color: theme.text.secondary, wrap: "truncate", children: item.description ?? "" })
                              ]
                            }
                          ),
                          /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(Box_default, { minWidth: 3 }),
                          /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(Box_default, { flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(
                            Text,
                            {
                              color: isActive ? theme.ui.focus : item.isGreyedOut ? theme.text.secondary : theme.text.primary,
                              terminalCursorFocus: editingKey === item.key && cursorVisible,
                              terminalCursorPosition: cpIndexToOffset(
                                editBuffer,
                                editCursorPos
                              ),
                              children: displayValue
                            }
                          ) })
                        ]
                      }
                    )
                  ]
                }
              ),
              /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(Box_default, { height: 1 })
            ] }, item.key);
          }),
          showScrollDown && /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(Box_default, { marginX: 1, children: /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(Text, { color: theme.text.secondary, children: "\u25BC" }) })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(Box_default, { height: 1 }),
        finalShowScopeSelector && /* @__PURE__ */ (0, import_jsx_runtime79.jsxs)(Box_default, { marginX: 1, flexDirection: "column", children: [
          /* @__PURE__ */ (0, import_jsx_runtime79.jsxs)(Text, { bold: effectiveFocusSection === "scope", wrap: "truncate", children: [
            effectiveFocusSection === "scope" ? "> " : "  ",
            "Apply To"
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(
            RadioButtonSelect,
            {
              items: scopeItems,
              initialIndex: scopeItems.findIndex(
                (item) => item.value === selectedScope
              ),
              onSelect: handleScopeChange,
              onHighlight: handleScopeChange,
              isFocused: effectiveFocusSection === "scope",
              showNumbers: effectiveFocusSection === "scope",
              priority: effectiveFocusSection === "scope"
            }
          )
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(Box_default, { height: 1 }),
        /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(Box_default, { marginX: 1, children: /* @__PURE__ */ (0, import_jsx_runtime79.jsxs)(Text, { color: theme.text.secondary, children: [
          "(Use Enter to select, ",
          formatCommand("app.clearScreen" /* CLEAR_SCREEN */),
          " to reset",
          finalShowScopeSelector ? ", Tab to change focus" : "",
          ", Esc to close)"
        ] }) }),
        footer && /* @__PURE__ */ (0, import_jsx_runtime79.jsx)(Box_default, { marginX: 1, children: footer.content })
      ] })
    }
  );
}

// packages/cli/src/ui/components/SettingsDialog.tsx
var import_jsx_runtime80 = __toESM(require_jsx_runtime(), 1);
var MAX_ITEMS_TO_SHOW = 8;
var KEY_UP = new KeyBinding("up");
var KEY_CTRL_P = new KeyBinding("ctrl+p");
var KEY_DOWN = new KeyBinding("down");
var KEY_CTRL_N = new KeyBinding("ctrl+n");
function getActiveRestartRequiredSettings(settings) {
  const snapshot = /* @__PURE__ */ new Map();
  const scopes = [
    ["User", settings.user.settings],
    ["Workspace", settings.workspace.settings],
    ["System", settings.system.settings]
  ];
  for (const key of getDialogRestartRequiredSettings()) {
    const scopeMap = /* @__PURE__ */ new Map();
    for (const [scopeName, scopeSettings] of scopes) {
      const value = isInSettingsScope(key, scopeSettings) ? getEffectiveValue(key, scopeSettings) : void 0;
      scopeMap.set(scopeName, JSON.stringify(value));
    }
    snapshot.set(key, scopeMap);
  }
  return snapshot;
}
function SettingsDialog({
  onSelect,
  onRestartRequest,
  availableTerminalHeight
}) {
  const { settings, setSetting } = useSettingsStore();
  const [selectedScope, setSelectedScope] = (0, import_react57.useState)(
    "User" /* User */
  );
  const [activeRestartRequiredSettings] = (0, import_react57.useState)(
    () => getActiveRestartRequiredSettings(settings)
  );
  const [searchQuery, setSearchQuery] = (0, import_react57.useState)("");
  const [filteredKeys, setFilteredKeys] = (0, import_react57.useState)(
    () => getDialogSettingKeys()
  );
  const { fzfInstance, searchMap } = (0, import_react57.useMemo)(() => {
    const keys = getDialogSettingKeys();
    const map = /* @__PURE__ */ new Map();
    const searchItems = [];
    keys.forEach((key) => {
      const def = getSettingDefinition(key);
      if (def?.label) {
        searchItems.push(def.label);
        map.set(def.label.toLowerCase(), key);
      }
    });
    const fzf = new AsyncFzf(searchItems, {
      fuzzy: "v2",
      casing: "case-insensitive"
    });
    return { fzfInstance: fzf, searchMap: map };
  }, []);
  (0, import_react57.useEffect)(() => {
    let active = true;
    if (!searchQuery.trim() || !fzfInstance) {
      setFilteredKeys(getDialogSettingKeys());
      return;
    }
    const doSearch = async () => {
      const results = await fzfInstance.find(searchQuery);
      if (!active) return;
      const matchedKeys = /* @__PURE__ */ new Set();
      results.forEach((res) => {
        const key = searchMap.get(res.item.toLowerCase());
        if (key) matchedKeys.add(key);
      });
      setFilteredKeys(Array.from(matchedKeys));
    };
    doSearch();
    return () => {
      active = false;
    };
  }, [searchQuery, fzfInstance, searchMap]);
  const pendingRestartRequiredSettings = (0, import_react57.useMemo)(() => {
    const changed = /* @__PURE__ */ new Set();
    const scopes = [
      ["User", settings.user.settings],
      ["Workspace", settings.workspace.settings],
      ["System", settings.system.settings]
    ];
    for (const [key, initialScopeMap] of activeRestartRequiredSettings) {
      for (const [scopeName, scopeSettings] of scopes) {
        const currentValue = isInSettingsScope(key, scopeSettings) ? getEffectiveValue(key, scopeSettings) : void 0;
        const initialJson = initialScopeMap.get(scopeName);
        if (JSON.stringify(currentValue) !== initialJson) {
          changed.add(key);
          break;
        }
      }
    }
    return changed;
  }, [settings, activeRestartRequiredSettings]);
  const showRestartPrompt = pendingRestartRequiredSettings.size > 0;
  const maxLabelOrDescriptionWidth = (0, import_react57.useMemo)(() => {
    const allKeys = getDialogSettingKeys();
    let max = 0;
    for (const key of allKeys) {
      const def = getSettingDefinition(key);
      if (!def) continue;
      const scopeMessage = getScopeMessageForSetting(
        key,
        selectedScope,
        settings
      );
      const label = def.label || key;
      const labelFull = label + (scopeMessage ? ` ${scopeMessage}` : "");
      const lWidth = getCachedStringWidth(labelFull);
      const dWidth = def.description ? getCachedStringWidth(def.description) : 0;
      max = Math.max(max, lWidth, dWidth);
    }
    return max;
  }, [selectedScope, settings]);
  const searchBuffer = useSearchBuffer({
    initialText: "",
    onChange: setSearchQuery
  });
  const settingKeys = searchQuery ? filteredKeys : getDialogSettingKeys();
  const items = (0, import_react57.useMemo)(() => {
    const scopeSettings = settings.forScope(selectedScope).settings;
    const mergedSettings = settings.merged;
    return settingKeys.map((key) => {
      const definition = getSettingDefinition(key);
      const type = definition?.type ?? "string";
      const displayValue = getDisplayValue(key, scopeSettings, mergedSettings);
      const scopeMessage = getScopeMessageForSetting(
        key,
        selectedScope,
        settings
      );
      const isGreyedOut = !isInSettingsScope(key, scopeSettings);
      const rawValue = getEffectiveValue(key, scopeSettings);
      const editValue = getEditValue(type, rawValue);
      return {
        key,
        label: definition?.label || key,
        description: definition?.description,
        type,
        displayValue,
        isGreyedOut,
        scopeMessage,
        rawValue,
        editValue
      };
    });
  }, [settingKeys, selectedScope, settings]);
  const handleScopeChange = (0, import_react57.useCallback)((scope) => {
    setSelectedScope(scope);
  }, []);
  const handleItemToggle = (0, import_react57.useCallback)(
    (key, _item) => {
      const definition = getSettingDefinition(key);
      if (!TOGGLE_TYPES.has(definition?.type)) {
        return;
      }
      const scopeSettings = settings.forScope(selectedScope).settings;
      const currentValue = getEffectiveValue(key, scopeSettings);
      let newValue;
      if (definition?.type === "boolean") {
        if (typeof currentValue !== "boolean") {
          return;
        }
        newValue = !currentValue;
      } else if (definition?.type === "enum" && definition.options) {
        const options = definition.options;
        if (options.length === 0) {
          return;
        }
        const currentIndex = options?.findIndex(
          (opt) => opt.value === currentValue
        );
        if (currentIndex !== -1 && currentIndex < options.length - 1) {
          newValue = options[currentIndex + 1].value;
        } else {
          newValue = options[0].value;
        }
      } else {
        return;
      }
      debugLogger.log(
        `[DEBUG SettingsDialog] Saving ${key} immediately with value:`,
        newValue
      );
      setSetting(selectedScope, key, newValue);
    },
    [settings, selectedScope, setSetting]
  );
  const handleEditCommit = (0, import_react57.useCallback)(
    (key, newValue, _item) => {
      const definition = getSettingDefinition(key);
      const type = definition?.type ?? "string";
      const parsed = parseEditedValue(type, newValue);
      if (parsed === null) {
        return;
      }
      setSetting(selectedScope, key, parsed);
    },
    [selectedScope, setSetting]
  );
  const handleItemClear = (0, import_react57.useCallback)(
    (key, _item) => {
      setSetting(selectedScope, key, void 0);
    },
    [selectedScope, setSetting]
  );
  const handleClose = (0, import_react57.useCallback)(() => {
    onSelect(void 0, selectedScope);
  }, [onSelect, selectedScope]);
  const globalKeyMatchers = useKeyMatchers();
  const settingsKeyMatchers = (0, import_react57.useMemo)(
    () => ({
      ...globalKeyMatchers,
      ["nav.dialog.up" /* DIALOG_NAVIGATION_UP */]: (key) => KEY_UP.matches(key) || KEY_CTRL_P.matches(key),
      ["nav.dialog.down" /* DIALOG_NAVIGATION_DOWN */]: (key) => KEY_DOWN.matches(key) || KEY_CTRL_N.matches(key)
    }),
    [globalKeyMatchers]
  );
  const handleKeyPress = (0, import_react57.useCallback)(
    (key, _currentItem) => {
      if (showRestartPrompt && key.sequence === "r") {
        if (onRestartRequest) onRestartRequest();
        return true;
      }
      return false;
    },
    [showRestartPrompt, onRestartRequest]
  );
  const hasWorkspace = settings.workspace.path !== void 0;
  const showSearch = !showRestartPrompt;
  return /* @__PURE__ */ (0, import_jsx_runtime80.jsx)(
    BaseSettingsDialog,
    {
      title: "Settings",
      borderColor: showRestartPrompt ? theme.status.warning : void 0,
      searchEnabled: showSearch,
      searchBuffer,
      items,
      showScopeSelector: hasWorkspace,
      selectedScope,
      onScopeChange: handleScopeChange,
      maxItemsToShow: MAX_ITEMS_TO_SHOW,
      availableHeight: availableTerminalHeight,
      maxLabelWidth: maxLabelOrDescriptionWidth,
      onItemToggle: handleItemToggle,
      onEditCommit: handleEditCommit,
      onItemClear: handleItemClear,
      onClose: handleClose,
      onKeyPress: handleKeyPress,
      keyMatchers: settingsKeyMatchers,
      footer: showRestartPrompt ? {
        content: /* @__PURE__ */ (0, import_jsx_runtime80.jsx)(Text, { color: theme.status.warning, children: "Changes that require a restart have been modified. Press r to exit and apply changes now." }),
        height: 1
      } : void 0
    }
  );
}

// packages/cli/src/ui/auth/AuthInProgress.tsx
var import_react58 = __toESM(require_react(), 1);
var import_jsx_runtime81 = __toESM(require_jsx_runtime(), 1);
function AuthInProgress({
  onTimeout
}) {
  const [timedOut, setTimedOut] = (0, import_react58.useState)(false);
  useKeypress(
    (key) => {
      if (key.name === "escape" || key.ctrl && key.name === "c") {
        onTimeout();
      }
    },
    { isActive: true }
  );
  (0, import_react58.useEffect)(() => {
    const timer = setTimeout(() => {
      setTimedOut(true);
      onTimeout();
    }, 18e4);
    return () => clearTimeout(timer);
  }, [onTimeout]);
  return /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: theme.border.default,
      flexDirection: "column",
      padding: 1,
      width: "100%",
      children: timedOut ? /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(Text, { color: theme.status.error, children: "Authentication timed out. Please try again." }) : /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime81.jsxs)(Text, { children: [
        /* @__PURE__ */ (0, import_jsx_runtime81.jsx)(CliSpinner, { type: "dots" }),
        " Waiting for authentication... (Press Esc or Ctrl+C to cancel)"
      ] }) })
    }
  );
}

// packages/cli/src/ui/auth/AuthDialog.tsx
var import_react60 = __toESM(require_react(), 1);

// packages/cli/src/ui/auth/useAuth.ts
var import_react59 = __toESM(require_react(), 1);
function validateAuthMethodWithSettings(authType, settings) {
  const enforcedType = settings.merged.security.auth.enforcedType;
  if (enforcedType && enforcedType !== authType) {
    return `Authentication is enforced to be ${enforcedType}, but you are currently using ${authType}.`;
  }
  if (settings.merged.security.auth.useExternal) {
    return null;
  }
  if (authType === AuthType.USE_GEMINI) {
    return null;
  }
  return validateAuthMethod(authType);
}
var useAuthCommand = (settings, config, initialAuthError = null, initialAccountSuspensionInfo = null) => {
  const [authState, setAuthState] = (0, import_react59.useState)(
    initialAuthError ? "updating" /* Updating */ : "unauthenticated" /* Unauthenticated */
  );
  const [authError, setAuthError] = (0, import_react59.useState)(initialAuthError);
  const [accountSuspensionInfo, setAccountSuspensionInfo] = (0, import_react59.useState)(initialAccountSuspensionInfo);
  const [apiKeyDefaultValue, setApiKeyDefaultValue] = (0, import_react59.useState)(void 0);
  const onAuthError = (0, import_react59.useCallback)(
    (error) => {
      setAuthError(error);
      if (error) {
        setAuthState("updating" /* Updating */);
      }
    },
    [setAuthError, setAuthState]
  );
  const reloadApiKey = (0, import_react59.useCallback)(async () => {
    const envKey = process.env["GEMINI_API_KEY"];
    if (envKey !== void 0) {
      setApiKeyDefaultValue(envKey);
      return envKey;
    }
    const storedKey = await loadApiKey() ?? "";
    setApiKeyDefaultValue(storedKey);
    return storedKey;
  }, []);
  (0, import_react59.useEffect)(() => {
    if (authState === "awaiting_api_key_input" /* AwaitingApiKeyInput */) {
      reloadApiKey();
    }
  }, [authState, reloadApiKey]);
  (0, import_react59.useEffect)(() => {
    (async () => {
      if (authState !== "unauthenticated" /* Unauthenticated */) {
        return;
      }
      const authType = settings.merged.security.auth.selectedType;
      if (!authType) {
        if (process.env["GEMINI_API_KEY"]) {
          onAuthError(
            'Existing API key detected (GEMINI_API_KEY). Select "Gemini API Key" option to use it.'
          );
        } else {
          onAuthError("No authentication method selected.");
        }
        return;
      }
      if (authType === AuthType.USE_GEMINI) {
        const key = await reloadApiKey();
        if (!key) {
          setAuthState("awaiting_api_key_input" /* AwaitingApiKeyInput */);
          return;
        }
      }
      const error = validateAuthMethodWithSettings(authType, settings);
      if (error) {
        onAuthError(error);
        return;
      }
      const defaultAuthType = process.env["GEMINI_DEFAULT_AUTH_TYPE"];
      if (defaultAuthType && // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
      !Object.values(AuthType).includes(defaultAuthType)) {
        onAuthError(
          `Invalid value for GEMINI_DEFAULT_AUTH_TYPE: "${defaultAuthType}". Valid values are: ${Object.values(AuthType).join(", ")}.`
        );
        return;
      }
      try {
        await config.refreshAuth(authType);
        debugLogger.log(`Authenticated via "${authType}".`);
        setAuthError(null);
        setAuthState("authenticated" /* Authenticated */);
      } catch (e) {
        const suspendedError = isAccountSuspendedError(e);
        if (suspendedError) {
          setAccountSuspensionInfo({
            message: suspendedError.message,
            appealUrl: suspendedError.appealUrl,
            appealLinkText: suspendedError.appealLinkText
          });
        } else if (e instanceof ProjectIdRequiredError) {
          onAuthError(getErrorMessage(e));
        } else {
          onAuthError(`Failed to sign in. Message: ${getErrorMessage(e)}`);
        }
      }
    })();
  }, [
    settings,
    config,
    authState,
    setAuthState,
    setAuthError,
    onAuthError,
    reloadApiKey
  ]);
  return {
    authState,
    setAuthState,
    authError,
    onAuthError,
    apiKeyDefaultValue,
    reloadApiKey,
    accountSuspensionInfo,
    setAccountSuspensionInfo
  };
};

// packages/cli/src/ui/auth/AuthDialog.tsx
var import_jsx_runtime82 = __toESM(require_jsx_runtime(), 1);
function AuthDialog({
  config,
  settings,
  setAuthState,
  authError,
  onAuthError,
  setAuthContext
}) {
  const [exiting, setExiting] = (0, import_react60.useState)(false);
  let items = [
    {
      label: "Sign in with Google",
      value: AuthType.LOGIN_WITH_GOOGLE,
      key: AuthType.LOGIN_WITH_GOOGLE
    },
    ...process.env["CLOUD_SHELL"] === "true" ? [
      {
        label: "Use Cloud Shell user credentials",
        value: AuthType.COMPUTE_ADC,
        key: AuthType.COMPUTE_ADC
      }
    ] : process.env["GEMINI_CLI_USE_COMPUTE_ADC"] === "true" ? [
      {
        label: "Use metadata server application default credentials",
        value: AuthType.COMPUTE_ADC,
        key: AuthType.COMPUTE_ADC
      }
    ] : [],
    {
      label: "Use Gemini API Key",
      value: AuthType.USE_GEMINI,
      key: AuthType.USE_GEMINI
    },
    {
      label: "Vertex AI",
      value: AuthType.USE_VERTEX_AI,
      key: AuthType.USE_VERTEX_AI
    }
  ];
  if (settings.merged.security.auth.enforcedType) {
    items = items.filter(
      (item) => item.value === settings.merged.security.auth.enforcedType
    );
  }
  let defaultAuthType = null;
  const defaultAuthTypeEnv = process.env["GEMINI_DEFAULT_AUTH_TYPE"];
  if (defaultAuthTypeEnv && // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
  Object.values(AuthType).includes(defaultAuthTypeEnv)) {
    defaultAuthType = defaultAuthTypeEnv;
  }
  let initialAuthIndex = items.findIndex((item) => {
    if (settings.merged.security.auth.selectedType) {
      return item.value === settings.merged.security.auth.selectedType;
    }
    if (defaultAuthType) {
      return item.value === defaultAuthType;
    }
    if (process.env["GEMINI_API_KEY"]) {
      return item.value === AuthType.USE_GEMINI;
    }
    return item.value === AuthType.LOGIN_WITH_GOOGLE;
  });
  if (settings.merged.security.auth.enforcedType) {
    initialAuthIndex = 0;
  }
  const onSelect = (0, import_react60.useCallback)(
    async (authType, scope) => {
      if (exiting) {
        return;
      }
      if (authType) {
        if (authType === AuthType.LOGIN_WITH_GOOGLE) {
          setAuthContext({ requiresRestart: true });
        } else {
          setAuthContext({});
        }
        await clearCachedCredentialFile();
        settings.setValue(scope, "security.auth.selectedType", authType);
        if (authType === AuthType.LOGIN_WITH_GOOGLE && config.isBrowserLaunchSuppressed()) {
          setExiting(true);
          setTimeout(relaunchApp, 100);
          return;
        }
        if (authType === AuthType.USE_GEMINI) {
          setAuthState("awaiting_api_key_input" /* AwaitingApiKeyInput */);
          return;
        }
      }
      setAuthState("unauthenticated" /* Unauthenticated */);
    },
    [settings, config, setAuthState, exiting, setAuthContext]
  );
  const handleAuthSelect = (authMethod) => {
    const error = validateAuthMethodWithSettings(authMethod, settings);
    if (error) {
      onAuthError(error);
    } else {
      onSelect(authMethod, "User" /* User */);
    }
  };
  useKeypress(
    (key) => {
      if (key.name === "escape") {
        if (authError) {
          return true;
        }
        if (settings.merged.security.auth.selectedType === void 0) {
          onAuthError(
            "You must select an auth method to proceed. Press Ctrl+C twice to exit."
          );
          return true;
        }
        onSelect(void 0, "User" /* User */);
        return true;
      }
      return false;
    },
    { isActive: true }
  );
  if (exiting) {
    return /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(
      Box_default,
      {
        borderStyle: "round",
        borderColor: theme.ui.focus,
        flexDirection: "row",
        padding: 1,
        width: "100%",
        alignItems: "flex-start",
        children: /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Text, { color: theme.text.primary, children: "Logging in with Google... Restarting Gemini CLI to continue." })
      }
    );
  }
  return /* @__PURE__ */ (0, import_jsx_runtime82.jsxs)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: theme.ui.focus,
      flexDirection: "row",
      padding: 1,
      width: "100%",
      alignItems: "flex-start",
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Text, { color: theme.text.accent, children: "? " }),
        /* @__PURE__ */ (0, import_jsx_runtime82.jsxs)(Box_default, { flexDirection: "column", flexGrow: 1, children: [
          /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Text, { bold: true, color: theme.text.primary, children: "Get started" }),
          /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Text, { color: theme.text.primary, children: "How would you like to authenticate for this project?" }) }),
          /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(
            RadioButtonSelect,
            {
              items,
              initialIndex: initialAuthIndex,
              onSelect: handleAuthSelect,
              onHighlight: () => {
                onAuthError(null);
              }
            }
          ) }),
          authError && /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Text, { color: theme.status.error, children: authError }) }),
          /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Text, { color: theme.text.secondary, children: "(Use Enter to select)" }) }),
          /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Text, { color: theme.text.primary, children: "Terms of Services and Privacy Notice for Gemini CLI" }) }),
          /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime82.jsx)(Text, { color: theme.text.link, children: "https://geminicli.com/docs/resources/tos-privacy/" }) })
        ] })
      ]
    }
  );
}

// packages/cli/src/ui/auth/BannedAccountDialog.tsx
var import_react61 = __toESM(require_react(), 1);
var import_jsx_runtime83 = __toESM(require_jsx_runtime(), 1);
function BannedAccountDialog({
  accountSuspensionInfo,
  onExit,
  onChangeAuth
}) {
  const [errorMessage, setErrorMessage] = (0, import_react61.useState)(null);
  const appealUrl = accountSuspensionInfo.appealUrl;
  const appealLinkText = accountSuspensionInfo.appealLinkText ?? "Open the Google Form";
  const items = (0, import_react61.useMemo)(() => {
    const menuItems = [];
    if (appealUrl) {
      menuItems.push({
        label: appealLinkText,
        value: "open_form",
        key: "open_form"
      });
    }
    menuItems.push(
      {
        label: "Change authentication",
        value: "change_auth",
        key: "change_auth"
      },
      {
        label: "Exit",
        value: "exit",
        key: "exit"
      }
    );
    return menuItems;
  }, [appealUrl, appealLinkText]);
  useKeypress(
    (key) => {
      if (key.name === "escape") {
        void handleExit();
        return true;
      }
      return false;
    },
    { isActive: true }
  );
  const handleExit = (0, import_react61.useCallback)(async () => {
    await runExitCleanup();
    onExit();
  }, [onExit]);
  const handleSelect = (0, import_react61.useCallback)(
    async (choice) => {
      if (choice === "open_form" && appealUrl) {
        if (!shouldLaunchBrowser()) {
          setErrorMessage(`Please open this URL in a browser: ${appealUrl}`);
          return;
        }
        try {
          await openBrowserSecurely(appealUrl);
        } catch {
          setErrorMessage(`Failed to open browser. Please visit: ${appealUrl}`);
        }
      } else if (choice === "change_auth") {
        onChangeAuth();
      } else {
        await handleExit();
      }
    },
    [handleExit, onChangeAuth, appealUrl]
  );
  return /* @__PURE__ */ (0, import_jsx_runtime83.jsxs)(Box_default, { flexDirection: "column", padding: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime83.jsx)(Text, { bold: true, color: theme.status.error, children: "Error: Account Suspended" }),
    /* @__PURE__ */ (0, import_jsx_runtime83.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime83.jsx)(Text, { children: accountSuspensionInfo.message }) }),
    appealUrl && /* @__PURE__ */ (0, import_jsx_runtime83.jsxs)(import_jsx_runtime83.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime83.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime83.jsx)(Text, { children: "Appeal URL:" }) }),
      /* @__PURE__ */ (0, import_jsx_runtime83.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime83.jsxs)(Text, { color: theme.text.link, children: [
        "[",
        appealUrl,
        "]"
      ] }) })
    ] }),
    errorMessage && /* @__PURE__ */ (0, import_jsx_runtime83.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime83.jsx)(Text, { color: theme.status.error, children: errorMessage }) }),
    /* @__PURE__ */ (0, import_jsx_runtime83.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime83.jsx)(
      RadioButtonSelect,
      {
        items,
        onSelect: (choice) => void handleSelect(choice)
      }
    ) }),
    /* @__PURE__ */ (0, import_jsx_runtime83.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime83.jsx)(Text, { dimColor: true, children: "Escape to exit" }) })
  ] });
}

// packages/cli/src/ui/auth/ApiAuthDialog.tsx
var import_react62 = __toESM(require_react(), 1);
var import_jsx_runtime84 = __toESM(require_jsx_runtime(), 1);
function ApiAuthDialog({
  onSubmit,
  onCancel,
  error,
  defaultValue = ""
}) {
  const keyMatchers = useKeyMatchers();
  const { terminalWidth } = useUIState();
  const viewportWidth = terminalWidth - 8;
  const pendingPromise = (0, import_react62.useRef)(null);
  (0, import_react62.useEffect)(
    () => () => {
      pendingPromise.current?.cancel();
    },
    []
  );
  const initialApiKey = defaultValue;
  const buffer = useTextBuffer({
    initialText: initialApiKey || "",
    initialCursorOffset: initialApiKey?.length || 0,
    viewport: {
      width: viewportWidth,
      height: 4
    },
    inputFilter: (text) => text.replace(/[^a-zA-Z0-9_-]/g, "").replace(/[\r\n]/g, ""),
    singleLine: true
  });
  const handleSubmit = (value) => {
    onSubmit(value);
  };
  const handleClear = () => {
    pendingPromise.current?.cancel();
    let isCancelled = false;
    const wrappedPromise = new Promise((resolve3, reject) => {
      clearApiKey().then(
        () => !isCancelled && resolve3(),
        (error2) => !isCancelled && reject(error2)
      );
    });
    pendingPromise.current = {
      cancel: () => {
        isCancelled = true;
      }
    };
    return wrappedPromise.then(() => {
      buffer.setText("");
    }).catch((err) => {
      debugLogger.debug("Failed to clear API key:", err);
    });
  };
  useKeypress(
    (key) => {
      if (keyMatchers["edit.clear" /* CLEAR_INPUT */](key)) {
        void handleClear();
        return true;
      }
      return false;
    },
    { isActive: true }
  );
  return /* @__PURE__ */ (0, import_jsx_runtime84.jsxs)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: theme.ui.focus,
      flexDirection: "column",
      padding: 1,
      width: "100%",
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(Text, { bold: true, color: theme.text.primary, children: "Enter Gemini API Key" }),
        /* @__PURE__ */ (0, import_jsx_runtime84.jsxs)(Box_default, { marginTop: 1, flexDirection: "column", children: [
          /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(Text, { color: theme.text.primary, children: "Please enter your Gemini API key. It will be securely stored in your system keychain." }),
          /* @__PURE__ */ (0, import_jsx_runtime84.jsxs)(Text, { color: theme.text.secondary, children: [
            "You can get an API key from",
            " ",
            /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(Text, { color: theme.text.link, children: "https://aistudio.google.com/app/apikey" })
          ] })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(Box_default, { marginTop: 1, flexDirection: "row", children: /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(
          Box_default,
          {
            borderStyle: "round",
            borderColor: theme.border.default,
            paddingX: 1,
            flexGrow: 1,
            children: /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(
              TextInput,
              {
                buffer,
                onSubmit: handleSubmit,
                onCancel,
                placeholder: "Paste your API key here"
              }
            )
          }
        ) }),
        error && /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(Text, { color: theme.status.error, children: error }) }),
        /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime84.jsx)(Text, { color: theme.text.secondary, children: "(Press Enter to submit, Esc to cancel, Ctrl+C to clear stored key)" }) })
      ]
    }
  );
}

// packages/cli/src/ui/components/EditorSettingsDialog.tsx
var import_react63 = __toESM(require_react(), 1);

// packages/cli/src/ui/editors/editorSettingsManager.ts
var EditorSettingsManager = class {
  availableEditors;
  constructor() {
    const editorTypes = Object.keys(
      EDITOR_DISPLAY_NAMES
    ).sort();
    this.availableEditors = [
      {
        name: "None",
        type: "not_set",
        disabled: false
      },
      ...editorTypes.map((type) => {
        const hasEditor = hasValidEditorCommand(type);
        const isAllowedInSandbox = allowEditorTypeInSandbox(type);
        let labelSuffix = !isAllowedInSandbox ? " (Not available in sandbox)" : "";
        labelSuffix = !hasEditor ? " (Not installed)" : labelSuffix;
        return {
          name: EDITOR_DISPLAY_NAMES[type] + labelSuffix,
          type,
          disabled: !hasEditor || !isAllowedInSandbox
        };
      })
    ];
  }
  getAvailableEditorDisplays() {
    return this.availableEditors;
  }
};
var editorSettingsManager = new EditorSettingsManager();

// packages/cli/src/ui/components/EditorSettingsDialog.tsx
var import_jsx_runtime85 = __toESM(require_jsx_runtime(), 1);
function EditorSettingsDialog({
  onSelect,
  settings,
  onExit
}) {
  const [selectedScope, setSelectedScope] = (0, import_react63.useState)(
    "User" /* User */
  );
  const [focusedSection, setFocusedSection] = (0, import_react63.useState)(
    "editor"
  );
  useKeypress(
    (key) => {
      if (key.name === "tab") {
        setFocusedSection((prev) => prev === "editor" ? "scope" : "editor");
        return true;
      }
      if (key.name === "escape") {
        onExit();
        return true;
      }
      return false;
    },
    { isActive: true }
  );
  const editorItems = editorSettingsManager.getAvailableEditorDisplays();
  const currentPreference = settings.forScope(selectedScope).settings.general?.preferredEditor;
  let editorIndex = currentPreference ? editorItems.findIndex(
    (item) => item.type === currentPreference
  ) : 0;
  if (editorIndex === -1) {
    coreEvents.emitFeedback(
      "error",
      `Editor is not supported: ${currentPreference}`
    );
    editorIndex = 0;
  }
  const scopeItems = [
    {
      label: "User Settings",
      value: "User" /* User */,
      key: "User" /* User */
    },
    {
      label: "Workspace Settings",
      value: "Workspace" /* Workspace */,
      key: "Workspace" /* Workspace */
    }
  ];
  const handleEditorSelect = (editorType) => {
    if (editorType === "not_set") {
      onSelect(void 0, selectedScope);
      return;
    }
    onSelect(editorType, selectedScope);
  };
  const handleScopeSelect = (scope) => {
    setSelectedScope(scope);
    setFocusedSection("editor");
  };
  let otherScopeModifiedMessage = "";
  const otherScope = selectedScope === "User" /* User */ ? "Workspace" /* Workspace */ : "User" /* User */;
  if (settings.forScope(otherScope).settings.general?.preferredEditor !== void 0) {
    otherScopeModifiedMessage = settings.forScope(selectedScope).settings.general?.preferredEditor !== void 0 ? `(Also modified in ${otherScope})` : `(Modified in ${otherScope})`;
  }
  let mergedEditorName = "None";
  if (settings.merged.general.preferredEditor && isEditorAvailable(settings.merged.general.preferredEditor)) {
    mergedEditorName = EDITOR_DISPLAY_NAMES[
      // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
      settings.merged.general.preferredEditor
    ];
  }
  return /* @__PURE__ */ (0, import_jsx_runtime85.jsxs)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: theme.border.default,
      flexDirection: "row",
      padding: 1,
      width: "100%",
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime85.jsxs)(Box_default, { flexDirection: "column", width: "45%", paddingRight: 2, children: [
          /* @__PURE__ */ (0, import_jsx_runtime85.jsxs)(Text, { bold: focusedSection === "editor", children: [
            focusedSection === "editor" ? "> " : "  ",
            "Select Editor",
            " ",
            /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Text, { color: theme.text.secondary, children: otherScopeModifiedMessage })
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(
            RadioButtonSelect,
            {
              items: editorItems.map((item) => ({
                label: item.name,
                value: item.type,
                disabled: item.disabled,
                key: item.type
              })),
              initialIndex: editorIndex,
              onSelect: handleEditorSelect,
              isFocused: focusedSection === "editor"
            },
            selectedScope
          ),
          /* @__PURE__ */ (0, import_jsx_runtime85.jsxs)(Box_default, { marginTop: 1, flexDirection: "column", children: [
            /* @__PURE__ */ (0, import_jsx_runtime85.jsxs)(Text, { bold: focusedSection === "scope", children: [
              focusedSection === "scope" ? "> " : "  ",
              "Apply To"
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(
              RadioButtonSelect,
              {
                items: scopeItems,
                initialIndex: 0,
                onSelect: handleScopeSelect,
                isFocused: focusedSection === "scope"
              }
            )
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Text, { color: theme.text.secondary, children: "(Use Enter to select, Tab to change focus, Esc to close)" }) })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime85.jsxs)(Box_default, { flexDirection: "column", width: "55%", paddingLeft: 2, children: [
          /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Text, { bold: true, color: theme.text.primary, children: "Editor Preference" }),
          /* @__PURE__ */ (0, import_jsx_runtime85.jsxs)(Box_default, { flexDirection: "column", gap: 1, marginTop: 1, children: [
            /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(Text, { color: theme.text.secondary, children: "These editors are currently supported. Please note that some editors cannot be used in sandbox mode." }),
            /* @__PURE__ */ (0, import_jsx_runtime85.jsxs)(Text, { color: theme.text.secondary, children: [
              "Your preferred editor is:",
              " ",
              /* @__PURE__ */ (0, import_jsx_runtime85.jsx)(
                Text,
                {
                  color: mergedEditorName === "None" ? theme.status.error : theme.text.link,
                  bold: true,
                  children: mergedEditorName
                }
              ),
              "."
            ] })
          ] })
        ] })
      ]
    }
  );
}

// packages/cli/src/ui/privacy/GeminiPrivacyNotice.tsx
var import_jsx_runtime86 = __toESM(require_jsx_runtime(), 1);
var GeminiPrivacyNotice = ({ onExit }) => {
  useKeypress(
    (key) => {
      if (key.name === "escape") {
        onExit();
        return true;
      }
      return false;
    },
    { isActive: true }
  );
  return /* @__PURE__ */ (0, import_jsx_runtime86.jsxs)(Box_default, { flexDirection: "column", marginBottom: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(Text, { bold: true, color: theme.text.accent, children: "Gemini API Key Notice" }),
    /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(Newline, {}),
    /* @__PURE__ */ (0, import_jsx_runtime86.jsxs)(Text, { color: theme.text.primary, children: [
      "By using the Gemini API",
      /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(Text, { color: theme.text.link, children: "[1]" }),
      ", Google AI Studio",
      /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(Text, { color: theme.status.error, children: "[2]" }),
      ', and the other Google developer services that reference these terms (collectively, the "APIs" or "Services"), you are agreeing to Google APIs Terms of Service (the "API Terms")',
      /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(Text, { color: theme.status.success, children: "[3]" }),
      ', and the Gemini API Additional Terms of Service (the "Additional Terms")',
      /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(Text, { color: theme.text.accent, children: "[4]" }),
      "."
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(Newline, {}),
    /* @__PURE__ */ (0, import_jsx_runtime86.jsxs)(Text, { color: theme.text.primary, children: [
      /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(Text, { color: theme.text.link, children: "[1]" }),
      " ",
      "https://ai.google.dev/docs/gemini_api_overview"
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime86.jsxs)(Text, { color: theme.text.primary, children: [
      /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(Text, { color: theme.status.error, children: "[2]" }),
      " https://aistudio.google.com/"
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime86.jsxs)(Text, { color: theme.text.primary, children: [
      /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(Text, { color: theme.status.success, children: "[3]" }),
      " ",
      "https://developers.google.com/terms"
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime86.jsxs)(Text, { color: theme.text.primary, children: [
      /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(Text, { color: theme.text.accent, children: "[4]" }),
      " ",
      "https://ai.google.dev/gemini-api/terms"
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(Newline, {}),
    /* @__PURE__ */ (0, import_jsx_runtime86.jsx)(Text, { color: theme.text.secondary, children: "Press Esc to exit." })
  ] });
};

// packages/cli/src/ui/privacy/CloudPaidPrivacyNotice.tsx
var import_jsx_runtime87 = __toESM(require_jsx_runtime(), 1);
var CloudPaidPrivacyNotice = ({
  onExit
}) => {
  useKeypress(
    (key) => {
      if (key.name === "escape") {
        onExit();
        return true;
      }
      return false;
    },
    { isActive: true }
  );
  return /* @__PURE__ */ (0, import_jsx_runtime87.jsxs)(Box_default, { flexDirection: "column", marginBottom: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime87.jsx)(Text, { bold: true, color: theme.text.accent, children: "Vertex AI Notice" }),
    /* @__PURE__ */ (0, import_jsx_runtime87.jsx)(Newline, {}),
    /* @__PURE__ */ (0, import_jsx_runtime87.jsxs)(Text, { color: theme.text.primary, children: [
      "Service Specific Terms",
      /* @__PURE__ */ (0, import_jsx_runtime87.jsx)(Text, { color: theme.text.link, children: "[1]" }),
      " are incorporated into the agreement under which Google has agreed to provide Google Cloud Platform",
      /* @__PURE__ */ (0, import_jsx_runtime87.jsx)(Text, { color: theme.status.success, children: "[2]" }),
      " to Customer (the \u201CAgreement\u201D). If the Agreement authorizes the resale or supply of Google Cloud Platform under a Google Cloud partner or reseller program, then except for in the section entitled \u201CPartner-Specific Terms\u201D, all references to Customer in the Service Specific Terms mean Partner or Reseller (as applicable), and all references to Customer Data in the Service Specific Terms mean Partner Data. Capitalized terms used but not defined in the Service Specific Terms have the meaning given to them in the Agreement."
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime87.jsx)(Newline, {}),
    /* @__PURE__ */ (0, import_jsx_runtime87.jsxs)(Text, { color: theme.text.primary, children: [
      /* @__PURE__ */ (0, import_jsx_runtime87.jsx)(Text, { color: theme.text.link, children: "[1]" }),
      " ",
      "https://cloud.google.com/terms/service-terms"
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime87.jsxs)(Text, { color: theme.text.primary, children: [
      /* @__PURE__ */ (0, import_jsx_runtime87.jsx)(Text, { color: theme.status.success, children: "[2]" }),
      " ",
      "https://cloud.google.com/terms/services"
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime87.jsx)(Newline, {}),
    /* @__PURE__ */ (0, import_jsx_runtime87.jsx)(Text, { color: theme.text.secondary, children: "Press Esc to exit." })
  ] });
};

// packages/cli/src/ui/hooks/usePrivacySettings.ts
var import_react64 = __toESM(require_react(), 1);
var usePrivacySettings = (config) => {
  const [privacyState, setPrivacyState] = (0, import_react64.useState)({
    isLoading: true
  });
  (0, import_react64.useEffect)(() => {
    const fetchInitialState = async () => {
      setPrivacyState({
        isLoading: true
      });
      try {
        const server = getCodeAssistServerOrFail(config);
        const tier = server.userTier;
        if (tier === void 0) {
          throw new Error("Could not determine user tier.");
        }
        if (tier !== UserTierId.FREE) {
          setPrivacyState({
            isLoading: false,
            isFreeTier: false
          });
          return;
        }
        const optIn = await getRemoteDataCollectionOptIn(server);
        setPrivacyState({
          isLoading: false,
          isFreeTier: true,
          dataCollectionOptIn: optIn
        });
      } catch (e) {
        setPrivacyState({
          isLoading: false,
          error: e instanceof Error ? e.message : String(e)
        });
      }
    };
    fetchInitialState();
  }, [config]);
  const updateDataCollectionOptIn = (0, import_react64.useCallback)(
    async (optIn) => {
      try {
        const server = getCodeAssistServerOrFail(config);
        const updatedOptIn = await setRemoteDataCollectionOptIn(server, optIn);
        setPrivacyState({
          isLoading: false,
          isFreeTier: true,
          dataCollectionOptIn: updatedOptIn
        });
      } catch (e) {
        setPrivacyState({
          isLoading: false,
          error: e instanceof Error ? e.message : String(e)
        });
      }
    },
    [config]
  );
  return {
    privacyState,
    updateDataCollectionOptIn
  };
};
function getCodeAssistServerOrFail(config) {
  const server = getCodeAssistServer(config);
  if (server === void 0) {
    throw new Error("Oauth not being used");
  } else if (server.projectId === void 0) {
    throw new Error("CodeAssist server is missing a project ID");
  }
  return server;
}
async function getRemoteDataCollectionOptIn(server) {
  try {
    const resp = await server.getCodeAssistGlobalUserSetting();
    if (resp.freeTierDataCollectionOptin === void 0) {
      debugLogger.warn(
        "Warning: Code Assist API did not return freeTierDataCollectionOptin. Defaulting to true."
      );
    }
    return resp.freeTierDataCollectionOptin ?? true;
  } catch (error) {
    if (error && typeof error === "object" && "response" in error) {
      const gaxiosError = error;
      if (gaxiosError.response?.status === 404) {
        return true;
      }
    }
    throw error;
  }
}
async function setRemoteDataCollectionOptIn(server, optIn) {
  const resp = await server.setCodeAssistGlobalUserSetting({
    cloudaicompanionProject: server.projectId,
    freeTierDataCollectionOptin: optIn
  });
  if (resp.freeTierDataCollectionOptin === void 0) {
    debugLogger.warn(
      `Warning: Code Assist API did not return freeTierDataCollectionOptin. Defaulting to ${optIn}.`
    );
  }
  return resp.freeTierDataCollectionOptin ?? optIn;
}

// packages/cli/src/ui/privacy/CloudFreePrivacyNotice.tsx
var import_jsx_runtime88 = __toESM(require_jsx_runtime(), 1);
var CloudFreePrivacyNotice = ({
  config,
  onExit
}) => {
  const { privacyState, updateDataCollectionOptIn } = usePrivacySettings(config);
  useKeypress(
    (key) => {
      if ((privacyState.error || privacyState.isFreeTier === false) && key.name === "escape") {
        onExit();
        return true;
      }
      return false;
    },
    { isActive: true }
  );
  if (privacyState.isLoading) {
    return /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Text, { color: theme.text.secondary, children: "Loading..." });
  }
  if (privacyState.error) {
    return /* @__PURE__ */ (0, import_jsx_runtime88.jsxs)(Box_default, { flexDirection: "column", marginY: 1, children: [
      /* @__PURE__ */ (0, import_jsx_runtime88.jsxs)(Text, { color: theme.status.error, children: [
        "Error loading Opt-in settings: ",
        privacyState.error
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Text, { color: theme.text.secondary, children: "Press Esc to exit." })
    ] });
  }
  if (privacyState.isFreeTier === false) {
    return /* @__PURE__ */ (0, import_jsx_runtime88.jsxs)(Box_default, { flexDirection: "column", marginY: 1, children: [
      /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Text, { bold: true, color: theme.text.accent, children: "Gemini Code Assist Privacy Notice" }),
      /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Newline, {}),
      /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Text, { children: "https://developers.google.com/gemini-code-assist/resources/privacy-notices" }),
      /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Newline, {}),
      /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Text, { color: theme.text.secondary, children: "Press Esc to exit." })
    ] });
  }
  const items = [
    { label: "Yes", value: true, key: "true" },
    { label: "No", value: false, key: "false" }
  ];
  return /* @__PURE__ */ (0, import_jsx_runtime88.jsxs)(Box_default, { flexDirection: "column", marginY: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Text, { bold: true, color: theme.text.accent, children: "Gemini Code Assist for Individuals Privacy Notice" }),
    /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Newline, {}),
    /* @__PURE__ */ (0, import_jsx_runtime88.jsxs)(Text, { color: theme.text.primary, children: [
      "This notice and our Privacy Policy",
      /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Text, { color: theme.text.link, children: "[1]" }),
      " describe how Gemini Code Assist handles your data. Please read them carefully."
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Newline, {}),
    /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Text, { color: theme.text.primary, children: "When you use Gemini Code Assist for individuals with Gemini CLI, Google collects your prompts, related code, generated output, code edits, related feature usage information, and your feedback to provide, improve, and develop Google products and services and machine learning technologies." }),
    /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Newline, {}),
    /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Text, { color: theme.text.primary, children: "To help with quality and improve our products (such as generative machine-learning models), human reviewers may read, annotate, and process the data collected above. We take steps to protect your privacy as part of this process. This includes disconnecting the data from your Google Account before reviewers see or annotate it, and storing those disconnected copies for up to 18 months. Please don't submit confidential information or any data you wouldn't want a reviewer to see or Google to use to improve our products, services and machine-learning technologies." }),
    /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Newline, {}),
    /* @__PURE__ */ (0, import_jsx_runtime88.jsxs)(Box_default, { flexDirection: "column", children: [
      /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Text, { color: theme.text.primary, children: "Allow Google to use this data to develop and improve our products?" }),
      /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(
        RadioButtonSelect,
        {
          items,
          initialIndex: privacyState.dataCollectionOptIn ? 0 : 1,
          onSelect: (value) => {
            updateDataCollectionOptIn(value);
            if (!privacyState.error) {
              onExit();
            }
          }
        }
      )
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Newline, {}),
    /* @__PURE__ */ (0, import_jsx_runtime88.jsxs)(Text, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Text, { color: theme.text.link, children: "[1]" }),
      " ",
      "https://policies.google.com/privacy"
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Newline, {}),
    /* @__PURE__ */ (0, import_jsx_runtime88.jsx)(Text, { color: theme.text.secondary, children: "Press Enter to choose an option and exit." })
  ] });
};

// packages/cli/src/ui/privacy/PrivacyNotice.tsx
var import_jsx_runtime89 = __toESM(require_jsx_runtime(), 1);
var PrivacyNoticeText = ({
  config,
  onExit
}) => {
  const authType = config.getContentGeneratorConfig()?.authType;
  switch (authType) {
    case AuthType.USE_GEMINI:
      return /* @__PURE__ */ (0, import_jsx_runtime89.jsx)(GeminiPrivacyNotice, { onExit });
    case AuthType.USE_VERTEX_AI:
      return /* @__PURE__ */ (0, import_jsx_runtime89.jsx)(CloudPaidPrivacyNotice, { onExit });
    case AuthType.LOGIN_WITH_GOOGLE:
    default:
      return /* @__PURE__ */ (0, import_jsx_runtime89.jsx)(CloudFreePrivacyNotice, { config, onExit });
  }
};
var PrivacyNotice = ({ onExit, config }) => /* @__PURE__ */ (0, import_jsx_runtime89.jsx)(Box_default, { borderStyle: "round", padding: 1, flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime89.jsx)(PrivacyNoticeText, { config, onExit }) });

// packages/cli/src/ui/components/ProQuotaDialog.tsx
var import_jsx_runtime90 = __toESM(require_jsx_runtime(), 1);
function ProQuotaDialog({
  failedModel,
  fallbackModel,
  message,
  isTerminalQuotaError,
  isModelNotFoundError,
  authType,
  tierName,
  onChoice
}) {
  let items;
  if (failedModel === fallbackModel) {
    items = [
      {
        label: "Keep trying",
        value: "retry_once",
        key: "retry_once"
      },
      {
        label: "Stop",
        value: "retry_later",
        key: "retry_later"
      }
    ];
  } else if (isModelNotFoundError || isTerminalQuotaError) {
    const isUltra = isUltraTier(tierName);
    items = [
      {
        label: `Switch to ${fallbackModel}`,
        value: "retry_always",
        key: "retry_always"
      },
      ...authType === AuthType.LOGIN_WITH_GOOGLE && !isUltra ? [
        {
          label: "Upgrade for higher limits",
          value: "upgrade",
          key: "upgrade"
        }
      ] : [],
      {
        label: `Stop`,
        value: "retry_later",
        key: "retry_later"
      }
    ];
  } else {
    items = [
      {
        label: "Keep trying",
        value: "retry_once",
        key: "retry_once"
      },
      {
        label: `Switch to ${fallbackModel}`,
        value: "retry_always",
        key: "retry_always"
      },
      {
        label: "Stop",
        value: "retry_later",
        key: "retry_later"
      }
    ];
  }
  const handleSelect = (choice) => {
    onChoice(choice);
  };
  const renderMessage = (msg) => {
    const parts = msg.split(/(\s+)/);
    return /* @__PURE__ */ (0, import_jsx_runtime90.jsx)(Text, { children: parts.map((part, index) => {
      if (part.startsWith("/")) {
        return /* @__PURE__ */ (0, import_jsx_runtime90.jsx)(Text, { bold: true, color: theme.text.accent, children: part }, index);
      }
      return /* @__PURE__ */ (0, import_jsx_runtime90.jsx)(Text, { children: part }, index);
    }) });
  };
  return /* @__PURE__ */ (0, import_jsx_runtime90.jsxs)(Box_default, { borderStyle: "round", flexDirection: "column", padding: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime90.jsx)(Box_default, { marginBottom: 1, children: renderMessage(message) }),
    /* @__PURE__ */ (0, import_jsx_runtime90.jsx)(Box_default, { marginTop: 1, marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime90.jsx)(RadioButtonSelect, { items, onSelect: handleSelect }) })
  ] });
}

// packages/cli/src/ui/components/ValidationDialog.tsx
var import_react65 = __toESM(require_react(), 1);
var import_jsx_runtime91 = __toESM(require_jsx_runtime(), 1);
function ValidationDialog({
  validationLink,
  learnMoreUrl,
  onChoice
}) {
  const keyMatchers = useKeyMatchers();
  const [state, setState] = (0, import_react65.useState)("choosing");
  const [errorMessage, setErrorMessage] = (0, import_react65.useState)("");
  const items = [
    {
      label: "Verify your account",
      value: "verify",
      key: "verify"
    },
    {
      label: "Change authentication",
      value: "change_auth",
      key: "change_auth"
    }
  ];
  useKeypress(
    (key) => {
      if (keyMatchers["basic.cancel" /* ESCAPE */](key) || keyMatchers["basic.quit" /* QUIT */](key)) {
        onChoice("cancel");
        return true;
      } else if (state === "waiting" && keyMatchers["basic.confirm" /* RETURN */](key)) {
        setState("complete");
        return true;
      }
      return false;
    },
    { isActive: state !== "complete" }
  );
  (0, import_react65.useEffect)(() => {
    if (state === "complete") {
      const timer = setTimeout(() => {
        onChoice("verify");
      }, 500);
      return () => clearTimeout(timer);
    }
    return void 0;
  }, [state, onChoice]);
  const handleSelect = (0, import_react65.useCallback)(
    async (choice) => {
      if (choice === "verify") {
        if (validationLink) {
          if (!shouldLaunchBrowser()) {
            setErrorMessage(
              `Please open this URL in a browser: ${validationLink}`
            );
            setState("waiting");
            return;
          }
          try {
            await openBrowserSecurely(validationLink);
            setState("waiting");
          } catch (error) {
            setErrorMessage(
              error instanceof Error ? error.message : "Failed to open browser"
            );
            setState("error");
          }
        } else {
          onChoice("verify");
        }
      } else {
        onChoice(choice);
      }
    },
    [validationLink, onChoice]
  );
  if (state === "error") {
    return /* @__PURE__ */ (0, import_jsx_runtime91.jsxs)(Box_default, { borderStyle: "round", flexDirection: "column", padding: 1, children: [
      /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(Text, { color: theme.status.error, children: errorMessage || "Failed to open verification link. Please try again or change authentication." }),
      /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(
        RadioButtonSelect,
        {
          items,
          onSelect: (choice) => void handleSelect(choice)
        }
      ) })
    ] });
  }
  if (state === "waiting") {
    return /* @__PURE__ */ (0, import_jsx_runtime91.jsxs)(Box_default, { borderStyle: "round", flexDirection: "column", padding: 1, children: [
      /* @__PURE__ */ (0, import_jsx_runtime91.jsxs)(Box_default, { children: [
        /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(CliSpinner, {}),
        /* @__PURE__ */ (0, import_jsx_runtime91.jsxs)(Text, { children: [
          " ",
          "Waiting for verification... (Press Esc or Ctrl+C to cancel)"
        ] })
      ] }),
      errorMessage && /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(Text, { children: errorMessage }) }),
      /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(Text, { dimColor: true, children: "Press Enter when verification is complete." }) })
    ] });
  }
  if (state === "complete") {
    return /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(Box_default, { borderStyle: "round", flexDirection: "column", padding: 1, children: /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(Text, { color: theme.status.success, children: "Verification complete" }) });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime91.jsxs)(Box_default, { borderStyle: "round", flexDirection: "column", padding: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(Box_default, { marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(Text, { children: "Further action is required to use this service." }) }),
    /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(Box_default, { marginTop: 1, marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(
      RadioButtonSelect,
      {
        items,
        onSelect: (choice) => void handleSelect(choice)
      }
    ) }),
    learnMoreUrl && /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime91.jsxs)(Text, { dimColor: true, children: [
      "Learn more: ",
      /* @__PURE__ */ (0, import_jsx_runtime91.jsx)(Text, { color: theme.text.accent, children: learnMoreUrl })
    ] }) })
  ] });
}

// packages/cli/src/ui/components/OverageMenuDialog.tsx
var import_jsx_runtime92 = __toESM(require_jsx_runtime(), 1);
function OverageMenuDialog({
  failedModel,
  fallbackModel,
  resetTime,
  creditBalance,
  onChoice
}) {
  const items = [
    {
      label: "Use AI Credits - Continue this request (Overage)",
      value: "use_credits",
      key: "use_credits"
    },
    {
      label: "Manage - View balance and purchase more credits",
      value: "manage",
      key: "manage"
    }
  ];
  if (fallbackModel) {
    items.push({
      label: `Switch to ${fallbackModel}`,
      value: "use_fallback",
      key: "use_fallback"
    });
  }
  items.push({
    label: "Stop - Abort request",
    value: "stop",
    key: "stop"
  });
  return /* @__PURE__ */ (0, import_jsx_runtime92.jsxs)(Box_default, { borderStyle: "round", flexDirection: "column", padding: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime92.jsxs)(Box_default, { marginBottom: 1, flexDirection: "column", children: [
      /* @__PURE__ */ (0, import_jsx_runtime92.jsxs)(Text, { color: theme.status.warning, children: [
        "Usage limit reached for ",
        failedModel,
        "."
      ] }),
      resetTime && /* @__PURE__ */ (0, import_jsx_runtime92.jsxs)(Text, { children: [
        "Access resets at ",
        resetTime,
        "."
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime92.jsxs)(Text, { children: [
        /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(Text, { bold: true, color: theme.text.accent, children: "/stats" }),
        " ",
        "model for usage details"
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime92.jsxs)(Text, { children: [
        /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(Text, { bold: true, color: theme.text.accent, children: "/model" }),
        " ",
        "to switch models."
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime92.jsxs)(Text, { children: [
        /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(Text, { bold: true, color: theme.text.accent, children: "/auth" }),
        " ",
        "to switch to API key."
      ] })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(Box_default, { marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime92.jsxs)(Text, { children: [
      "You have",
      " ",
      /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(Text, { bold: true, color: theme.status.success, children: creditBalance }),
      " ",
      "AI Credits available."
    ] }) }),
    /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(Box_default, { marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(Text, { children: "How would you like to proceed?" }) }),
    /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(Box_default, { marginTop: 1, marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime92.jsx)(RadioButtonSelect, { items, onSelect: onChoice }) })
  ] });
}

// packages/cli/src/ui/components/EmptyWalletDialog.tsx
var import_jsx_runtime93 = __toESM(require_jsx_runtime(), 1);
function EmptyWalletDialog({
  failedModel,
  fallbackModel,
  resetTime,
  onGetCredits,
  onChoice
}) {
  const items = [
    {
      label: "Get AI Credits - Open browser to purchase credits",
      value: "get_credits",
      key: "get_credits"
    }
  ];
  if (fallbackModel) {
    items.push({
      label: `Switch to ${fallbackModel}`,
      value: "use_fallback",
      key: "use_fallback"
    });
  }
  items.push({
    label: "Stop - Abort request",
    value: "stop",
    key: "stop"
  });
  const handleSelect = (choice) => {
    if (choice === "get_credits") {
      onGetCredits?.();
    }
    onChoice(choice);
  };
  return /* @__PURE__ */ (0, import_jsx_runtime93.jsxs)(Box_default, { borderStyle: "round", flexDirection: "column", padding: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime93.jsxs)(Box_default, { marginBottom: 1, flexDirection: "column", children: [
      /* @__PURE__ */ (0, import_jsx_runtime93.jsxs)(Text, { color: theme.status.warning, children: [
        "Usage limit reached for ",
        failedModel,
        "."
      ] }),
      resetTime && /* @__PURE__ */ (0, import_jsx_runtime93.jsxs)(Text, { children: [
        "Access resets at ",
        resetTime,
        "."
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime93.jsxs)(Text, { children: [
        /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(Text, { bold: true, color: theme.text.accent, children: "/stats" }),
        " ",
        "model for usage details"
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime93.jsxs)(Text, { children: [
        /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(Text, { bold: true, color: theme.text.accent, children: "/model" }),
        " ",
        "to switch models."
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime93.jsxs)(Text, { children: [
        /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(Text, { bold: true, color: theme.text.accent, children: "/auth" }),
        " ",
        "to switch to API key."
      ] })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(Box_default, { marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(Text, { children: "To continue using this model now, purchase more AI Credits." }) }),
    /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(Box_default, { marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(Text, { dimColor: true, children: "Newly purchased AI credits may take a few minutes to update." }) }),
    /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(Box_default, { marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(Text, { children: "How would you like to proceed?" }) }),
    /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(Box_default, { marginTop: 1, marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime93.jsx)(RadioButtonSelect, { items, onSelect: handleSelect }) })
  ] });
}

// packages/cli/src/ui/components/SessionBrowser.tsx
var import_react66 = __toESM(require_react(), 1);

// packages/cli/src/ui/colors.ts
var Colors = {
  get type() {
    return themeManager.getActiveTheme().colors.type;
  },
  get Foreground() {
    return themeManager.getActiveTheme().colors.Foreground;
  },
  get Background() {
    return themeManager.getColors().Background;
  },
  get LightBlue() {
    return themeManager.getActiveTheme().colors.LightBlue;
  },
  get AccentBlue() {
    return themeManager.getActiveTheme().colors.AccentBlue;
  },
  get AccentPurple() {
    return themeManager.getActiveTheme().colors.AccentPurple;
  },
  get AccentCyan() {
    return themeManager.getActiveTheme().colors.AccentCyan;
  },
  get AccentGreen() {
    return themeManager.getActiveTheme().colors.AccentGreen;
  },
  get AccentYellow() {
    return themeManager.getActiveTheme().colors.AccentYellow;
  },
  get AccentRed() {
    return themeManager.getActiveTheme().colors.AccentRed;
  },
  get DiffAdded() {
    return themeManager.getActiveTheme().colors.DiffAdded;
  },
  get DiffRemoved() {
    return themeManager.getActiveTheme().colors.DiffRemoved;
  },
  get Comment() {
    return themeManager.getActiveTheme().colors.Comment;
  },
  get Gray() {
    return themeManager.getActiveTheme().colors.Gray;
  },
  get DarkGray() {
    return themeManager.getColors().DarkGray;
  },
  get InputBackground() {
    return themeManager.getColors().InputBackground;
  },
  get MessageBackground() {
    return themeManager.getColors().MessageBackground;
  },
  get GradientColors() {
    return themeManager.getActiveTheme().colors.GradientColors;
  }
};

// packages/cli/src/ui/components/SessionBrowser.tsx
import path6 from "node:path";

// packages/cli/src/ui/components/SessionBrowser/SessionBrowserNav.tsx
var import_jsx_runtime94 = __toESM(require_jsx_runtime(), 1);
var Kbd = ({ name, shortcut }) => /* @__PURE__ */ (0, import_jsx_runtime94.jsxs)(import_jsx_runtime94.Fragment, { children: [
  name,
  ": ",
  /* @__PURE__ */ (0, import_jsx_runtime94.jsx)(Text, { bold: true, children: shortcut })
] });
var NavigationHelpDisplay = () => /* @__PURE__ */ (0, import_jsx_runtime94.jsxs)(Box_default, { flexDirection: "column", children: [
  /* @__PURE__ */ (0, import_jsx_runtime94.jsxs)(Text, { color: Colors.Gray, children: [
    /* @__PURE__ */ (0, import_jsx_runtime94.jsx)(Kbd, { name: "Navigate", shortcut: "\u2191/\u2193" }),
    "   ",
    /* @__PURE__ */ (0, import_jsx_runtime94.jsx)(Kbd, { name: "Resume", shortcut: "Enter" }),
    "   ",
    /* @__PURE__ */ (0, import_jsx_runtime94.jsx)(Kbd, { name: "Search", shortcut: "/" }),
    "   ",
    /* @__PURE__ */ (0, import_jsx_runtime94.jsx)(Kbd, { name: "Delete", shortcut: "x" }),
    "   ",
    /* @__PURE__ */ (0, import_jsx_runtime94.jsx)(Kbd, { name: "Quit", shortcut: "q" })
  ] }),
  /* @__PURE__ */ (0, import_jsx_runtime94.jsxs)(Text, { color: Colors.Gray, children: [
    /* @__PURE__ */ (0, import_jsx_runtime94.jsx)(Kbd, { name: "Sort", shortcut: "s" }),
    "         ",
    /* @__PURE__ */ (0, import_jsx_runtime94.jsx)(Kbd, { name: "Reverse", shortcut: "r" }),
    "      ",
    /* @__PURE__ */ (0, import_jsx_runtime94.jsx)(Kbd, { name: "First/Last", shortcut: "g/G" })
  ] })
] });
var SearchModeDisplay = ({
  state
}) => /* @__PURE__ */ (0, import_jsx_runtime94.jsxs)(Box_default, { marginTop: 1, children: [
  /* @__PURE__ */ (0, import_jsx_runtime94.jsx)(Text, { color: Colors.Gray, children: "Search: " }),
  /* @__PURE__ */ (0, import_jsx_runtime94.jsx)(Text, { color: Colors.AccentPurple, children: state.searchQuery }),
  /* @__PURE__ */ (0, import_jsx_runtime94.jsx)(Text, { color: Colors.Gray, children: " (Esc to cancel)" })
] });
var NoResultsDisplay = ({
  state
}) => /* @__PURE__ */ (0, import_jsx_runtime94.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime94.jsxs)(Text, { color: Colors.Gray, dimColor: true, children: [
  "No sessions found matching '",
  state.searchQuery,
  "'."
] }) });

// packages/cli/src/ui/components/SessionBrowser/SessionListHeader.tsx
var import_jsx_runtime95 = __toESM(require_jsx_runtime(), 1);
var SessionListHeader = ({
  state
}) => /* @__PURE__ */ (0, import_jsx_runtime95.jsxs)(Box_default, { flexDirection: "row", justifyContent: "space-between", children: [
  /* @__PURE__ */ (0, import_jsx_runtime95.jsxs)(Text, { color: Colors.AccentPurple, children: [
    "Chat Sessions (",
    state.totalSessions,
    " total",
    state.searchQuery ? `, filtered` : "",
    ")"
  ] }),
  /* @__PURE__ */ (0, import_jsx_runtime95.jsxs)(Text, { color: Colors.Gray, children: [
    "sorted by ",
    state.sortOrder,
    " ",
    state.sortReverse ? "asc" : "desc"
  ] })
] });

// packages/cli/src/ui/components/SessionBrowser/SessionBrowserLoading.tsx
var import_jsx_runtime96 = __toESM(require_jsx_runtime(), 1);
var SessionBrowserLoading = () => /* @__PURE__ */ (0, import_jsx_runtime96.jsx)(Box_default, { flexDirection: "column", paddingX: 1, children: /* @__PURE__ */ (0, import_jsx_runtime96.jsx)(Text, { color: Colors.Gray, children: "Loading sessions\u2026" }) });

// packages/cli/src/ui/components/SessionBrowser/SessionBrowserError.tsx
var import_jsx_runtime97 = __toESM(require_jsx_runtime(), 1);
var SessionBrowserError = ({
  state
}) => /* @__PURE__ */ (0, import_jsx_runtime97.jsxs)(Box_default, { flexDirection: "column", paddingX: 1, children: [
  /* @__PURE__ */ (0, import_jsx_runtime97.jsxs)(Text, { color: Colors.AccentRed, children: [
    "Error: ",
    state.error
  ] }),
  /* @__PURE__ */ (0, import_jsx_runtime97.jsx)(Text, { color: Colors.Gray, children: "Press q to exit" })
] });

// packages/cli/src/ui/components/SessionBrowser/SessionBrowserEmpty.tsx
var import_jsx_runtime98 = __toESM(require_jsx_runtime(), 1);
var SessionBrowserEmpty = () => /* @__PURE__ */ (0, import_jsx_runtime98.jsxs)(Box_default, { flexDirection: "column", paddingX: 1, children: [
  /* @__PURE__ */ (0, import_jsx_runtime98.jsx)(Text, { color: Colors.Gray, children: "No auto-saved conversations found." }),
  /* @__PURE__ */ (0, import_jsx_runtime98.jsx)(Text, { color: Colors.Gray, children: "Press q to exit" })
] });

// packages/cli/src/ui/components/SessionBrowser/utils.ts
var sortSessions = (sessions, sortBy, reverse) => {
  const sorted = [...sessions].sort((a, b) => {
    switch (sortBy) {
      case "date":
        return new Date(b.lastUpdated).getTime() - new Date(a.lastUpdated).getTime();
      case "messages":
        return b.messageCount - a.messageCount;
      case "name":
        return a.displayName.localeCompare(b.displayName);
      default:
        return 0;
    }
  });
  return reverse ? sorted.reverse() : sorted;
};
var findTextMatches = (messages, query) => {
  if (!query.trim()) return [];
  const lowerQuery = query.toLowerCase();
  const matches = [];
  for (const message of messages) {
    const m = cleanMessage(message.content);
    const lowerContent = m.toLowerCase();
    let startIndex = 0;
    while (true) {
      const matchIndex = lowerContent.indexOf(lowerQuery, startIndex);
      if (matchIndex === -1) break;
      const contextStart = Math.max(0, matchIndex - 10);
      const contextEnd = Math.min(m.length, matchIndex + query.length + 10);
      const snippet = m.slice(contextStart, contextEnd);
      const relativeMatchStart = matchIndex - contextStart;
      const relativeMatchEnd = relativeMatchStart + query.length;
      let before = snippet.slice(0, relativeMatchStart);
      const match = snippet.slice(relativeMatchStart, relativeMatchEnd);
      let after = snippet.slice(relativeMatchEnd);
      if (contextStart > 0) before = "\u2026" + before;
      if (contextEnd < m.length) after = after + "\u2026";
      matches.push({ before, match, after, role: message.role });
      startIndex = matchIndex + 1;
    }
  }
  return matches;
};
var filterSessions = (sessions, query) => {
  if (!query.trim()) {
    return sessions.map((session) => ({
      ...session,
      matchSnippets: void 0,
      matchCount: void 0
    }));
  }
  const lowerQuery = query.toLowerCase();
  return sessions.filter((session) => {
    const titleMatch = session.displayName.toLowerCase().includes(lowerQuery) || session.id.toLowerCase().includes(lowerQuery) || session.firstUserMessage.toLowerCase().includes(lowerQuery);
    const contentMatch = session.fullContent?.toLowerCase().includes(lowerQuery);
    if (titleMatch || contentMatch) {
      if (session.messages) {
        session.matchSnippets = findTextMatches(session.messages, query);
        session.matchCount = session.matchSnippets.length;
      }
      return true;
    }
    return false;
  });
};

// packages/cli/src/ui/components/SessionBrowser.tsx
var import_jsx_runtime99 = __toESM(require_jsx_runtime(), 1);
var SESSIONS_PER_PAGE = 20;
var FIXED_SESSION_COLUMNS_WIDTH = 30;
var SessionTableHeader = ({
  state
}) => /* @__PURE__ */ (0, import_jsx_runtime99.jsxs)(Box_default, { flexDirection: "row", marginTop: 1, children: [
  /* @__PURE__ */ (0, import_jsx_runtime99.jsx)(Text, { children: state.scrollOffset > 0 ? /* @__PURE__ */ (0, import_jsx_runtime99.jsx)(Text, { children: "\u25B2 " }) : "  " }),
  /* @__PURE__ */ (0, import_jsx_runtime99.jsx)(Box_default, { width: 5, flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime99.jsx)(Text, { color: Colors.Gray, bold: true, children: "Index" }) }),
  /* @__PURE__ */ (0, import_jsx_runtime99.jsx)(Text, { color: Colors.Gray, children: " \u2502 " }),
  /* @__PURE__ */ (0, import_jsx_runtime99.jsx)(Box_default, { width: 4, flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime99.jsx)(Text, { color: Colors.Gray, bold: true, children: "Msgs" }) }),
  /* @__PURE__ */ (0, import_jsx_runtime99.jsx)(Text, { color: Colors.Gray, children: " \u2502 " }),
  /* @__PURE__ */ (0, import_jsx_runtime99.jsx)(Box_default, { width: 4, flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime99.jsx)(Text, { color: Colors.Gray, bold: true, children: "Age" }) }),
  /* @__PURE__ */ (0, import_jsx_runtime99.jsx)(Text, { color: Colors.Gray, children: " \u2502 " }),
  /* @__PURE__ */ (0, import_jsx_runtime99.jsx)(Box_default, { flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime99.jsx)(Text, { color: Colors.Gray, bold: true, children: state.searchQuery ? "Match" : "Name" }) })
] });
var MatchSnippetDisplay = ({
  session,
  textColor
}) => {
  if (!session.matchSnippets || session.matchSnippets.length === 0) {
    return null;
  }
  const firstMatch = session.matchSnippets[0];
  const rolePrefix = firstMatch.role === "user" ? "You:   " : "Gemini:";
  const roleColor = textColor(
    firstMatch.role === "user" ? Colors.AccentGreen : Colors.AccentBlue
  );
  return /* @__PURE__ */ (0, import_jsx_runtime99.jsxs)(import_jsx_runtime99.Fragment, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime99.jsxs)(Text, { color: roleColor, bold: true, children: [
      rolePrefix,
      " "
    ] }),
    firstMatch.before,
    /* @__PURE__ */ (0, import_jsx_runtime99.jsx)(Text, { color: textColor(Colors.AccentRed), bold: true, children: firstMatch.match }),
    firstMatch.after
  ] });
};
var SessionItem = ({
  session,
  state,
  terminalWidth,
  formatRelativeTime: formatRelativeTime2
}) => {
  const originalIndex = state.startIndex + state.visibleSessions.indexOf(session);
  const isActive = originalIndex === state.activeIndex;
  const isDisabled = session.isCurrentSession;
  const textColor = (c2 = Colors.Foreground) => {
    if (isDisabled) {
      return Colors.Gray;
    }
    return isActive ? theme.ui.focus : c2;
  };
  const prefix = isActive ? "\u276F " : "  ";
  let additionalInfo = "";
  let matchDisplay = null;
  if (session.isCurrentSession) {
    additionalInfo = " (current)";
  }
  if (state.searchQuery && session.matchSnippets && session.matchSnippets.length > 0) {
    matchDisplay = /* @__PURE__ */ (0, import_jsx_runtime99.jsx)(MatchSnippetDisplay, { session, textColor });
    if (session.matchCount && session.matchCount > 1) {
      additionalInfo += ` (+${session.matchCount - 1} more)`;
    }
  }
  const reservedForMeta = additionalInfo ? additionalInfo.length + 1 : 0;
  const availableMessageWidth = Math.max(
    20,
    terminalWidth - FIXED_SESSION_COLUMNS_WIDTH - reservedForMeta
  );
  const truncatedMessage = matchDisplay || (session.displayName.length === 0 ? /* @__PURE__ */ (0, import_jsx_runtime99.jsx)(Text, { color: textColor(Colors.Gray), dimColor: true, children: "(No messages)" }) : session.displayName.length > availableMessageWidth ? session.displayName.slice(0, availableMessageWidth - 1) + "\u2026" : session.displayName);
  return /* @__PURE__ */ (0, import_jsx_runtime99.jsxs)(
    Box_default,
    {
      flexDirection: "row",
      backgroundColor: isActive ? theme.background.focus : void 0,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime99.jsx)(Text, { color: textColor(), dimColor: isDisabled, children: prefix }),
        /* @__PURE__ */ (0, import_jsx_runtime99.jsx)(Box_default, { width: 5, children: /* @__PURE__ */ (0, import_jsx_runtime99.jsxs)(Text, { color: textColor(), dimColor: isDisabled, children: [
          "#",
          originalIndex + 1
        ] }) }),
        /* @__PURE__ */ (0, import_jsx_runtime99.jsxs)(Text, { color: textColor(Colors.Gray), dimColor: isDisabled, children: [
          " ",
          "\u2502",
          " "
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime99.jsx)(Box_default, { width: 4, children: /* @__PURE__ */ (0, import_jsx_runtime99.jsx)(Text, { color: textColor(), dimColor: isDisabled, children: session.messageCount }) }),
        /* @__PURE__ */ (0, import_jsx_runtime99.jsxs)(Text, { color: textColor(Colors.Gray), dimColor: isDisabled, children: [
          " ",
          "\u2502",
          " "
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime99.jsx)(Box_default, { width: 4, children: /* @__PURE__ */ (0, import_jsx_runtime99.jsx)(Text, { color: textColor(), dimColor: isDisabled, children: formatRelativeTime2(session.lastUpdated, "short") }) }),
        /* @__PURE__ */ (0, import_jsx_runtime99.jsxs)(Text, { color: textColor(Colors.Gray), dimColor: isDisabled, children: [
          " ",
          "\u2502",
          " "
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime99.jsx)(Box_default, { flexGrow: 1, children: /* @__PURE__ */ (0, import_jsx_runtime99.jsxs)(Text, { color: textColor(Colors.Comment), dimColor: isDisabled, children: [
          truncatedMessage,
          additionalInfo && /* @__PURE__ */ (0, import_jsx_runtime99.jsx)(Text, { color: textColor(Colors.Gray), dimColor: true, bold: false, children: additionalInfo })
        ] }) })
      ]
    }
  );
};
var SessionList = ({
  state,
  formatRelativeTime: formatRelativeTime2
}) => /* @__PURE__ */ (0, import_jsx_runtime99.jsxs)(Box_default, { flexDirection: "column", children: [
  /* @__PURE__ */ (0, import_jsx_runtime99.jsxs)(Box_default, { flexDirection: "column", children: [
    !state.isSearchMode && /* @__PURE__ */ (0, import_jsx_runtime99.jsx)(NavigationHelpDisplay, {}),
    /* @__PURE__ */ (0, import_jsx_runtime99.jsx)(SessionTableHeader, { state })
  ] }),
  state.visibleSessions.map((session) => /* @__PURE__ */ (0, import_jsx_runtime99.jsx)(
    SessionItem,
    {
      session,
      state,
      terminalWidth: state.terminalWidth,
      formatRelativeTime: formatRelativeTime2
    },
    session.id
  )),
  /* @__PURE__ */ (0, import_jsx_runtime99.jsx)(Text, { color: Colors.Gray, children: state.endIndex < state.totalSessions ? /* @__PURE__ */ (0, import_jsx_runtime99.jsx)(import_jsx_runtime99.Fragment, { children: "\u25BC" }) : /* @__PURE__ */ (0, import_jsx_runtime99.jsx)(Text, { dimColor: true, children: "\u25BC" }) })
] });
var useSessionBrowserState = (initialSessions = [], initialLoading = true, initialError = null) => {
  const { columns: terminalWidth } = useTerminalSize();
  const [sessions, setSessions] = (0, import_react66.useState)(initialSessions);
  const [loading, setLoading] = (0, import_react66.useState)(initialLoading);
  const [error, setError] = (0, import_react66.useState)(initialError);
  const [activeIndex, setActiveIndex] = (0, import_react66.useState)(0);
  const [scrollOffset, setScrollOffset] = (0, import_react66.useState)(0);
  const [sortOrder, setSortOrder] = (0, import_react66.useState)(
    "date"
  );
  const [sortReverse, setSortReverse] = (0, import_react66.useState)(false);
  const [searchQuery, setSearchQuery] = (0, import_react66.useState)("");
  const [isSearchMode, setIsSearchMode] = (0, import_react66.useState)(false);
  const [hasLoadedFullContent, setHasLoadedFullContent] = (0, import_react66.useState)(false);
  const loadingFullContentRef = (0, import_react66.useRef)(false);
  const filteredAndSortedSessions = (0, import_react66.useMemo)(() => {
    const filtered = filterSessions(sessions, searchQuery);
    return sortSessions(filtered, sortOrder, sortReverse);
  }, [sessions, searchQuery, sortOrder, sortReverse]);
  (0, import_react66.useEffect)(() => {
    if (!searchQuery) {
      setHasLoadedFullContent(false);
      loadingFullContentRef.current = false;
    }
  }, [searchQuery]);
  const totalSessions = filteredAndSortedSessions.length;
  const startIndex = scrollOffset;
  const endIndex = Math.min(scrollOffset + SESSIONS_PER_PAGE, totalSessions);
  const visibleSessions = filteredAndSortedSessions.slice(startIndex, endIndex);
  const state = {
    sessions,
    setSessions,
    loading,
    setLoading,
    error,
    setError,
    activeIndex,
    setActiveIndex,
    scrollOffset,
    setScrollOffset,
    searchQuery,
    setSearchQuery,
    isSearchMode,
    setIsSearchMode,
    hasLoadedFullContent,
    setHasLoadedFullContent,
    sortOrder,
    setSortOrder,
    sortReverse,
    setSortReverse,
    terminalWidth,
    filteredAndSortedSessions,
    totalSessions,
    startIndex,
    endIndex,
    visibleSessions
  };
  return state;
};
var useLoadSessions = (config, state) => {
  const {
    setSessions,
    setLoading,
    setError,
    isSearchMode,
    hasLoadedFullContent,
    setHasLoadedFullContent
  } = state;
  (0, import_react66.useEffect)(() => {
    const loadSessions = async () => {
      try {
        const chatsDir = path6.join(config.storage.getProjectTempDir(), "chats");
        const sessionData = await getSessionFiles(
          chatsDir,
          config.getSessionId()
        );
        setSessions(sessionData);
        setLoading(false);
      } catch (err) {
        setError(
          err instanceof Error ? err.message : "Failed to load sessions"
        );
        setLoading(false);
      }
    };
    loadSessions();
  }, [config, setSessions, setLoading, setError]);
  (0, import_react66.useEffect)(() => {
    const loadFullContent = async () => {
      if (isSearchMode && !hasLoadedFullContent) {
        try {
          const chatsDir = path6.join(
            config.storage.getProjectTempDir(),
            "chats"
          );
          const sessionData = await getSessionFiles(
            chatsDir,
            config.getSessionId(),
            { includeFullContent: true }
          );
          setSessions(sessionData);
          setHasLoadedFullContent(true);
        } catch (err) {
          setError(
            err instanceof Error ? err.message : "Failed to load full session content"
          );
        }
      }
    };
    loadFullContent();
  }, [
    isSearchMode,
    hasLoadedFullContent,
    config,
    setSessions,
    setHasLoadedFullContent,
    setError
  ]);
};
var useMoveSelection = (state) => {
  const {
    totalSessions,
    activeIndex,
    scrollOffset,
    setActiveIndex,
    setScrollOffset
  } = state;
  return (0, import_react66.useCallback)(
    (delta) => {
      const newIndex = Math.max(
        0,
        Math.min(totalSessions - 1, activeIndex + delta)
      );
      setActiveIndex(newIndex);
      if (newIndex < scrollOffset) {
        setScrollOffset(newIndex);
      } else if (newIndex >= scrollOffset + SESSIONS_PER_PAGE) {
        setScrollOffset(newIndex - SESSIONS_PER_PAGE + 1);
      }
    },
    [totalSessions, activeIndex, scrollOffset, setActiveIndex, setScrollOffset]
  );
};
var useCycleSortOrder = (state) => {
  const { sortOrder, setSortOrder } = state;
  return (0, import_react66.useCallback)(() => {
    const orders = [
      "date",
      "messages",
      "name"
    ];
    const currentIndex = orders.indexOf(sortOrder);
    const nextIndex = (currentIndex + 1) % orders.length;
    setSortOrder(orders[nextIndex]);
  }, [sortOrder, setSortOrder]);
};
var useSessionBrowserInput = (state, moveSelection, cycleSortOrder, onResumeSession, onDeleteSession, onExit) => {
  useKeypress(
    (key) => {
      if (state.isSearchMode) {
        if (key.name === "escape") {
          state.setIsSearchMode(false);
          state.setSearchQuery("");
          state.setActiveIndex(0);
          state.setScrollOffset(0);
          return true;
        } else if (key.name === "backspace") {
          state.setSearchQuery((prev) => prev.slice(0, -1));
          state.setActiveIndex(0);
          state.setScrollOffset(0);
          return true;
        } else if (key.sequence && key.sequence.length === 1 && !key.alt && !key.ctrl && !key.cmd) {
          state.setSearchQuery((prev) => prev + key.sequence);
          state.setActiveIndex(0);
          state.setScrollOffset(0);
          return true;
        }
      } else {
        if (key.sequence === "g") {
          state.setActiveIndex(0);
          state.setScrollOffset(0);
          return true;
        } else if (key.sequence === "G") {
          state.setActiveIndex(state.totalSessions - 1);
          state.setScrollOffset(
            Math.max(0, state.totalSessions - SESSIONS_PER_PAGE)
          );
          return true;
        } else if (key.sequence === "s") {
          cycleSortOrder();
          return true;
        } else if (key.sequence === "r") {
          state.setSortReverse(!state.sortReverse);
          return true;
        } else if (key.sequence === "/") {
          state.setIsSearchMode(true);
          return true;
        } else if (key.sequence === "q" || key.sequence === "Q" || key.name === "escape") {
          onExit();
          return true;
        } else if (key.sequence === "x" || key.sequence === "X") {
          const selectedSession = state.filteredAndSortedSessions[state.activeIndex];
          if (selectedSession && !selectedSession.isCurrentSession) {
            onDeleteSession(selectedSession).then(() => {
              state.setSessions(
                state.sessions.filter((s) => s.id !== selectedSession.id)
              );
              if (state.activeIndex >= state.filteredAndSortedSessions.length - 1) {
                state.setActiveIndex(
                  Math.max(0, state.filteredAndSortedSessions.length - 2)
                );
              }
            }).catch((error) => {
              state.setError(
                `Failed to delete session: ${error instanceof Error ? error.message : "Unknown error"}`
              );
            });
          }
          return true;
        } else if (key.sequence === "u") {
          moveSelection(-Math.round(SESSIONS_PER_PAGE / 2));
          return true;
        } else if (key.sequence === "d") {
          moveSelection(Math.round(SESSIONS_PER_PAGE / 2));
          return true;
        }
      }
      if (key.name === "enter" && state.filteredAndSortedSessions[state.activeIndex]) {
        const selectedSession = state.filteredAndSortedSessions[state.activeIndex];
        if (!selectedSession.isCurrentSession) {
          onResumeSession(selectedSession);
        }
        return true;
      } else if (key.name === "up") {
        moveSelection(-1);
        return true;
      } else if (key.name === "down") {
        moveSelection(1);
        return true;
      } else if (key.name === "pageup") {
        moveSelection(-SESSIONS_PER_PAGE);
        return true;
      } else if (key.name === "pagedown") {
        moveSelection(SESSIONS_PER_PAGE);
        return true;
      }
      return false;
    },
    { isActive: true }
  );
};
function SessionBrowserView({
  state
}) {
  if (state.loading) {
    return /* @__PURE__ */ (0, import_jsx_runtime99.jsx)(SessionBrowserLoading, {});
  }
  if (state.error) {
    return /* @__PURE__ */ (0, import_jsx_runtime99.jsx)(SessionBrowserError, { state });
  }
  if (state.sessions.length === 0) {
    return /* @__PURE__ */ (0, import_jsx_runtime99.jsx)(SessionBrowserEmpty, {});
  }
  return /* @__PURE__ */ (0, import_jsx_runtime99.jsxs)(Box_default, { flexDirection: "column", paddingX: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime99.jsx)(SessionListHeader, { state }),
    state.isSearchMode && /* @__PURE__ */ (0, import_jsx_runtime99.jsx)(SearchModeDisplay, { state }),
    state.totalSessions === 0 ? /* @__PURE__ */ (0, import_jsx_runtime99.jsx)(NoResultsDisplay, { state }) : /* @__PURE__ */ (0, import_jsx_runtime99.jsx)(SessionList, { state, formatRelativeTime })
  ] });
}
function SessionBrowser({
  config,
  onResumeSession,
  onDeleteSession,
  onExit
}) {
  const state = useSessionBrowserState();
  useLoadSessions(config, state);
  const moveSelection = useMoveSelection(state);
  const cycleSortOrder = useCycleSortOrder(state);
  useSessionBrowserInput(
    state,
    moveSelection,
    cycleSortOrder,
    onResumeSession,
    onDeleteSession,
    onExit
  );
  return /* @__PURE__ */ (0, import_jsx_runtime99.jsx)(SessionBrowserView, { state });
}

// packages/cli/src/ui/components/ModelDialog.tsx
var import_react68 = __toESM(require_react(), 1);

// packages/cli/src/ui/components/ModelQuotaDisplay.tsx
var import_react67 = __toESM(require_react(), 1);

// packages/cli/src/ui/components/ProgressBar.tsx
var import_jsx_runtime100 = __toESM(require_jsx_runtime(), 1);
var ProgressBar = ({
  value,
  width,
  warningThreshold = 80
}) => {
  const safeValue = Math.min(Math.max(value, 0), 100);
  const activeChars = Math.ceil(safeValue / 100 * width);
  const inactiveChars = width - activeChars;
  let color = theme.status.success;
  if (safeValue >= 100) {
    color = theme.status.error;
  } else if (safeValue >= warningThreshold) {
    color = theme.status.warning;
  }
  return /* @__PURE__ */ (0, import_jsx_runtime100.jsxs)(Box_default, { flexDirection: "row", children: [
    /* @__PURE__ */ (0, import_jsx_runtime100.jsx)(Text, { color, children: "\u25AC".repeat(activeChars) }),
    /* @__PURE__ */ (0, import_jsx_runtime100.jsx)(Text, { color: theme.border.default, children: "\u25AC".repeat(inactiveChars) })
  ] });
};

// packages/cli/src/ui/components/ModelQuotaDisplay.tsx
var import_jsx_runtime101 = __toESM(require_jsx_runtime(), 1);
var ModelUsageRow = ({ row, availableWidth }) => {
  const { terminalWidth } = useUIState();
  const nameColumnWidth = 12;
  const percentageWidth = 4;
  const resetColumnWidth = 26;
  const usedPercentage = row.usedPercentage;
  const nameLabel = row.name;
  const percentageLabel = `${usedPercentage.toFixed(0)}%`.padEnd(
    percentageWidth
  );
  const resetLabel = row.resetTime ? formatResetTime(row.resetTime, "column").slice(0, resetColumnWidth).padEnd(resetColumnWidth) : "".padEnd(resetColumnWidth);
  const nameColWidth = nameColumnWidth;
  const percentColWidth = percentageWidth + 1;
  const resetColWidth = resetColumnWidth + 1;
  const fixedSiblingWidth = nameColWidth + percentColWidth + resetColWidth;
  const calcWidth = availableWidth ?? terminalWidth;
  const defaultPadding = availableWidth != null ? 0 : 4;
  const buffer = 3;
  const barWidth = Math.max(
    0,
    calcWidth - defaultPadding - fixedSiblingWidth - buffer
  );
  let percentageColor = theme.text.primary;
  if (usedPercentage >= 100) {
    percentageColor = theme.status.error;
  } else if (usedPercentage >= 80) {
    percentageColor = theme.status.warning;
  }
  return /* @__PURE__ */ (0, import_jsx_runtime101.jsxs)(Box_default, { flexDirection: "row", width: "100%", children: [
    /* @__PURE__ */ (0, import_jsx_runtime101.jsx)(Box_default, { width: nameColumnWidth, children: /* @__PURE__ */ (0, import_jsx_runtime101.jsx)(Text, { color: theme.text.primary, wrap: "truncate-end", children: nameLabel }) }),
    /* @__PURE__ */ (0, import_jsx_runtime101.jsx)(Box_default, { flexGrow: 1, children: /* @__PURE__ */ (0, import_jsx_runtime101.jsx)(ProgressBar, { value: usedPercentage, width: barWidth }) }),
    /* @__PURE__ */ (0, import_jsx_runtime101.jsx)(Box_default, { width: 4, marginLeft: 1, children: /* @__PURE__ */ (0, import_jsx_runtime101.jsx)(Text, { color: percentageColor, children: percentageLabel }) }),
    /* @__PURE__ */ (0, import_jsx_runtime101.jsx)(Box_default, { width: resetColumnWidth, marginLeft: 1, children: /* @__PURE__ */ (0, import_jsx_runtime101.jsx)(Text, { color: theme.text.secondary, children: resetLabel.trim() ? `Resets: ${resetLabel}` : "" }) })
  ] });
};
var ModelQuotaDisplay = ({
  buckets,
  availableWidth,
  modelsToShow = ["all"],
  title = "Model usage"
}) => {
  const config = useConfig();
  const modelsWithQuotas = (0, import_react67.useMemo)(() => {
    if (!buckets) return [];
    let filteredBuckets = buckets.filter(
      (b) => b.modelId && b.remainingFraction != null
    );
    if (modelsToShow.includes("current")) {
      const currentModel = config.getActiveModel?.() ?? config.getModel?.();
      filteredBuckets = filteredBuckets.filter(
        (b) => b.modelId === currentModel
      );
    } else if (!modelsToShow.includes("all")) {
      filteredBuckets = filteredBuckets.filter(
        (b) => b.modelId && modelsToShow.includes(b.modelId)
      );
    }
    const groupedByTier = /* @__PURE__ */ new Map();
    filteredBuckets.forEach((b) => {
      const modelId = b.modelId;
      const remainingFraction = b.remainingFraction;
      if (!modelId || remainingFraction == null) return;
      const tier = config?.modelConfigService?.getModelDefinition(modelId)?.tier;
      const groupKey = tier ?? modelId;
      const existing = groupedByTier.get(groupKey);
      if (!existing || remainingFraction < existing.remainingFraction) {
        const tierDisplayNames = {
          pro: "Pro",
          flash: "Flash",
          "flash-lite": "Flash Lite"
        };
        const name = tier ? tierDisplayNames[tier] ?? tier : getDisplayString(modelId, config);
        groupedByTier.set(groupKey, {
          modelId,
          remainingFraction,
          resetTime: b.resetTime,
          name
        });
      }
    });
    return Array.from(groupedByTier.entries()).map(([key, data]) => {
      const usedFraction = 1 - data.remainingFraction;
      const usedPercentage = usedFraction * 100;
      return {
        modelId: key,
        name: data.name,
        usedFraction,
        usedPercentage,
        resetTime: data.resetTime
      };
    });
  }, [buckets, config, modelsToShow]);
  if (modelsWithQuotas.length === 0) {
    return null;
  }
  return /* @__PURE__ */ (0, import_jsx_runtime101.jsxs)(Box_default, { flexDirection: "column", marginTop: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime101.jsx)(
      Box_default,
      {
        borderStyle: "single",
        borderTop: true,
        borderBottom: false,
        borderLeft: false,
        borderRight: false,
        borderColor: theme.border.default
      }
    ),
    /* @__PURE__ */ (0, import_jsx_runtime101.jsxs)(Box_default, { flexDirection: "column", children: [
      /* @__PURE__ */ (0, import_jsx_runtime101.jsx)(Box_default, { marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime101.jsx)(Text, { bold: true, color: theme.text.primary, children: title }) }),
      modelsWithQuotas.map((row) => /* @__PURE__ */ (0, import_jsx_runtime101.jsx)(
        ModelUsageRow,
        {
          row,
          availableWidth
        },
        row.modelId
      ))
    ] })
  ] });
};

// packages/cli/src/ui/components/shared/DescriptiveRadioButtonSelect.tsx
var import_jsx_runtime102 = __toESM(require_jsx_runtime(), 1);
function DescriptiveRadioButtonSelect({
  items,
  initialIndex = 0,
  onSelect,
  onHighlight,
  isFocused = true,
  showNumbers = false,
  showScrollArrows = false,
  maxItemsToShow = 10
}) {
  return /* @__PURE__ */ (0, import_jsx_runtime102.jsx)(
    BaseSelectionList,
    {
      items,
      initialIndex,
      onSelect,
      onHighlight,
      isFocused,
      showNumbers,
      showScrollArrows,
      maxItemsToShow,
      renderItem: (item, { titleColor }) => /* @__PURE__ */ (0, import_jsx_runtime102.jsxs)(Box_default, { flexDirection: "column", children: [
        /* @__PURE__ */ (0, import_jsx_runtime102.jsx)(Text, { color: titleColor, children: item.title }),
        item.description && /* @__PURE__ */ (0, import_jsx_runtime102.jsx)(Text, { color: theme.text.secondary, children: item.description })
      ] }, item.key)
    }
  );
}

// packages/cli/src/ui/components/ModelDialog.tsx
var import_jsx_runtime103 = __toESM(require_jsx_runtime(), 1);
function ModelDialog({ onClose }) {
  const config = (0, import_react68.useContext)(ConfigContext);
  const settings = useSettings();
  const { terminalWidth } = useUIState();
  const [hasAccessToProModel, setHasAccessToProModel] = (0, import_react68.useState)(
    () => !(config?.getProModelNoAccessSync() ?? false)
  );
  const [view, setView] = (0, import_react68.useState)(
    () => config?.getProModelNoAccessSync() ? "manual" : "main"
  );
  const [persistMode, setPersistMode] = (0, import_react68.useState)(false);
  (0, import_react68.useEffect)(() => {
    async function checkAccess() {
      if (!config) return;
      const noAccess = await config.getProModelNoAccess();
      setHasAccessToProModel(!noAccess);
      if (noAccess) {
        setView("manual");
      }
    }
    void checkAccess();
  }, [config]);
  const preferredModel = config?.getModel() || DEFAULT_GEMINI_MODEL_AUTO;
  const shouldShowPreviewModels = config?.getHasAccessToPreviewModel();
  const useGemini31 = config?.getGemini31LaunchedSync?.() ?? false;
  const useGemini31FlashLite = config?.getGemini31FlashLiteLaunchedSync?.() ?? false;
  const selectedAuthType = settings.merged.security.auth.selectedType;
  const useCustomToolModel = useGemini31 && selectedAuthType === AuthType.USE_GEMINI;
  const manualModelSelected = (0, import_react68.useMemo)(() => {
    if (config?.getExperimentalDynamicModelConfiguration?.() === true && config.getModelConfigService) {
      const def = config.getModelConfigService().getModelDefinition(preferredModel);
      return def && def.tier !== "auto" && def.isVisible === true ? preferredModel : "";
    }
    const manualModels = [
      DEFAULT_GEMINI_MODEL,
      DEFAULT_GEMINI_FLASH_MODEL,
      DEFAULT_GEMINI_FLASH_LITE_MODEL,
      PREVIEW_GEMINI_MODEL,
      PREVIEW_GEMINI_3_1_MODEL,
      PREVIEW_GEMINI_3_1_CUSTOM_TOOLS_MODEL,
      PREVIEW_GEMINI_3_1_FLASH_LITE_MODEL,
      PREVIEW_GEMINI_FLASH_MODEL
    ];
    if (manualModels.includes(preferredModel)) {
      return preferredModel;
    }
    return "";
  }, [preferredModel, config]);
  useKeypress(
    (key) => {
      if (key.name === "escape") {
        if (view === "manual" && hasAccessToProModel) {
          setView("main");
        } else {
          onClose();
        }
        return true;
      }
      if (key.name === "tab") {
        setPersistMode((prev) => !prev);
        return true;
      }
      return false;
    },
    { isActive: true }
  );
  const mainOptions = (0, import_react68.useMemo)(() => {
    if (config?.getExperimentalDynamicModelConfiguration?.() === true && config.getModelConfigService) {
      const allOptions = config.getModelConfigService().getAvailableModelOptions({
        useGemini3_1: useGemini31,
        useGemini3_1FlashLite: useGemini31FlashLite,
        useCustomTools: useCustomToolModel,
        hasAccessToPreview: shouldShowPreviewModels,
        hasAccessToProModel
      });
      const list2 = allOptions.filter((o) => o.tier === "auto").map((o) => ({
        value: o.modelId,
        title: o.name,
        description: o.description,
        key: o.modelId
      }));
      list2.push({
        value: "Manual",
        title: manualModelSelected ? `Manual (${getDisplayString(manualModelSelected, config ?? void 0)})` : "Manual",
        description: "Manually select a model",
        key: "Manual"
      });
      return list2;
    }
    const list = [
      {
        value: DEFAULT_GEMINI_MODEL_AUTO,
        title: getDisplayString(DEFAULT_GEMINI_MODEL_AUTO),
        description: "Let Gemini CLI decide the best model for the task: gemini-2.5-pro, gemini-2.5-flash",
        key: DEFAULT_GEMINI_MODEL_AUTO
      },
      {
        value: "Manual",
        title: manualModelSelected ? `Manual (${getDisplayString(manualModelSelected)})` : "Manual",
        description: "Manually select a model",
        key: "Manual"
      }
    ];
    if (shouldShowPreviewModels) {
      list.unshift({
        value: PREVIEW_GEMINI_MODEL_AUTO,
        title: getDisplayString(PREVIEW_GEMINI_MODEL_AUTO),
        description: useGemini31 ? "Let Gemini CLI decide the best model for the task: gemini-3.1-pro, gemini-3-flash" : "Let Gemini CLI decide the best model for the task: gemini-3-pro, gemini-3-flash",
        key: PREVIEW_GEMINI_MODEL_AUTO
      });
    }
    return list;
  }, [
    config,
    shouldShowPreviewModels,
    manualModelSelected,
    useGemini31,
    useGemini31FlashLite,
    useCustomToolModel,
    hasAccessToProModel
  ]);
  const manualOptions = (0, import_react68.useMemo)(() => {
    if (config?.getExperimentalDynamicModelConfiguration?.() === true && config.getModelConfigService) {
      const allOptions = config.getModelConfigService().getAvailableModelOptions({
        useGemini3_1: useGemini31,
        useGemini3_1FlashLite: useGemini31FlashLite,
        useCustomTools: useCustomToolModel,
        hasAccessToPreview: shouldShowPreviewModels,
        hasAccessToProModel
      });
      return allOptions.filter((o) => o.tier !== "auto").map((o) => ({
        value: o.modelId,
        title: o.name,
        key: o.modelId
      }));
    }
    const list = [
      {
        value: DEFAULT_GEMINI_MODEL,
        title: getDisplayString(DEFAULT_GEMINI_MODEL),
        key: DEFAULT_GEMINI_MODEL
      },
      {
        value: DEFAULT_GEMINI_FLASH_MODEL,
        title: getDisplayString(DEFAULT_GEMINI_FLASH_MODEL),
        key: DEFAULT_GEMINI_FLASH_MODEL
      },
      {
        value: DEFAULT_GEMINI_FLASH_LITE_MODEL,
        title: getDisplayString(DEFAULT_GEMINI_FLASH_LITE_MODEL),
        key: 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),
          key: previewProModel
        },
        {
          value: PREVIEW_GEMINI_FLASH_MODEL,
          title: getDisplayString(PREVIEW_GEMINI_FLASH_MODEL),
          key: PREVIEW_GEMINI_FLASH_MODEL
        }
      ];
      if (useGemini31FlashLite) {
        previewOptions.push({
          value: PREVIEW_GEMINI_3_1_FLASH_LITE_MODEL,
          title: getDisplayString(PREVIEW_GEMINI_3_1_FLASH_LITE_MODEL),
          key: PREVIEW_GEMINI_3_1_FLASH_LITE_MODEL
        });
      }
      list.unshift(...previewOptions);
    }
    if (!hasAccessToProModel) {
      return list.filter((option) => !isProModel(option.value));
    }
    return list;
  }, [
    shouldShowPreviewModels,
    useGemini31,
    useGemini31FlashLite,
    useCustomToolModel,
    hasAccessToProModel,
    config
  ]);
  const options = view === "main" ? mainOptions : manualOptions;
  const initialIndex = (0, import_react68.useMemo)(() => {
    const idx = options.findIndex((option) => option.value === preferredModel);
    if (idx !== -1) {
      return idx;
    }
    if (view === "main") {
      const manualIdx = options.findIndex((o) => o.value === "Manual");
      return manualIdx !== -1 ? manualIdx : 0;
    }
    return 0;
  }, [preferredModel, options, view]);
  const handleSelect = (0, import_react68.useCallback)(
    (model) => {
      if (model === "Manual") {
        setView("manual");
        return;
      }
      if (config) {
        config.setModel(model, persistMode ? false : true);
        const event = new ModelSlashCommandEvent(model);
        logModelSlashCommand(config, event);
      }
      onClose();
    },
    [config, onClose, persistMode]
  );
  return /* @__PURE__ */ (0, import_jsx_runtime103.jsxs)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: theme.border.default,
      flexDirection: "column",
      padding: 1,
      width: "100%",
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime103.jsx)(Text, { bold: true, children: "Select Model" }),
        /* @__PURE__ */ (0, import_jsx_runtime103.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime103.jsx)(
          DescriptiveRadioButtonSelect,
          {
            items: options,
            onSelect: handleSelect,
            initialIndex,
            showNumbers: true
          }
        ) }),
        /* @__PURE__ */ (0, import_jsx_runtime103.jsx)(Box_default, { marginTop: 1, flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime103.jsxs)(Box_default, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime103.jsxs)(Text, { bold: true, color: theme.text.primary, children: [
            "Remember model for future sessions:",
            " "
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime103.jsx)(Text, { color: theme.status.success, children: persistMode ? "true" : "false" }),
          /* @__PURE__ */ (0, import_jsx_runtime103.jsx)(Text, { color: theme.text.secondary, children: " (Press Tab to toggle)" })
        ] }) }),
        /* @__PURE__ */ (0, import_jsx_runtime103.jsx)(Box_default, { flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime103.jsx)(Text, { color: theme.text.secondary, children: "> To use a specific Gemini model on startup, use the --model flag." }) }),
        /* @__PURE__ */ (0, import_jsx_runtime103.jsx)(
          ModelQuotaDisplay,
          {
            buckets: config?.getLastRetrievedQuota()?.buckets,
            availableWidth: terminalWidth - 2
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime103.jsx)(Box_default, { marginTop: 1, flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime103.jsx)(Text, { color: theme.text.secondary, children: "(Press Esc to close)" }) })
      ]
    }
  );
}

// packages/cli/src/ui/components/DialogManager.tsx
import process7 from "node:process";

// packages/cli/src/ui/components/AdminSettingsChangedDialog.tsx
var import_jsx_runtime104 = __toESM(require_jsx_runtime(), 1);
var AdminSettingsChangedDialog = () => {
  const keyMatchers = useKeyMatchers();
  const { handleRestart } = useUIActions();
  useKeypress(
    (key) => {
      if (keyMatchers["app.restart" /* RESTART_APP */](key)) {
        handleRestart();
        return true;
      }
      return false;
    },
    { isActive: true }
  );
  const message = "Admin settings have changed. Please restart the session to apply new settings.";
  return /* @__PURE__ */ (0, import_jsx_runtime104.jsx)(Box_default, { borderStyle: "round", borderColor: theme.status.warning, paddingX: 1, children: /* @__PURE__ */ (0, import_jsx_runtime104.jsxs)(Text, { color: theme.status.warning, children: [
    message,
    " Press 'r' to restart, or 'Ctrl+C' twice to exit."
  ] }) });
};

// packages/cli/src/ui/components/IdeTrustChangeDialog.tsx
var import_jsx_runtime105 = __toESM(require_jsx_runtime(), 1);
var IdeTrustChangeDialog = ({ reason }) => {
  useKeypress(
    (key) => {
      if (key.name === "r" || key.name === "R") {
        relaunchApp();
        return true;
      }
      return false;
    },
    { isActive: true }
  );
  let message = "Workspace trust has changed.";
  if (reason === "NONE") {
    debugLogger.warn(
      'IdeTrustChangeDialog rendered with unexpected reason "NONE"'
    );
  } else if (reason === "CONNECTION_CHANGE") {
    message = "Workspace trust has changed due to a change in the IDE connection.";
  } else if (reason === "TRUST_CHANGE") {
    message = "Workspace trust has changed due to a change in the IDE trust.";
  }
  return /* @__PURE__ */ (0, import_jsx_runtime105.jsx)(Box_default, { borderStyle: "round", borderColor: theme.status.warning, paddingX: 1, children: /* @__PURE__ */ (0, import_jsx_runtime105.jsxs)(Text, { color: theme.status.warning, children: [
    message,
    " Press 'r' to restart Gemini to apply the changes."
  ] }) });
};

// packages/cli/src/ui/components/AgentConfigDialog.tsx
var import_react69 = __toESM(require_react(), 1);
var import_jsx_runtime106 = __toESM(require_jsx_runtime(), 1);
var AGENT_CONFIG_FIELDS = [
  {
    key: "enabled",
    label: "Enabled",
    description: "Enable or disable this agent",
    type: "boolean",
    path: ["enabled"],
    defaultValue: true
  },
  {
    key: "model",
    label: "Model",
    description: "Model to use (e.g., 'gemini-2.0-flash' or 'inherit')",
    type: "string",
    path: ["modelConfig", "model"],
    defaultValue: "inherit"
  },
  {
    key: "temperature",
    label: "Temperature",
    description: "Sampling temperature (0.0 to 2.0)",
    type: "number",
    path: ["modelConfig", "generateContentConfig", "temperature"],
    defaultValue: void 0
  },
  {
    key: "topP",
    label: "Top P",
    description: "Nucleus sampling parameter (0.0 to 1.0)",
    type: "number",
    path: ["modelConfig", "generateContentConfig", "topP"],
    defaultValue: void 0
  },
  {
    key: "topK",
    label: "Top K",
    description: "Top-K sampling parameter",
    type: "number",
    path: ["modelConfig", "generateContentConfig", "topK"],
    defaultValue: void 0
  },
  {
    key: "maxOutputTokens",
    label: "Max Output Tokens",
    description: "Maximum number of tokens to generate",
    type: "number",
    path: ["modelConfig", "generateContentConfig", "maxOutputTokens"],
    defaultValue: void 0
  },
  {
    key: "maxTimeMinutes",
    label: "Max Time (minutes)",
    description: "Maximum execution time in minutes",
    type: "number",
    path: ["runConfig", "maxTimeMinutes"],
    defaultValue: void 0
  },
  {
    key: "maxTurns",
    label: "Max Turns",
    description: "Maximum number of conversational turns",
    type: "number",
    path: ["runConfig", "maxTurns"],
    defaultValue: void 0
  }
];
function setNestedValue(obj, path16, value) {
  if (!isRecord(obj)) return obj;
  const result = { ...obj };
  let current = result;
  for (let i = 0; i < path16.length - 1; i++) {
    const key = path16[i];
    if (current[key] === void 0 || current[key] === null) {
      current[key] = {};
    } else if (isRecord(current[key])) {
      current[key] = { ...current[key] };
    }
    const next = current[key];
    if (isRecord(next)) {
      current = next;
    } else {
      return result;
    }
  }
  const finalKey = path16[path16.length - 1];
  if (value === void 0) {
    delete current[finalKey];
  } else {
    current[finalKey] = value;
  }
  return result;
}
function getFieldDefaultFromDefinition(field, definition) {
  if (definition.kind !== "local") return field.defaultValue;
  if (field.key === "enabled") {
    return !definition.experimental;
  }
  if (field.key === "model") {
    return definition.modelConfig?.model ?? "inherit";
  }
  if (field.key === "temperature") {
    return definition.modelConfig?.generateContentConfig?.temperature;
  }
  if (field.key === "topP") {
    return definition.modelConfig?.generateContentConfig?.topP;
  }
  if (field.key === "topK") {
    return definition.modelConfig?.generateContentConfig?.topK;
  }
  if (field.key === "maxOutputTokens") {
    return definition.modelConfig?.generateContentConfig?.maxOutputTokens;
  }
  if (field.key === "maxTimeMinutes") {
    return definition.runConfig?.maxTimeMinutes;
  }
  if (field.key === "maxTurns") {
    return definition.runConfig?.maxTurns;
  }
  return field.defaultValue;
}
function AgentConfigDialog({
  agentName,
  displayName,
  definition,
  settings,
  onClose,
  onSave,
  availableTerminalHeight
}) {
  const [selectedScope, setSelectedScope] = (0, import_react69.useState)(
    "User" /* User */
  );
  const [pendingOverride, setPendingOverride] = (0, import_react69.useState)(() => {
    const scopeSettings = settings.forScope(selectedScope).settings;
    const existingOverride = scopeSettings.agents?.overrides?.[agentName];
    return existingOverride ? structuredClone(existingOverride) : {};
  });
  const [modifiedFields, setModifiedFields] = (0, import_react69.useState)(/* @__PURE__ */ new Set());
  (0, import_react69.useEffect)(() => {
    const scopeSettings = settings.forScope(selectedScope).settings;
    const existingOverride = scopeSettings.agents?.overrides?.[agentName];
    setPendingOverride(
      existingOverride ? structuredClone(existingOverride) : {}
    );
    setModifiedFields(/* @__PURE__ */ new Set());
  }, [selectedScope, settings, agentName]);
  const saveFieldValue = (0, import_react69.useCallback)(
    (fieldKey, path16, value) => {
      if (["__proto__", "constructor", "prototype"].includes(agentName)) {
        return;
      }
      const settingsPath2 = ["agents", "overrides", agentName, ...path16].join(
        "."
      );
      settings.setValue(selectedScope, settingsPath2, value);
      onSave?.();
    },
    [settings, selectedScope, agentName, onSave]
  );
  const maxLabelWidth = (0, import_react69.useMemo)(() => {
    let max = 0;
    for (const field of AGENT_CONFIG_FIELDS) {
      const lWidth = getCachedStringWidth(field.label);
      const dWidth = getCachedStringWidth(field.description);
      max = Math.max(max, lWidth, dWidth);
    }
    return max;
  }, []);
  const items = (0, import_react69.useMemo)(
    () => AGENT_CONFIG_FIELDS.map((field) => {
      const currentValue = getNestedValue(pendingOverride, field.path);
      const defaultValue = getFieldDefaultFromDefinition(field, definition);
      const effectiveValue = currentValue !== void 0 ? currentValue : defaultValue;
      let displayValue;
      if (field.type === "boolean") {
        displayValue = effectiveValue ? "true" : "false";
      } else if (effectiveValue !== void 0 && effectiveValue !== null) {
        displayValue = String(effectiveValue);
      } else {
        displayValue = "(default)";
      }
      const isModified = modifiedFields.has(field.key) || currentValue !== void 0;
      if (isModified && currentValue !== void 0) {
        displayValue += "*";
      }
      const rawValue = currentValue !== void 0 ? currentValue : effectiveValue;
      return {
        key: field.key,
        label: field.label,
        description: field.description,
        type: field.type,
        displayValue,
        isGreyedOut: currentValue === void 0,
        scopeMessage: void 0,
        // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
        rawValue
      };
    }),
    [pendingOverride, definition, modifiedFields]
  );
  const maxItemsToShow = 8;
  const handleScopeChange = (0, import_react69.useCallback)((scope) => {
    setSelectedScope(scope);
  }, []);
  const handleItemToggle = (0, import_react69.useCallback)(
    (key, _item) => {
      const field = AGENT_CONFIG_FIELDS.find((f) => f.key === key);
      if (!field || field.type !== "boolean") return;
      const currentValue = getNestedValue(pendingOverride, field.path);
      const defaultValue = getFieldDefaultFromDefinition(field, definition);
      const effectiveValue = currentValue !== void 0 ? currentValue : defaultValue;
      const newValue = !effectiveValue;
      const newOverride = setNestedValue(
        pendingOverride,
        field.path,
        newValue
      );
      setPendingOverride(newOverride);
      setModifiedFields((prev) => new Set(prev).add(key));
      saveFieldValue(field.key, field.path, newValue);
    },
    [pendingOverride, definition, saveFieldValue]
  );
  const handleEditCommit = (0, import_react69.useCallback)(
    (key, newValue, _item) => {
      const field = AGENT_CONFIG_FIELDS.find((f) => f.key === key);
      if (!field) return;
      let parsed;
      if (field.type === "number") {
        if (newValue.trim() === "") {
          parsed = void 0;
        } else {
          const numParsed = Number(newValue.trim());
          if (Number.isNaN(numParsed)) {
            return;
          }
          parsed = numParsed;
        }
      } else {
        parsed = newValue.trim() === "" ? void 0 : newValue;
      }
      const newOverride = setNestedValue(
        pendingOverride,
        field.path,
        parsed
      );
      setPendingOverride(newOverride);
      setModifiedFields((prev) => new Set(prev).add(key));
      saveFieldValue(field.key, field.path, parsed);
    },
    [pendingOverride, saveFieldValue]
  );
  const handleItemClear = (0, import_react69.useCallback)(
    (key, _item) => {
      const field = AGENT_CONFIG_FIELDS.find((f) => f.key === key);
      if (!field) return;
      const newOverride = setNestedValue(
        pendingOverride,
        field.path,
        void 0
      );
      setPendingOverride(newOverride);
      setModifiedFields((prev) => {
        const updated = new Set(prev);
        updated.delete(key);
        return updated;
      });
      saveFieldValue(field.key, field.path, void 0);
    },
    [pendingOverride, saveFieldValue]
  );
  return /* @__PURE__ */ (0, import_jsx_runtime106.jsx)(
    BaseSettingsDialog,
    {
      title: `Configure: ${displayName}`,
      searchEnabled: false,
      items,
      showScopeSelector: true,
      selectedScope,
      onScopeChange: handleScopeChange,
      maxItemsToShow,
      availableHeight: availableTerminalHeight,
      maxLabelWidth,
      onItemToggle: handleItemToggle,
      onEditCommit: handleEditCommit,
      onItemClear: handleItemClear,
      onClose,
      footer: modifiedFields.size > 0 ? {
        content: /* @__PURE__ */ (0, import_jsx_runtime106.jsx)(Text, { color: theme.text.secondary, children: "Changes saved automatically." }),
        height: 1
      } : void 0
    }
  );
}

// packages/cli/src/ui/components/PolicyUpdateDialog.tsx
var import_react70 = __toESM(require_react(), 1);
var import_jsx_runtime107 = __toESM(require_jsx_runtime(), 1);
var PolicyUpdateDialog = ({
  config,
  request,
  onClose
}) => {
  const keyMatchers = useKeyMatchers();
  const isProcessing = (0, import_react70.useRef)(false);
  const handleSelect = (0, import_react70.useCallback)(
    async (choice) => {
      if (isProcessing.current) {
        return;
      }
      isProcessing.current = true;
      try {
        if (choice === "accept" /* ACCEPT */) {
          const integrityManager = new PolicyIntegrityManager();
          await integrityManager.acceptIntegrity(
            request.scope,
            request.identifier,
            request.newHash
          );
          await config.loadWorkspacePolicies(request.policyDir);
        }
        onClose();
      } finally {
        isProcessing.current = false;
      }
    },
    [config, request, onClose]
  );
  useKeypress(
    (key) => {
      if (keyMatchers["basic.cancel" /* ESCAPE */](key)) {
        onClose();
        return true;
      }
      return false;
    },
    { isActive: true }
  );
  const options = [
    {
      label: "Accept and Load",
      value: "accept" /* ACCEPT */,
      key: "accept"
    },
    {
      label: "Ignore (Use Default Policies)",
      value: "ignore" /* IGNORE */,
      key: "ignore"
    }
  ];
  return /* @__PURE__ */ (0, import_jsx_runtime107.jsx)(Box_default, { flexDirection: "column", width: "100%", children: /* @__PURE__ */ (0, import_jsx_runtime107.jsxs)(
    Box_default,
    {
      flexDirection: "column",
      borderStyle: "round",
      borderColor: theme.status.warning,
      padding: 1,
      marginLeft: 1,
      marginRight: 1,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime107.jsxs)(Box_default, { flexDirection: "column", marginBottom: 1, children: [
          /* @__PURE__ */ (0, import_jsx_runtime107.jsxs)(Text, { bold: true, color: theme.text.primary, children: [
            "New or changed ",
            request.scope,
            " policies detected"
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime107.jsxs)(Text, { color: theme.text.primary, children: [
            "Location: ",
            request.identifier
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime107.jsx)(Text, { color: theme.text.primary, children: "Do you want to accept and load these policies?" })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime107.jsx)(
          RadioButtonSelect,
          {
            items: options,
            onSelect: handleSelect,
            isFocused: true
          }
        )
      ]
    }
  ) });
};

// packages/cli/src/ui/components/DialogManager.tsx
var import_jsx_runtime108 = __toESM(require_jsx_runtime(), 1);
var DialogManager = ({
  addItem,
  terminalWidth
}) => {
  const config = useConfig();
  const settings = useSettings();
  const uiState = useUIState();
  const uiActions = useUIActions();
  const {
    constrainHeight,
    terminalHeight,
    staticExtraHeight,
    terminalWidth: uiTerminalWidth
  } = uiState;
  if (uiState.adminSettingsChanged) {
    return /* @__PURE__ */ (0, import_jsx_runtime108.jsx)(AdminSettingsChangedDialog, {});
  }
  if (uiState.showIdeRestartPrompt) {
    return /* @__PURE__ */ (0, import_jsx_runtime108.jsx)(IdeTrustChangeDialog, { reason: uiState.ideTrustRestartReason });
  }
  if (uiState.newAgents) {
    return /* @__PURE__ */ (0, import_jsx_runtime108.jsx)(
      NewAgentsNotification,
      {
        agents: uiState.newAgents,
        onSelect: uiActions.handleNewAgentsSelect
      }
    );
  }
  if (uiState.quota.proQuotaRequest) {
    return /* @__PURE__ */ (0, import_jsx_runtime108.jsx)(
      ProQuotaDialog,
      {
        failedModel: uiState.quota.proQuotaRequest.failedModel,
        fallbackModel: uiState.quota.proQuotaRequest.fallbackModel,
        message: uiState.quota.proQuotaRequest.message,
        isTerminalQuotaError: uiState.quota.proQuotaRequest.isTerminalQuotaError,
        isModelNotFoundError: !!uiState.quota.proQuotaRequest.isModelNotFoundError,
        authType: uiState.quota.proQuotaRequest.authType,
        tierName: config?.getUserTierName(),
        onChoice: uiActions.handleProQuotaChoice
      }
    );
  }
  if (uiState.quota.validationRequest) {
    return /* @__PURE__ */ (0, import_jsx_runtime108.jsx)(
      ValidationDialog,
      {
        validationLink: uiState.quota.validationRequest.validationLink,
        validationDescription: uiState.quota.validationRequest.validationDescription,
        learnMoreUrl: uiState.quota.validationRequest.learnMoreUrl,
        onChoice: uiActions.handleValidationChoice
      }
    );
  }
  if (uiState.quota.overageMenuRequest) {
    return /* @__PURE__ */ (0, import_jsx_runtime108.jsx)(
      OverageMenuDialog,
      {
        failedModel: uiState.quota.overageMenuRequest.failedModel,
        fallbackModel: uiState.quota.overageMenuRequest.fallbackModel,
        resetTime: uiState.quota.overageMenuRequest.resetTime,
        creditBalance: uiState.quota.overageMenuRequest.creditBalance,
        onChoice: uiActions.handleOverageMenuChoice
      }
    );
  }
  if (uiState.quota.emptyWalletRequest) {
    return /* @__PURE__ */ (0, import_jsx_runtime108.jsx)(
      EmptyWalletDialog,
      {
        failedModel: uiState.quota.emptyWalletRequest.failedModel,
        fallbackModel: uiState.quota.emptyWalletRequest.fallbackModel,
        resetTime: uiState.quota.emptyWalletRequest.resetTime,
        onGetCredits: uiState.quota.emptyWalletRequest.onGetCredits,
        onChoice: uiActions.handleEmptyWalletChoice
      }
    );
  }
  if (uiState.shouldShowIdePrompt) {
    return /* @__PURE__ */ (0, import_jsx_runtime108.jsx)(
      IdeIntegrationNudge,
      {
        ide: uiState.currentIDE,
        onComplete: uiActions.handleIdePromptComplete
      }
    );
  }
  if (uiState.isFolderTrustDialogOpen) {
    return /* @__PURE__ */ (0, import_jsx_runtime108.jsx)(
      FolderTrustDialog,
      {
        onSelect: uiActions.handleFolderTrustSelect,
        isRestarting: uiState.isRestarting,
        discoveryResults: uiState.folderDiscoveryResults
      }
    );
  }
  if (uiState.isPolicyUpdateDialogOpen) {
    return /* @__PURE__ */ (0, import_jsx_runtime108.jsx)(
      PolicyUpdateDialog,
      {
        config,
        request: uiState.policyUpdateConfirmationRequest,
        onClose: () => uiActions.setIsPolicyUpdateDialogOpen(false)
      }
    );
  }
  if (uiState.loopDetectionConfirmationRequest) {
    return /* @__PURE__ */ (0, import_jsx_runtime108.jsx)(
      LoopDetectionConfirmation,
      {
        onComplete: uiState.loopDetectionConfirmationRequest.onComplete
      }
    );
  }
  if (uiState.permissionConfirmationRequest) {
    const files = uiState.permissionConfirmationRequest.files;
    const filesList = files.map((f) => `- ${f}`).join("\n");
    return /* @__PURE__ */ (0, import_jsx_runtime108.jsx)(
      ConsentPrompt,
      {
        prompt: `The following files are outside your workspace:

${filesList}

Do you want to allow this read?`,
        onConfirm: (allowed) => {
          uiState.permissionConfirmationRequest?.onComplete({ allowed });
        },
        terminalWidth
      }
    );
  }
  if (uiState.commandConfirmationRequest) {
    return /* @__PURE__ */ (0, import_jsx_runtime108.jsx)(
      ConsentPrompt,
      {
        prompt: uiState.commandConfirmationRequest.prompt,
        onConfirm: uiState.commandConfirmationRequest.onConfirm,
        terminalWidth
      }
    );
  }
  if (uiState.authConsentRequest) {
    return /* @__PURE__ */ (0, import_jsx_runtime108.jsx)(
      ConsentPrompt,
      {
        prompt: uiState.authConsentRequest.prompt,
        onConfirm: uiState.authConsentRequest.onConfirm,
        terminalWidth
      }
    );
  }
  if (uiState.confirmUpdateExtensionRequests.length > 0) {
    const request = uiState.confirmUpdateExtensionRequests[0];
    return /* @__PURE__ */ (0, import_jsx_runtime108.jsx)(
      ConsentPrompt,
      {
        prompt: request.prompt,
        onConfirm: request.onConfirm,
        terminalWidth
      }
    );
  }
  if (uiState.isThemeDialogOpen) {
    return /* @__PURE__ */ (0, import_jsx_runtime108.jsxs)(Box_default, { flexDirection: "column", children: [
      uiState.themeError && /* @__PURE__ */ (0, import_jsx_runtime108.jsx)(Box_default, { marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime108.jsx)(Text, { color: theme.status.error, children: uiState.themeError }) }),
      /* @__PURE__ */ (0, import_jsx_runtime108.jsx)(
        ThemeDialog,
        {
          onSelect: uiActions.handleThemeSelect,
          onCancel: uiActions.closeThemeDialog,
          onHighlight: uiActions.handleThemeHighlight,
          settings,
          availableTerminalHeight: constrainHeight ? terminalHeight - staticExtraHeight : void 0,
          terminalWidth: uiTerminalWidth
        }
      )
    ] });
  }
  if (uiState.isSettingsDialogOpen) {
    return /* @__PURE__ */ (0, import_jsx_runtime108.jsx)(Box_default, { flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime108.jsx)(
      SettingsDialog,
      {
        onSelect: () => uiActions.closeSettingsDialog(),
        onRestartRequest: relaunchApp,
        availableTerminalHeight: terminalHeight - staticExtraHeight
      }
    ) });
  }
  if (uiState.isModelDialogOpen) {
    return /* @__PURE__ */ (0, import_jsx_runtime108.jsx)(ModelDialog, { onClose: uiActions.closeModelDialog });
  }
  if (uiState.isAgentConfigDialogOpen && uiState.selectedAgentName && uiState.selectedAgentDisplayName && uiState.selectedAgentDefinition) {
    return /* @__PURE__ */ (0, import_jsx_runtime108.jsx)(Box_default, { flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime108.jsx)(
      AgentConfigDialog,
      {
        agentName: uiState.selectedAgentName,
        displayName: uiState.selectedAgentDisplayName,
        definition: uiState.selectedAgentDefinition,
        settings,
        availableTerminalHeight: terminalHeight - staticExtraHeight,
        onClose: uiActions.closeAgentConfigDialog,
        onSave: async () => {
          const agentRegistry = config?.getAgentRegistry();
          if (agentRegistry) {
            await agentRegistry.reload();
          }
        }
      }
    ) });
  }
  if (uiState.accountSuspensionInfo) {
    return /* @__PURE__ */ (0, import_jsx_runtime108.jsx)(Box_default, { flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime108.jsx)(
      BannedAccountDialog,
      {
        accountSuspensionInfo: uiState.accountSuspensionInfo,
        onExit: () => {
          process7.exit(1);
        },
        onChangeAuth: () => {
          uiActions.clearAccountSuspension();
        }
      }
    ) });
  }
  if (uiState.isAuthenticating) {
    return /* @__PURE__ */ (0, import_jsx_runtime108.jsx)(
      AuthInProgress,
      {
        onTimeout: () => {
          uiActions.onAuthError("Authentication cancelled.");
        }
      }
    );
  }
  if (uiState.isAwaitingApiKeyInput) {
    return /* @__PURE__ */ (0, import_jsx_runtime108.jsx)(Box_default, { flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime108.jsx)(
      ApiAuthDialog,
      {
        onSubmit: uiActions.handleApiKeySubmit,
        onCancel: uiActions.handleApiKeyCancel,
        error: uiState.authError,
        defaultValue: uiState.apiKeyDefaultValue
      },
      uiState.apiKeyDefaultValue
    ) });
  }
  if (uiState.isAuthDialogOpen) {
    return /* @__PURE__ */ (0, import_jsx_runtime108.jsx)(Box_default, { flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime108.jsx)(
      AuthDialog,
      {
        config,
        settings,
        setAuthState: uiActions.setAuthState,
        authError: uiState.authError,
        onAuthError: uiActions.onAuthError,
        setAuthContext: uiActions.setAuthContext
      }
    ) });
  }
  if (uiState.isEditorDialogOpen) {
    return /* @__PURE__ */ (0, import_jsx_runtime108.jsxs)(Box_default, { flexDirection: "column", children: [
      uiState.editorError && /* @__PURE__ */ (0, import_jsx_runtime108.jsx)(Box_default, { marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime108.jsx)(Text, { color: theme.status.error, children: uiState.editorError }) }),
      /* @__PURE__ */ (0, import_jsx_runtime108.jsx)(
        EditorSettingsDialog,
        {
          onSelect: uiActions.handleEditorSelect,
          settings,
          onExit: uiActions.exitEditorDialog
        }
      )
    ] });
  }
  if (uiState.showPrivacyNotice) {
    return /* @__PURE__ */ (0, import_jsx_runtime108.jsx)(
      PrivacyNotice,
      {
        onExit: () => uiActions.exitPrivacyNotice(),
        config
      }
    );
  }
  if (uiState.isSessionBrowserOpen) {
    return /* @__PURE__ */ (0, import_jsx_runtime108.jsx)(
      SessionBrowser,
      {
        config,
        onResumeSession: uiActions.handleResumeSession,
        onDeleteSession: uiActions.handleDeleteSession,
        onExit: uiActions.closeSessionBrowser
      }
    );
  }
  if (uiState.isPermissionsDialogOpen) {
    return /* @__PURE__ */ (0, import_jsx_runtime108.jsx)(
      PermissionsModifyTrustDialog,
      {
        onExit: uiActions.closePermissionsDialog,
        addItem,
        targetDirectory: uiState.permissionsDialogProps?.targetDirectory
      }
    );
  }
  return null;
};

// packages/cli/src/ui/components/Composer.tsx
var import_react93 = __toESM(require_react(), 1);

// packages/cli/src/ui/components/ToastDisplay.tsx
var import_jsx_runtime109 = __toESM(require_jsx_runtime(), 1);
function shouldShowToast(uiState, inputState) {
  return uiState.ctrlCPressedOnce || Boolean(uiState.transientMessage) || uiState.ctrlDPressedOnce || inputState.showEscapePrompt && (inputState.buffer.text.length > 0 || uiState.history.length > 0) || Boolean(uiState.queueErrorMessage) || uiState.showIsExpandableHint;
}
var ToastDisplay = () => {
  const uiState = useUIState();
  const inputState = useInputState();
  if (uiState.ctrlCPressedOnce) {
    return /* @__PURE__ */ (0, import_jsx_runtime109.jsx)(Text, { color: theme.status.warning, children: "Press Ctrl+C again to exit." });
  }
  if (uiState.transientMessage?.type === "warning" /* Warning */ && uiState.transientMessage.text) {
    return /* @__PURE__ */ (0, import_jsx_runtime109.jsx)(Text, { color: theme.status.warning, children: uiState.transientMessage.text });
  }
  if (uiState.ctrlDPressedOnce) {
    return /* @__PURE__ */ (0, import_jsx_runtime109.jsx)(Text, { color: theme.status.warning, children: "Press Ctrl+D again to exit." });
  }
  if (inputState.showEscapePrompt) {
    const isPromptEmpty = inputState.buffer.text.length === 0;
    const hasHistory = uiState.history.length > 0;
    if (isPromptEmpty && !hasHistory) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime109.jsxs)(Text, { color: theme.text.secondary, children: [
      "Press Esc again to ",
      isPromptEmpty ? "rewind" : "clear prompt",
      "."
    ] });
  }
  if (uiState.transientMessage?.type === "hint" /* Hint */ && uiState.transientMessage.text) {
    return /* @__PURE__ */ (0, import_jsx_runtime109.jsx)(Text, { color: theme.text.secondary, children: uiState.transientMessage.text });
  }
  if (uiState.queueErrorMessage) {
    return /* @__PURE__ */ (0, import_jsx_runtime109.jsx)(Text, { color: theme.status.error, children: uiState.queueErrorMessage });
  }
  if (uiState.showIsExpandableHint) {
    const action = uiState.constrainHeight ? "show more" : "collapse";
    return /* @__PURE__ */ (0, import_jsx_runtime109.jsxs)(Text, { color: theme.text.secondary, children: [
      "Press Ctrl+O to ",
      action,
      " lines of the last response"
    ] });
  }
  return null;
};

// packages/cli/src/ui/components/DetailedMessagesDisplay.tsx
var import_react72 = __toESM(require_react(), 1);

// packages/cli/src/ui/hooks/useConsoleMessages.ts
var import_react71 = __toESM(require_react(), 1);
var MAX_CONSOLE_MESSAGES = 1e3;
var globalConsoleMessages = [];
var globalErrorCount = 0;
var listeners = /* @__PURE__ */ new Set();
var messageQueue = [];
var timeoutId = null;
function initializeConsoleStore() {
  if (timeoutId) {
    clearTimeout(timeoutId);
    timeoutId = null;
  }
  messageQueue = [];
  globalConsoleMessages = [];
  globalErrorCount = 0;
  notifyListeners();
  coreEvents.off(CoreEvent.ConsoleLog, handleConsoleLog);
  coreEvents.off(CoreEvent.Output, handleOutput);
  coreEvents.on(CoreEvent.ConsoleLog, handleConsoleLog);
  coreEvents.on(CoreEvent.Output, handleOutput);
}
function notifyListeners() {
  for (const listener of listeners) {
    listener();
  }
}
function processQueue() {
  if (messageQueue.length === 0) return;
  const newMessages = [...globalConsoleMessages];
  for (const queuedMessage of messageQueue) {
    if (queuedMessage.type === "error") {
      globalErrorCount++;
    }
    const prev = newMessages[newMessages.length - 1];
    if (prev && prev.type === queuedMessage.type && prev.content === queuedMessage.content) {
      newMessages[newMessages.length - 1] = {
        ...prev,
        count: prev.count + 1
      };
    } else {
      newMessages.push({ ...queuedMessage, count: 1 });
    }
  }
  globalConsoleMessages = newMessages.length > MAX_CONSOLE_MESSAGES ? newMessages.slice(-MAX_CONSOLE_MESSAGES) : newMessages;
  messageQueue = [];
  timeoutId = null;
  notifyListeners();
}
function handleNewMessage(message) {
  messageQueue.push(message);
  if (!timeoutId) {
    timeoutId = setTimeout(processQueue, 50);
  }
}
function subscribe(listener) {
  listeners.add(listener);
  return () => {
    listeners.delete(listener);
  };
}
function getConsoleMessagesSnapshot() {
  return globalConsoleMessages;
}
function getErrorCountSnapshot() {
  return globalErrorCount;
}
var handleConsoleLog = (payload) => {
  let content = payload.content;
  const MAX_CONSOLE_MSG_LENGTH = 1e4;
  if (content.length > MAX_CONSOLE_MSG_LENGTH) {
    content = content.slice(0, MAX_CONSOLE_MSG_LENGTH) + `... [Truncated ${content.length - MAX_CONSOLE_MSG_LENGTH} characters]`;
  }
  handleNewMessage({
    type: payload.type,
    content,
    count: 1
  });
};
var handleOutput = (payload) => {
  let content = typeof payload.chunk === "string" ? payload.chunk : new TextDecoder().decode(payload.chunk);
  const MAX_OUTPUT_CHUNK_LENGTH = 1e4;
  if (content.length > MAX_OUTPUT_CHUNK_LENGTH) {
    content = content.slice(0, MAX_OUTPUT_CHUNK_LENGTH) + `... [Truncated ${content.length - MAX_OUTPUT_CHUNK_LENGTH} characters]`;
  }
  handleNewMessage({ type: "log", content, count: 1 });
};
function useConsoleMessages() {
  return (0, import_react71.useSyncExternalStore)(subscribe, getConsoleMessagesSnapshot);
}
function useErrorCount() {
  const errorCount = (0, import_react71.useSyncExternalStore)(subscribe, getErrorCountSnapshot);
  const clearErrorCount = (0, import_react71.useCallback)(() => {
    globalErrorCount = 0;
    notifyListeners();
  }, []);
  return { errorCount, clearErrorCount };
}

// packages/cli/src/ui/components/DetailedMessagesDisplay.tsx
var import_jsx_runtime110 = __toESM(require_jsx_runtime(), 1);
var iconBoxWidth = 3;
var DetailedMessagesDisplay = ({ maxHeight, width, hasFocus }) => {
  const scrollableListRef = (0, import_react72.useRef)(null);
  const consoleMessages = useConsoleMessages();
  const config = useConfig();
  const messages = (0, import_react72.useMemo)(() => {
    if (config.getDebugMode()) {
      return consoleMessages;
    }
    return consoleMessages.filter((msg) => msg.type !== "debug");
  }, [consoleMessages, config]);
  const borderAndPadding = 3;
  const estimatedItemHeight = (0, import_react72.useCallback)(
    (index) => {
      const msg = messages[index];
      if (!msg) {
        return 1;
      }
      const textWidth = width - borderAndPadding - iconBoxWidth;
      if (textWidth <= 0) {
        return 1;
      }
      const lines = Math.ceil((msg.content?.length || 1) / textWidth);
      return Math.max(1, lines);
    },
    [width, messages]
  );
  if (messages.length === 0) {
    return null;
  }
  return /* @__PURE__ */ (0, import_jsx_runtime110.jsxs)(
    Box_default,
    {
      flexDirection: "column",
      marginTop: 1,
      borderStyle: "round",
      borderColor: theme.border.default,
      paddingLeft: 1,
      width,
      height: maxHeight,
      flexShrink: 0,
      flexGrow: 0,
      overflow: "hidden",
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime110.jsx)(Box_default, { marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime110.jsxs)(Text, { bold: true, color: theme.text.primary, children: [
          "Debug Console ",
          /* @__PURE__ */ (0, import_jsx_runtime110.jsx)(Text, { color: theme.text.secondary, children: "(F12 to close)" })
        ] }) }),
        /* @__PURE__ */ (0, import_jsx_runtime110.jsx)(Box_default, { height: maxHeight, width: width - borderAndPadding, children: /* @__PURE__ */ (0, import_jsx_runtime110.jsx)(
          ScrollableListWithForwardRef,
          {
            ref: scrollableListRef,
            data: messages,
            renderItem: ({ item: msg }) => {
              let textColor = theme.text.primary;
              let icon = "\u2139";
              switch (msg.type) {
                case "warn":
                  textColor = theme.status.warning;
                  icon = "\u26A0";
                  break;
                case "error":
                  textColor = theme.status.error;
                  icon = "\u2716";
                  break;
                case "debug":
                  textColor = theme.text.secondary;
                  icon = "\u{1F50D}";
                  break;
                case "log":
                default:
                  break;
              }
              return /* @__PURE__ */ (0, import_jsx_runtime110.jsxs)(Box_default, { flexDirection: "row", children: [
                /* @__PURE__ */ (0, import_jsx_runtime110.jsx)(Box_default, { minWidth: iconBoxWidth, flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime110.jsx)(Text, { color: textColor, children: icon }) }),
                /* @__PURE__ */ (0, import_jsx_runtime110.jsxs)(Text, { color: textColor, wrap: "wrap", children: [
                  msg.content,
                  msg.count && msg.count > 1 && /* @__PURE__ */ (0, import_jsx_runtime110.jsxs)(Text, { color: theme.text.secondary, children: [
                    " (x",
                    msg.count,
                    ")"
                  ] })
                ] })
              ] });
            },
            keyExtractor: (item, index) => `${item.content}-${index}`,
            estimatedItemHeight,
            hasFocus,
            initialScrollIndex: Number.MAX_SAFE_INTEGER
          }
        ) })
      ]
    }
  );
};

// packages/cli/src/ui/components/shared/SectionHeader.tsx
var import_jsx_runtime111 = __toESM(require_jsx_runtime(), 1);
var SectionHeader = ({
  title,
  subtitle
}) => /* @__PURE__ */ (0, import_jsx_runtime111.jsxs)(Box_default, { width: "100%", flexDirection: "column", overflow: "hidden", children: [
  /* @__PURE__ */ (0, import_jsx_runtime111.jsx)(
    Box_default,
    {
      width: "100%",
      borderStyle: "single",
      borderTop: true,
      borderBottom: false,
      borderLeft: false,
      borderRight: false,
      borderColor: theme.text.secondary
    }
  ),
  /* @__PURE__ */ (0, import_jsx_runtime111.jsxs)(Box_default, { flexDirection: "row", children: [
    /* @__PURE__ */ (0, import_jsx_runtime111.jsx)(Text, { color: theme.text.primary, bold: true, wrap: "truncate-end", children: title }),
    subtitle && /* @__PURE__ */ (0, import_jsx_runtime111.jsx)(Text, { color: theme.text.secondary, wrap: "truncate-end", children: subtitle })
  ] })
] });

// packages/cli/src/ui/components/ShortcutsHelp.tsx
var import_jsx_runtime112 = __toESM(require_jsx_runtime(), 1);
var buildShortcutItems = () => [
  { key: "!", description: "shell mode" },
  { key: "@", description: "select file or folder" },
  { key: "Double Esc", description: "clear & rewind" },
  { key: formatCommand("app.focusShellInput" /* FOCUS_SHELL_INPUT */), description: "focus UI" },
  { key: formatCommand("app.toggleYolo" /* TOGGLE_YOLO */), description: "YOLO mode" },
  {
    key: formatCommand("app.cycleApprovalMode" /* CYCLE_APPROVAL_MODE */),
    description: "cycle mode"
  },
  {
    key: formatCommand("input.paste" /* PASTE_CLIPBOARD */),
    description: "paste images"
  },
  {
    key: formatCommand("app.toggleMarkdown" /* TOGGLE_MARKDOWN */),
    description: "raw markdown mode"
  },
  {
    key: formatCommand("history.search.start" /* REVERSE_SEARCH */),
    description: "reverse-search history"
  },
  {
    key: formatCommand("input.openExternalEditor" /* OPEN_EXTERNAL_EDITOR */),
    description: "open external editor"
  }
];
var Shortcut = ({ item }) => /* @__PURE__ */ (0, import_jsx_runtime112.jsxs)(Box_default, { flexDirection: "row", children: [
  /* @__PURE__ */ (0, import_jsx_runtime112.jsx)(Box_default, { flexShrink: 0, marginRight: 1, children: /* @__PURE__ */ (0, import_jsx_runtime112.jsx)(Text, { color: theme.text.accent, children: item.key }) }),
  /* @__PURE__ */ (0, import_jsx_runtime112.jsx)(Box_default, { flexGrow: 1, children: /* @__PURE__ */ (0, import_jsx_runtime112.jsx)(Text, { color: theme.text.primary, children: item.description }) })
] });
var ShortcutsHelp = () => {
  const { terminalWidth } = useUIState();
  const isNarrow = isNarrowWidth(terminalWidth);
  const items = buildShortcutItems();
  const itemsForDisplay = isNarrow ? items : [
    // Keep first column stable: !, @, Esc Esc, Tab Tab.
    items[0],
    items[5],
    items[6],
    items[1],
    items[4],
    items[7],
    items[2],
    items[8],
    items[9],
    items[3]
  ];
  return /* @__PURE__ */ (0, import_jsx_runtime112.jsxs)(Box_default, { flexDirection: "column", width: "100%", children: [
    /* @__PURE__ */ (0, import_jsx_runtime112.jsx)(SectionHeader, { title: " Shortcuts", subtitle: " See /help for more" }),
    /* @__PURE__ */ (0, import_jsx_runtime112.jsx)(Box_default, { flexDirection: "row", flexWrap: "wrap", paddingLeft: 1, paddingRight: 2, children: itemsForDisplay.map((item, index) => /* @__PURE__ */ (0, import_jsx_runtime112.jsx)(
      Box_default,
      {
        width: isNarrow ? "100%" : "33%",
        paddingRight: isNarrow ? 0 : 2,
        children: /* @__PURE__ */ (0, import_jsx_runtime112.jsx)(Shortcut, { item })
      },
      `${item.key}-${index}`
    )) })
  ] });
};

// packages/cli/src/ui/components/InputPrompt.tsx
var import_react85 = __toESM(require_react(), 1);

// packages/cli/src/ui/components/SuggestionsDisplay.tsx
var import_jsx_runtime113 = __toESM(require_jsx_runtime(), 1);
var MAX_SUGGESTIONS_TO_SHOW = 8;
function SuggestionsDisplay({
  suggestions,
  activeIndex,
  isLoading,
  width,
  scrollOffset,
  userInput,
  mode,
  expandedIndex
}) {
  if (isLoading) {
    return /* @__PURE__ */ (0, import_jsx_runtime113.jsx)(Box_default, { paddingX: 1, width, children: /* @__PURE__ */ (0, import_jsx_runtime113.jsx)(Text, { color: "gray", children: "Loading suggestions..." }) });
  }
  if (suggestions.length === 0) {
    return null;
  }
  const startIndex = scrollOffset;
  const endIndex = Math.min(
    scrollOffset + MAX_SUGGESTIONS_TO_SHOW,
    suggestions.length
  );
  const visibleSuggestions = suggestions.slice(startIndex, endIndex);
  const COMMAND_KIND_SUFFIX = {
    ["mcp-prompt" /* MCP_PROMPT */]: " [MCP]",
    ["agent" /* AGENT */]: " [Agent]"
  };
  const getFullLabel = (s) => s.label + (s.commandKind ? COMMAND_KIND_SUFFIX[s.commandKind] ?? "" : "");
  const maxLabelLength = Math.max(
    ...suggestions.map((s) => getFullLabel(s).length)
  );
  const commandColumnWidth = mode === "slash" ? Math.min(maxLabelLength, Math.floor(width * 0.5)) : 0;
  return /* @__PURE__ */ (0, import_jsx_runtime113.jsxs)(Box_default, { flexDirection: "column", paddingX: 1, width, children: [
    scrollOffset > 0 && /* @__PURE__ */ (0, import_jsx_runtime113.jsx)(Text, { color: theme.text.primary, children: "\u25B2" }),
    visibleSuggestions.map((suggestion, index) => {
      const originalIndex = startIndex + index;
      const isActive = originalIndex === activeIndex;
      const isExpanded = originalIndex === expandedIndex;
      const textColor = isActive ? theme.ui.focus : theme.text.secondary;
      const isLong = suggestion.value.length >= MAX_WIDTH;
      const previousSectionTitle = suggestions[originalIndex - 1]?.sectionTitle;
      const shouldRenderSectionHeader = mode === "slash" && !!suggestion.sectionTitle && suggestion.sectionTitle !== previousSectionTitle;
      const labelElement = /* @__PURE__ */ (0, import_jsx_runtime113.jsx)(
        ExpandableText,
        {
          label: suggestion.value,
          matchedIndex: suggestion.matchedIndex,
          userInput,
          textColor,
          isExpanded
        }
      );
      return /* @__PURE__ */ (0, import_jsx_runtime113.jsxs)(
        Box_default,
        {
          flexDirection: "column",
          children: [
            shouldRenderSectionHeader && /* @__PURE__ */ (0, import_jsx_runtime113.jsxs)(Text, { color: theme.text.secondary, children: [
              "-- ",
              suggestion.sectionTitle,
              " --"
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime113.jsxs)(
              Box_default,
              {
                flexDirection: "row",
                backgroundColor: isActive ? theme.background.focus : void 0,
                children: [
                  /* @__PURE__ */ (0, import_jsx_runtime113.jsx)(
                    Box_default,
                    {
                      ...mode === "slash" ? { width: commandColumnWidth, flexShrink: 0 } : { flexShrink: 1 },
                      children: /* @__PURE__ */ (0, import_jsx_runtime113.jsxs)(Box_default, { children: [
                        labelElement,
                        suggestion.commandKind && COMMAND_KIND_SUFFIX[suggestion.commandKind] && /* @__PURE__ */ (0, import_jsx_runtime113.jsx)(Text, { color: textColor, children: COMMAND_KIND_SUFFIX[suggestion.commandKind] })
                      ] })
                    }
                  ),
                  suggestion.description && /* @__PURE__ */ (0, import_jsx_runtime113.jsx)(Box_default, { flexGrow: 1, paddingLeft: 3, children: /* @__PURE__ */ (0, import_jsx_runtime113.jsx)(Text, { color: textColor, wrap: "truncate", children: sanitizeForDisplay(suggestion.description, 100) }) }),
                  isActive && isLong && /* @__PURE__ */ (0, import_jsx_runtime113.jsx)(Box_default, { width: 3, flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime113.jsx)(Text, { color: Colors.Gray, children: isExpanded ? " \u2190 " : " \u2192 " }) })
                ]
              }
            )
          ]
        },
        `${suggestion.value}-${originalIndex}`
      );
    }),
    endIndex < suggestions.length && /* @__PURE__ */ (0, import_jsx_runtime113.jsx)(Text, { color: "gray", children: "\u25BC" }),
    suggestions.length > MAX_SUGGESTIONS_TO_SHOW && /* @__PURE__ */ (0, import_jsx_runtime113.jsxs)(Text, { color: "gray", children: [
      "(",
      activeIndex + 1,
      "/",
      suggestions.length,
      ")"
    ] })
  ] });
}

// packages/cli/src/ui/hooks/useInputHistory.ts
var import_react73 = __toESM(require_react(), 1);
function useInputHistory({
  userMessages,
  onSubmit,
  isActive,
  currentQuery,
  currentCursorOffset,
  onChange
}) {
  const [historyIndex, setHistoryIndex] = (0, import_react73.useState)(-1);
  const previousHistoryIndexRef = (0, import_react73.useRef)(void 0);
  const historyCacheRef = (0, import_react73.useRef)({});
  const resetHistoryNav = (0, import_react73.useCallback)(() => {
    setHistoryIndex(-1);
    previousHistoryIndexRef.current = void 0;
    historyCacheRef.current = {};
  }, []);
  const handleSubmit = (0, import_react73.useCallback)(
    (value) => {
      const trimmedValue = value.trim();
      if (trimmedValue) {
        onSubmit(trimmedValue);
      }
      resetHistoryNav();
    },
    [onSubmit, resetHistoryNav]
  );
  const navigateTo = (0, import_react73.useCallback)(
    (nextIndex, defaultCursor) => {
      const prevIndexBeforeMove = historyIndex;
      historyCacheRef.current[prevIndexBeforeMove] = {
        text: currentQuery,
        offset: currentCursorOffset
      };
      setHistoryIndex(nextIndex);
      const saved = historyCacheRef.current[nextIndex];
      const isReturningToPrevious = nextIndex === -1 || nextIndex === previousHistoryIndexRef.current;
      if (isReturningToPrevious && saved && saved.offset > 0 && saved.offset < cpLen(saved.text)) {
        onChange(saved.text, saved.offset);
      } else if (nextIndex === -1) {
        onChange(saved ? saved.text : "", defaultCursor);
      } else {
        if (saved) {
          onChange(saved.text, defaultCursor);
        } else {
          const newValue = userMessages[userMessages.length - 1 - nextIndex];
          onChange(newValue, defaultCursor);
        }
      }
      previousHistoryIndexRef.current = prevIndexBeforeMove;
    },
    [historyIndex, currentQuery, currentCursorOffset, userMessages, onChange]
  );
  const navigateUp = (0, import_react73.useCallback)(() => {
    if (!isActive) return false;
    if (userMessages.length === 0) return false;
    if (historyIndex < userMessages.length - 1) {
      navigateTo(historyIndex + 1, "start");
      return true;
    }
    return false;
  }, [historyIndex, userMessages, isActive, navigateTo]);
  const navigateDown = (0, import_react73.useCallback)(() => {
    if (!isActive) return false;
    if (historyIndex === -1) return false;
    navigateTo(historyIndex - 1, "end");
    return true;
  }, [historyIndex, isActive, navigateTo]);
  return {
    handleSubmit,
    navigateUp,
    navigateDown
  };
}

// packages/cli/src/ui/components/InputPrompt.tsx
var import_chalk3 = __toESM(require_source(), 1);

// packages/cli/src/ui/hooks/useShellHistory.ts
var import_react74 = __toESM(require_react(), 1);
import * as fs2 from "node:fs/promises";
import * as path7 from "node:path";
var MAX_HISTORY_LENGTH = 100;
async function getHistoryFilePath(projectRoot, configStorage) {
  const storage = configStorage ?? new Storage(projectRoot);
  await storage.initialize();
  return storage.getHistoryFilePath();
}
async function readHistoryFile(filePath) {
  try {
    const text = await fs2.readFile(filePath, "utf-8");
    const result = [];
    let cur = "";
    for (const raw of text.split(/\r?\n/)) {
      if (!raw.trim()) continue;
      const line = raw;
      const m = cur.match(/(\\+)$/);
      if (m && m[1].length % 2) {
        cur = cur.slice(0, -1) + " " + line;
      } else {
        if (cur) result.push(cur);
        cur = line;
      }
    }
    if (cur) result.push(cur);
    return result;
  } catch (err) {
    if (isNodeError(err) && err.code === "ENOENT") return [];
    debugLogger.error("Error reading history:", err);
    return [];
  }
}
async function writeHistoryFile(filePath, history) {
  try {
    await fs2.mkdir(path7.dirname(filePath), { recursive: true });
    await fs2.writeFile(filePath, history.join("\n"));
  } catch (error) {
    debugLogger.error("Error writing shell history:", error);
  }
}
function useShellHistory(projectRoot, storage) {
  const [history, setHistory] = (0, import_react74.useState)([]);
  const [historyIndex, setHistoryIndex] = (0, import_react74.useState)(-1);
  const [historyFilePath, setHistoryFilePath] = (0, import_react74.useState)(null);
  (0, import_react74.useEffect)(() => {
    async function loadHistory() {
      const filePath = await getHistoryFilePath(projectRoot, storage);
      setHistoryFilePath(filePath);
      const loadedHistory = await readHistoryFile(filePath);
      setHistory(loadedHistory.reverse());
    }
    loadHistory();
  }, [projectRoot, storage]);
  const addCommandToHistory = (0, import_react74.useCallback)(
    (command) => {
      if (!command.trim() || !historyFilePath) {
        return;
      }
      const newHistory = [command, ...history.filter((c2) => c2 !== command)].slice(0, MAX_HISTORY_LENGTH).filter(Boolean);
      setHistory(newHistory);
      writeHistoryFile(historyFilePath, [...newHistory].reverse());
      setHistoryIndex(-1);
    },
    [history, historyFilePath]
  );
  const getPreviousCommand = (0, import_react74.useCallback)(() => {
    if (history.length === 0) {
      return null;
    }
    const newIndex = Math.min(historyIndex + 1, history.length - 1);
    setHistoryIndex(newIndex);
    return history[newIndex] ?? null;
  }, [history, historyIndex]);
  const getNextCommand = (0, import_react74.useCallback)(() => {
    if (historyIndex < 0) {
      return null;
    }
    const newIndex = historyIndex - 1;
    setHistoryIndex(newIndex);
    if (newIndex < 0) {
      return "";
    }
    return history[newIndex] ?? null;
  }, [history, historyIndex]);
  const resetHistoryPosition = (0, import_react74.useCallback)(() => {
    setHistoryIndex(-1);
  }, []);
  return {
    history,
    addCommandToHistory,
    getPreviousCommand,
    getNextCommand,
    resetHistoryPosition
  };
}

// packages/cli/src/ui/hooks/useReverseSearchCompletion.tsx
var import_react76 = __toESM(require_react(), 1);

// packages/cli/src/ui/hooks/useCompletion.ts
var import_react75 = __toESM(require_react(), 1);
function useCompletion() {
  const [suggestions, setSuggestions] = (0, import_react75.useState)([]);
  const [activeSuggestionIndex, setActiveSuggestionIndex] = (0, import_react75.useState)(-1);
  const [visibleStartIndex, setVisibleStartIndex] = (0, import_react75.useState)(0);
  const [isLoadingSuggestions, setIsLoadingSuggestions] = (0, import_react75.useState)(false);
  const [isPerfectMatch, setIsPerfectMatch] = (0, import_react75.useState)(false);
  const resetCompletionState = (0, import_react75.useCallback)(() => {
    setSuggestions([]);
    setActiveSuggestionIndex(-1);
    setVisibleStartIndex(0);
    setIsLoadingSuggestions(false);
    setIsPerfectMatch(false);
  }, []);
  const navigateUp = (0, import_react75.useCallback)(() => {
    if (suggestions.length === 0) return;
    setActiveSuggestionIndex((prevActiveIndex) => {
      const newActiveIndex = prevActiveIndex <= 0 ? suggestions.length - 1 : prevActiveIndex - 1;
      setVisibleStartIndex((prevVisibleStart) => {
        if (newActiveIndex === suggestions.length - 1 && suggestions.length > MAX_SUGGESTIONS_TO_SHOW) {
          return Math.max(0, suggestions.length - MAX_SUGGESTIONS_TO_SHOW);
        }
        if (newActiveIndex < prevVisibleStart) {
          return newActiveIndex;
        }
        return prevVisibleStart;
      });
      return newActiveIndex;
    });
  }, [suggestions.length]);
  const navigateDown = (0, import_react75.useCallback)(() => {
    if (suggestions.length === 0) return;
    setActiveSuggestionIndex((prevActiveIndex) => {
      const newActiveIndex = prevActiveIndex >= suggestions.length - 1 ? 0 : prevActiveIndex + 1;
      setVisibleStartIndex((prevVisibleStart) => {
        if (newActiveIndex === 0 && suggestions.length > MAX_SUGGESTIONS_TO_SHOW) {
          return 0;
        }
        const visibleEndIndex = prevVisibleStart + MAX_SUGGESTIONS_TO_SHOW;
        if (newActiveIndex >= visibleEndIndex) {
          return newActiveIndex - MAX_SUGGESTIONS_TO_SHOW + 1;
        }
        return prevVisibleStart;
      });
      return newActiveIndex;
    });
  }, [suggestions.length]);
  return {
    suggestions,
    activeSuggestionIndex,
    visibleStartIndex,
    isLoadingSuggestions,
    isPerfectMatch,
    setSuggestions,
    setActiveSuggestionIndex,
    setVisibleStartIndex,
    setIsLoadingSuggestions,
    setIsPerfectMatch,
    resetCompletionState,
    navigateUp,
    navigateDown
  };
}

// packages/cli/src/ui/hooks/useReverseSearchCompletion.tsx
function useDebouncedValue(value, delay2 = 200) {
  const [debounced, setDebounced] = (0, import_react76.useState)(value);
  (0, import_react76.useEffect)(() => {
    const handle = setTimeout(() => setDebounced(value), delay2);
    return () => clearTimeout(handle);
  }, [value, delay2]);
  return debounced;
}
function useReverseSearchCompletion(buffer, history, reverseSearchActive) {
  const {
    suggestions,
    activeSuggestionIndex,
    visibleStartIndex,
    isLoadingSuggestions,
    setSuggestions,
    setActiveSuggestionIndex,
    resetCompletionState,
    navigateUp,
    navigateDown,
    setVisibleStartIndex
  } = useCompletion();
  const debouncedQuery = useDebouncedValue(buffer.text, 100);
  const prevQueryRef = (0, import_react76.useRef)("");
  const prevMatchesRef = (0, import_react76.useRef)([]);
  (0, import_react76.useEffect)(() => {
    if (reverseSearchActive) {
      prevQueryRef.current = "";
      prevMatchesRef.current = [];
    }
  }, [reverseSearchActive]);
  (0, import_react76.useEffect)(() => {
    prevQueryRef.current = "";
    prevMatchesRef.current = [];
  }, [history]);
  const searchHistory = (0, import_react76.useCallback)(
    (query, items) => {
      const out = [];
      for (let i = 0; i < items.length; i++) {
        const cmd = items[i];
        const idx = cmd.toLowerCase().indexOf(query);
        if (idx !== -1) {
          out.push({ label: cmd, value: cmd, matchedIndex: idx });
        }
      }
      return out;
    },
    []
  );
  const matches = (0, import_react76.useMemo)(() => {
    if (!reverseSearchActive) return [];
    if (debouncedQuery.length === 0)
      return history.map((cmd) => ({
        label: cmd,
        value: cmd,
        matchedIndex: -1
      }));
    const query = debouncedQuery.toLowerCase();
    const canUseCache = prevQueryRef.current && query.startsWith(prevQueryRef.current) && prevMatchesRef.current.length > 0;
    const source2 = canUseCache ? prevMatchesRef.current.map((m) => m.value) : history;
    return searchHistory(query, source2);
  }, [debouncedQuery, history, reverseSearchActive, searchHistory]);
  (0, import_react76.useEffect)(() => {
    if (!reverseSearchActive) {
      resetCompletionState();
      return;
    }
    setSuggestions(matches);
    const hasAny = matches.length > 0;
    setActiveSuggestionIndex(hasAny ? 0 : -1);
    setVisibleStartIndex(0);
    prevQueryRef.current = debouncedQuery.toLowerCase();
    prevMatchesRef.current = matches;
  }, [
    debouncedQuery,
    matches,
    reverseSearchActive,
    setSuggestions,
    setActiveSuggestionIndex,
    setVisibleStartIndex,
    resetCompletionState
  ]);
  const showSuggestions = reverseSearchActive && (isLoadingSuggestions || suggestions.length > 0);
  const handleAutocomplete = (0, import_react76.useCallback)(
    (i) => {
      if (i < 0 || i >= suggestions.length) return;
      buffer.setText(suggestions[i].value);
      resetCompletionState();
    },
    [buffer, suggestions, resetCompletionState]
  );
  return {
    suggestions,
    activeSuggestionIndex,
    visibleStartIndex,
    showSuggestions,
    isLoadingSuggestions,
    navigateUp,
    navigateDown,
    handleAutocomplete,
    resetCompletionState
  };
}

// packages/cli/src/ui/hooks/useCommandCompletion.tsx
var import_react81 = __toESM(require_react(), 1);

// packages/cli/src/ui/hooks/useAtCompletion.ts
var import_react77 = __toESM(require_react(), 1);
import { setTimeout as setTimeoutPromise } from "node:timers/promises";
import * as path8 from "node:path";
var DEFAULT_SEARCH_TIMEOUT_MS = 5e3;
var initialState3 = {
  status: "idle" /* IDLE */,
  suggestions: [],
  isLoading: false,
  pattern: null
};
function atCompletionReducer(state, action) {
  switch (action.type) {
    case "INITIALIZE":
      return {
        ...state,
        status: "initializing" /* INITIALIZING */,
        isLoading: true
      };
    case "INITIALIZE_SUCCESS":
      return { ...state, status: "ready" /* READY */, isLoading: false };
    case "SEARCH":
      return {
        ...state,
        status: "searching" /* SEARCHING */,
        pattern: action.payload
      };
    case "SEARCH_SUCCESS":
      return {
        ...state,
        status: "ready" /* READY */,
        suggestions: action.payload,
        isLoading: false
      };
    case "SET_LOADING":
      if (state.status === "searching" /* SEARCHING */) {
        return { ...state, isLoading: action.payload, suggestions: [] };
      }
      return state;
    case "ERROR":
      return {
        ...state,
        status: "error" /* ERROR */,
        isLoading: false,
        suggestions: []
      };
    case "RESET":
      return initialState3;
    default:
      return state;
  }
}
function buildResourceCandidates(config) {
  const registry = config?.getResourceRegistry?.();
  if (!registry) {
    return [];
  }
  const resources = registry.getAllResources().map((resource) => {
    const prefixedUri = `${resource.serverName}:${resource.uri}`;
    return {
      // Include prefixedUri in searchKey so users can search by the displayed format
      searchKey: `${prefixedUri} ${resource.name ?? ""}`.toLowerCase(),
      suggestion: {
        label: prefixedUri,
        value: prefixedUri
      }
    };
  });
  return resources;
}
function buildAgentCandidates(config) {
  const registry = config?.getAgentRegistry?.();
  if (!registry) {
    return [];
  }
  return registry.getAllDefinitions().map((def) => ({
    label: def.name,
    value: def.name,
    commandKind: "agent" /* AGENT */
  }));
}
async function searchResourceCandidates(pattern, candidates) {
  if (candidates.length === 0) {
    return [];
  }
  const normalizedPattern = pattern.toLowerCase();
  if (!normalizedPattern) {
    return candidates.slice(0, MAX_SUGGESTIONS_TO_SHOW).map((candidate) => candidate.suggestion);
  }
  const fzf = new AsyncFzf(candidates, {
    selector: (candidate) => candidate.searchKey
  });
  const results = await fzf.find(normalizedPattern, {
    limit: MAX_SUGGESTIONS_TO_SHOW * 3
  });
  return results.map(
    (result) => result.item.suggestion
  );
}
async function searchAgentCandidates(pattern, candidates) {
  if (candidates.length === 0) {
    return [];
  }
  const normalizedPattern = pattern.toLowerCase();
  if (!normalizedPattern) {
    return candidates.slice(0, MAX_SUGGESTIONS_TO_SHOW);
  }
  const fzf = new AsyncFzf(candidates, {
    selector: (s) => s.label
  });
  const results = await fzf.find(normalizedPattern, {
    limit: MAX_SUGGESTIONS_TO_SHOW
  });
  return results.map((r2) => r2.item);
}
function useAtCompletion(props) {
  const {
    enabled,
    pattern,
    config,
    cwd: cwd5,
    setSuggestions,
    setIsLoadingSuggestions
  } = props;
  const [state, dispatch] = (0, import_react77.useReducer)(atCompletionReducer, initialState3);
  const fileSearchMap = (0, import_react77.useRef)(/* @__PURE__ */ new Map());
  const initEpoch = (0, import_react77.useRef)(0);
  const searchAbortController = (0, import_react77.useRef)(null);
  const slowSearchTimer = (0, import_react77.useRef)(null);
  (0, import_react77.useEffect)(() => {
    setSuggestions(state.suggestions);
  }, [state.suggestions, setSuggestions]);
  (0, import_react77.useEffect)(() => {
    setIsLoadingSuggestions(state.isLoading);
  }, [state.isLoading, setIsLoadingSuggestions]);
  const resetFileSearchState = () => {
    fileSearchMap.current.clear();
    initEpoch.current += 1;
    dispatch({ type: "RESET" });
  };
  (0, import_react77.useEffect)(() => {
    resetFileSearchState();
  }, [cwd5, config]);
  (0, import_react77.useEffect)(() => {
    const workspaceContext = config?.getWorkspaceContext?.();
    if (!workspaceContext) return;
    const unsubscribe = workspaceContext.onDirectoriesChanged(resetFileSearchState);
    return unsubscribe;
  }, [config]);
  (0, import_react77.useEffect)(() => {
    if (!enabled) {
      if (state.status === "ready" /* READY */ || state.status === "error" /* ERROR */) {
        dispatch({ type: "RESET" });
      }
      return;
    }
    if (pattern === null) {
      dispatch({ type: "RESET" });
      return;
    }
    if (state.status === "idle" /* IDLE */) {
      dispatch({ type: "INITIALIZE" });
    } else if ((state.status === "ready" /* READY */ || state.status === "searching" /* SEARCHING */) && pattern.toLowerCase() !== state.pattern) {
      dispatch({ type: "SEARCH", payload: pattern.toLowerCase() });
    }
  }, [enabled, pattern, state.status, state.pattern]);
  (0, import_react77.useEffect)(() => {
    const initialize = async () => {
      const currentEpoch = initEpoch.current;
      try {
        const directories = config?.getWorkspaceContext?.()?.getDirectories() ?? [cwd5];
        const initPromises = [];
        for (const dir of directories) {
          if (fileSearchMap.current.has(dir)) continue;
          const searcher = FileSearchFactory.create({
            projectRoot: dir,
            ignoreDirs: [],
            fileDiscoveryService: new FileDiscoveryService(
              dir,
              config?.getFileFilteringOptions()
            ),
            cache: true,
            cacheTtl: 30,
            enableRecursiveFileSearch: config?.getEnableRecursiveFileSearch() ?? true,
            enableFuzzySearch: config?.getFileFilteringEnableFuzzySearch() ?? true,
            maxFiles: config?.getFileFilteringOptions()?.maxFileCount
          });
          initPromises.push(
            searcher.initialize().then(() => {
              if (initEpoch.current === currentEpoch) {
                fileSearchMap.current.set(dir, searcher);
              }
            })
          );
        }
        await Promise.all(initPromises);
        if (initEpoch.current !== currentEpoch) return;
        dispatch({ type: "INITIALIZE_SUCCESS" });
        if (state.pattern !== null) {
          dispatch({ type: "SEARCH", payload: state.pattern });
        }
      } catch {
        if (initEpoch.current === currentEpoch) {
          dispatch({ type: "ERROR" });
        }
      }
    };
    const search = async () => {
      if (fileSearchMap.current.size === 0 || state.pattern === null) {
        return;
      }
      const currentPattern = state.pattern;
      if (slowSearchTimer.current) {
        clearTimeout(slowSearchTimer.current);
      }
      const controller = new AbortController();
      searchAbortController.current = controller;
      slowSearchTimer.current = setTimeout(() => {
        dispatch({ type: "SET_LOADING", payload: true });
      }, 200);
      const timeoutMs = config?.getFileFilteringOptions()?.searchTimeout ?? DEFAULT_SEARCH_TIMEOUT_MS;
      (async () => {
        try {
          await setTimeoutPromise(timeoutMs, void 0, {
            signal: controller.signal
          });
          controller.abort();
        } catch {
        }
      })();
      try {
        const directories = config?.getWorkspaceContext?.()?.getDirectories() ?? [cwd5];
        const cwdRealpath = directories[0];
        const allSearchPromises = [...fileSearchMap.current.entries()].map(
          async ([dir, searcher]) => {
            const results = await searcher.search(currentPattern, {
              signal: controller.signal,
              maxResults: MAX_SUGGESTIONS_TO_SHOW * 3
            });
            if (dir !== cwdRealpath) {
              return results.map((p) => path8.join(dir, p));
            }
            return results;
          }
        );
        const allResults = await Promise.all(allSearchPromises);
        if (slowSearchTimer.current) {
          clearTimeout(slowSearchTimer.current);
        }
        if (controller.signal.aborted) {
          return;
        }
        const mergedResults = allResults.flat();
        const fileSuggestions = mergedResults.map((p) => ({
          label: p,
          value: escapePath(p)
        }));
        const resourceCandidates = buildResourceCandidates(config);
        const resourceSuggestions = (await searchResourceCandidates(
          currentPattern ?? "",
          resourceCandidates
        )).map((suggestion) => ({
          ...suggestion,
          label: suggestion.label.replace(/^@/, ""),
          value: suggestion.value.replace(/^@/, "")
        }));
        const agentCandidates = buildAgentCandidates(config);
        const agentSuggestions = await searchAgentCandidates(
          currentPattern ?? "",
          agentCandidates
        );
        if (controller.signal.aborted) {
          return;
        }
        const combinedSuggestions = [
          ...agentSuggestions,
          ...fileSuggestions,
          ...resourceSuggestions
        ];
        dispatch({ type: "SEARCH_SUCCESS", payload: combinedSuggestions });
      } catch (error) {
        if (!(error instanceof Error && error.name === "AbortError")) {
          dispatch({ type: "ERROR" });
        }
      } finally {
        controller.abort();
      }
    };
    if (state.status === "initializing" /* INITIALIZING */) {
      initialize();
    } else if (state.status === "searching" /* SEARCHING */) {
      search();
    }
    return () => {
      searchAbortController.current?.abort();
      if (slowSearchTimer.current) {
        clearTimeout(slowSearchTimer.current);
      }
    };
  }, [state.status, state.pattern, config, cwd5]);
}

// packages/cli/src/ui/hooks/useSlashCompletion.ts
var import_react78 = __toESM(require_react(), 1);
function logErrorSafely(error, context) {
  if (error instanceof Error) {
    debugLogger.warn(`[${context}]`, error);
  } else {
    debugLogger.warn(`[${context}] Non-error thrown:`, error);
  }
}
function matchesCommand(cmd, query) {
  return cmd.name.toLowerCase() === query.toLowerCase() || cmd.altNames?.some((alt) => alt.toLowerCase() === query.toLowerCase()) || false;
}
function useCommandParser(query, slashCommands) {
  return (0, import_react78.useMemo)(() => {
    if (!query) {
      return {
        hasTrailingSpace: false,
        commandPathParts: [],
        partial: "",
        currentLevel: slashCommands,
        leafCommand: null,
        isArgumentCompletion: false
      };
    }
    const fullPath = query.substring(1) || "";
    const hasTrailingSpace = !!query.endsWith(" ");
    const rawParts = fullPath.split(/\s+/).filter((p) => p);
    let commandPathParts = rawParts;
    let partial = "";
    if (!hasTrailingSpace && rawParts.length > 0) {
      partial = rawParts[rawParts.length - 1];
      commandPathParts = rawParts.slice(0, -1);
    }
    let currentLevel = slashCommands;
    let leafCommand = null;
    for (const part of commandPathParts) {
      if (!currentLevel) {
        leafCommand = null;
        currentLevel = [];
        break;
      }
      const found = currentLevel.find(
        (cmd) => matchesCommand(cmd, part)
      );
      if (found) {
        leafCommand = found;
        currentLevel = found.subCommands;
        if (found.kind === "mcp-prompt" /* MCP_PROMPT */) {
          break;
        }
      } else {
        leafCommand = null;
        currentLevel = [];
        break;
      }
    }
    const depth = commandPathParts.length;
    const isArgumentCompletion = !!(leafCommand?.completion && (hasTrailingSpace || rawParts.length > depth && depth > 0 && partial !== ""));
    return {
      hasTrailingSpace,
      commandPathParts,
      partial,
      currentLevel,
      leafCommand,
      isArgumentCompletion
    };
  }, [query, slashCommands]);
}
function useCommandSuggestions(query, parserResult, commandContext, getFzfForCommands, getPrefixSuggestions) {
  const [suggestions, setSuggestions] = (0, import_react78.useState)([]);
  const [isLoading, setIsLoading] = (0, import_react78.useState)(false);
  (0, import_react78.useEffect)(() => {
    const abortController = new AbortController();
    const { signal } = abortController;
    const {
      isArgumentCompletion,
      leafCommand,
      commandPathParts,
      partial,
      currentLevel
    } = parserResult;
    if (isArgumentCompletion) {
      const fetchAndSetSuggestions = async () => {
        if (signal.aborted) return;
        if (!leafCommand?.completion) {
          debugLogger.warn(
            "Attempted argument completion without completion function"
          );
          return;
        }
        const showLoading = leafCommand.showCompletionLoading !== false;
        if (showLoading) {
          setIsLoading(true);
        }
        try {
          const rawParts = [...commandPathParts];
          if (partial) rawParts.push(partial);
          const depth = commandPathParts.length;
          const argString = rawParts.slice(depth).join(" ");
          const results = await leafCommand.completion(
            {
              ...commandContext,
              invocation: {
                raw: query || `/${rawParts.join(" ")}`,
                name: leafCommand.name,
                args: argString
              }
            },
            argString
          ) || [];
          if (!signal.aborted) {
            const finalSuggestions = results.map((s) => ({
              label: s,
              value: s
            }));
            setSuggestions(finalSuggestions);
            setIsLoading(false);
          }
        } catch (error) {
          if (!signal.aborted) {
            logErrorSafely(error, "Argument completion");
            setSuggestions([]);
            setIsLoading(false);
          }
        }
      };
      fetchAndSetSuggestions();
      return () => abortController.abort();
    }
    const commandsToSearch = currentLevel || [];
    if (commandsToSearch.length > 0) {
      const performFuzzySearch = async () => {
        if (signal.aborted) return;
        let potentialSuggestions = [];
        if (partial === "") {
          potentialSuggestions = commandsToSearch.filter(
            (cmd) => cmd.description && !cmd.hidden
          );
        } else {
          const fzfInstance = getFzfForCommands(commandsToSearch);
          if (fzfInstance) {
            try {
              const fzfResults = await fzfInstance.fzf.find(partial);
              if (signal.aborted) return;
              const uniqueCommands = /* @__PURE__ */ new Set();
              fzfResults.forEach((result) => {
                const cmd = fzfInstance.commandMap.get(result.item);
                if (cmd && cmd.description) {
                  uniqueCommands.add(cmd);
                }
              });
              potentialSuggestions = Array.from(uniqueCommands);
            } catch (error) {
              logErrorSafely(
                error,
                "Fuzzy search - falling back to prefix matching"
              );
              potentialSuggestions = getPrefixSuggestions(
                commandsToSearch,
                partial
              );
            }
          } else {
            potentialSuggestions = getPrefixSuggestions(
              commandsToSearch,
              partial
            );
          }
        }
        if (!signal.aborted) {
          const lowerPartial = partial.toLowerCase();
          const sortedSuggestions = [...potentialSuggestions].sort((a, b) => {
            const aNameExact = a.name.toLowerCase() === lowerPartial;
            const bNameExact = b.name.toLowerCase() === lowerPartial;
            if (aNameExact && !bNameExact) return -1;
            if (!aNameExact && bNameExact) return 1;
            const aAltExact = a.altNames?.some((alt) => alt.toLowerCase() === lowerPartial) || false;
            const bAltExact = b.altNames?.some((alt) => alt.toLowerCase() === lowerPartial) || false;
            if (aAltExact && !bAltExact) return -1;
            if (!aAltExact && bAltExact) return 1;
            const aNamePrefix = a.name.toLowerCase().startsWith(lowerPartial);
            const bNamePrefix = b.name.toLowerCase().startsWith(lowerPartial);
            if (aNamePrefix && !bNamePrefix) return -1;
            if (!aNamePrefix && bNamePrefix) return 1;
            const aAltPrefix = a.altNames?.some(
              (alt) => alt.toLowerCase().startsWith(lowerPartial)
            ) || false;
            const bAltPrefix = b.altNames?.some(
              (alt) => alt.toLowerCase().startsWith(lowerPartial)
            ) || false;
            if (aAltPrefix && !bAltPrefix) return -1;
            if (!aAltPrefix && bAltPrefix) return 1;
            return 0;
          });
          const finalSuggestions = sortedSuggestions.map((cmd) => {
            const suggestion = {
              label: cmd.name,
              value: cmd.name,
              description: cmd.description,
              commandKind: cmd.kind
            };
            if (cmd.suggestionGroup) {
              suggestion.sectionTitle = cmd.suggestionGroup;
            }
            return suggestion;
          });
          const isTopLevelChatOrResumeContext = !!(leafCommand && (leafCommand.name === "chat" || leafCommand.name === "resume") && (commandPathParts.length === 0 || commandPathParts.length === 1 && matchesCommand(leafCommand, commandPathParts[0])));
          if (isTopLevelChatOrResumeContext) {
            const canonicalParentName = leafCommand.name;
            const autoSectionSuggestion = {
              label: "list",
              value: "list",
              insertValue: canonicalParentName,
              description: "Browse auto-saved chats",
              commandKind: "built-in" /* BUILT_IN */,
              sectionTitle: "auto",
              submitValue: `/${canonicalParentName}`
            };
            setSuggestions([autoSectionSuggestion, ...finalSuggestions]);
            return;
          }
          setSuggestions(finalSuggestions);
        }
      };
      performFuzzySearch().catch((error) => {
        logErrorSafely(error, "Unexpected fuzzy search error");
        if (!signal.aborted) {
          setSuggestions([]);
        }
      });
      return () => abortController.abort();
    }
    setSuggestions([]);
    return () => abortController.abort();
  }, [
    query,
    parserResult,
    commandContext,
    getFzfForCommands,
    getPrefixSuggestions
  ]);
  return { suggestions, isLoading };
}
function useCompletionPositions(query, parserResult) {
  return (0, import_react78.useMemo)(() => {
    if (!query) {
      return { start: -1, end: -1 };
    }
    const { hasTrailingSpace, partial } = parserResult;
    if (hasTrailingSpace) {
      return { start: query.length, end: query.length };
    } else if (partial) {
      if (parserResult.isArgumentCompletion) {
        const commandSoFar = `/${parserResult.commandPathParts.join(" ")}`;
        const argStartIndex = commandSoFar.length + (parserResult.commandPathParts.length > 0 ? 1 : 0);
        return { start: argStartIndex, end: query.length };
      } else {
        return { start: query.length - partial.length, end: query.length };
      }
    } else {
      return { start: 1, end: query.length };
    }
  }, [query, parserResult]);
}
function usePerfectMatch(parserResult) {
  return (0, import_react78.useMemo)(() => {
    const { hasTrailingSpace, partial, leafCommand, currentLevel } = parserResult;
    if (hasTrailingSpace) {
      return { isPerfectMatch: false };
    }
    if (leafCommand && partial === "" && leafCommand.action) {
      return { isPerfectMatch: true };
    }
    if (currentLevel) {
      const perfectMatch = currentLevel.find(
        (cmd) => matchesCommand(cmd, partial) && cmd.action
      );
      if (perfectMatch) {
        return { isPerfectMatch: true };
      }
    }
    return { isPerfectMatch: false };
  }, [parserResult]);
}
function getCommandFromSuggestion(suggestion, parserResult) {
  const { currentLevel } = parserResult;
  if (!currentLevel) {
    return void 0;
  }
  const command = currentLevel.find(
    (cmd) => matchesCommand(cmd, suggestion.value)
  );
  return command;
}
function useSlashCompletion(props) {
  const {
    enabled,
    query,
    slashCommands,
    commandContext,
    setSuggestions,
    setIsLoadingSuggestions,
    setIsPerfectMatch
  } = props;
  const [completionStart, setCompletionStart] = (0, import_react78.useState)(-1);
  const [completionEnd, setCompletionEnd] = (0, import_react78.useState)(-1);
  const fzfInstanceCache = (0, import_react78.useMemo)(
    () => /* @__PURE__ */ new WeakMap(),
    []
  );
  const getFzfForCommands = (0, import_react78.useMemo)(
    () => (commands) => {
      if (!commands || commands.length === 0) {
        return null;
      }
      const cached = fzfInstanceCache.get(commands);
      if (cached) {
        return cached;
      }
      const commandItems = [];
      const commandMap = /* @__PURE__ */ new Map();
      commands.forEach((cmd) => {
        if (cmd.description && !cmd.hidden) {
          commandItems.push(cmd.name);
          commandMap.set(cmd.name, cmd);
          if (cmd.altNames) {
            cmd.altNames.forEach((alt) => {
              commandItems.push(alt);
              commandMap.set(alt, cmd);
            });
          }
        }
      });
      if (commandItems.length === 0) {
        return null;
      }
      try {
        const instance = {
          fzf: new AsyncFzf(commandItems, {
            fuzzy: "v2",
            casing: "case-insensitive"
            // Explicitly enforce case-insensitivity
          }),
          commandMap
        };
        fzfInstanceCache.set(commands, instance);
        return instance;
      } catch (error) {
        logErrorSafely(error, "FZF instance creation");
        return null;
      }
    },
    [fzfInstanceCache]
  );
  const getPrefixSuggestions = (0, import_react78.useMemo)(
    () => (commands, partial) => commands.filter(
      (cmd) => cmd.description && !cmd.hidden && (cmd.name.toLowerCase().startsWith(partial.toLowerCase()) || cmd.altNames?.some(
        (alt) => alt.toLowerCase().startsWith(partial.toLowerCase())
      ))
    ),
    []
  );
  const parserResult = useCommandParser(query, slashCommands);
  const { suggestions: hookSuggestions, isLoading } = useCommandSuggestions(
    query,
    parserResult,
    commandContext,
    getFzfForCommands,
    getPrefixSuggestions
  );
  const { start: calculatedStart, end: calculatedEnd } = useCompletionPositions(
    query,
    parserResult
  );
  const { isPerfectMatch } = usePerfectMatch(parserResult);
  (0, import_react78.useEffect)(() => {
    if (!enabled) {
      setSuggestions([]);
      setIsLoadingSuggestions(false);
      setIsPerfectMatch(false);
      setCompletionStart(-1);
      setCompletionEnd(-1);
    }
  }, [enabled, setSuggestions, setIsLoadingSuggestions, setIsPerfectMatch]);
  (0, import_react78.useEffect)(() => {
    if (!enabled || query === null) {
      return;
    }
    setSuggestions(hookSuggestions);
    setIsLoadingSuggestions(isLoading);
    setIsPerfectMatch(isPerfectMatch);
    setCompletionStart(calculatedStart);
    setCompletionEnd(calculatedEnd);
  }, [
    enabled,
    query,
    hookSuggestions,
    isLoading,
    isPerfectMatch,
    calculatedStart,
    calculatedEnd,
    setSuggestions,
    setIsLoadingSuggestions,
    setIsPerfectMatch
  ]);
  return {
    completionStart,
    completionEnd,
    getCommandFromSuggestion: (suggestion) => getCommandFromSuggestion(suggestion, parserResult),
    isArgumentCompletion: parserResult.isArgumentCompletion,
    leafCommand: parserResult.leafCommand
  };
}

// packages/cli/src/ui/hooks/useShellCompletion.ts
var import_react79 = __toESM(require_react(), 1);
import * as fs4 from "node:fs/promises";
import * as path10 from "node:path";
import * as os from "node:os";

// packages/cli/src/ui/hooks/shell-completions/gitProvider.ts
import { execFile } from "node:child_process";
import { promisify } from "node:util";
var execFileAsync = promisify(execFile);
var GIT_SUBCOMMANDS = [
  "add",
  "branch",
  "checkout",
  "commit",
  "diff",
  "merge",
  "pull",
  "push",
  "rebase",
  "status",
  "switch"
];
var gitProvider = {
  command: "git",
  async getCompletions(tokens, cursorIndex, cwd5, signal) {
    if (cursorIndex === 1) {
      const partial = tokens[1] || "";
      return {
        suggestions: GIT_SUBCOMMANDS.filter(
          (cmd) => cmd.startsWith(partial)
        ).map((cmd) => ({
          label: cmd,
          value: cmd,
          description: "git command"
        })),
        exclusive: true
      };
    }
    if (cursorIndex === 2) {
      const subcommand = tokens[1];
      if (subcommand === "checkout" || subcommand === "switch" || subcommand === "merge" || subcommand === "branch") {
        const partial = tokens[2] || "";
        try {
          const { stdout } = await execFileAsync(
            "git",
            ["branch", "--format=%(refname:short)"],
            { cwd: cwd5, signal }
          );
          const branches = stdout.split("\n").map((b) => b.trim()).filter(Boolean);
          return {
            suggestions: branches.filter((b) => b.startsWith(partial)).map((b) => ({
              label: b,
              value: escapeShellPath(b),
              description: "branch"
            })),
            exclusive: true
          };
        } catch {
          return { suggestions: [], exclusive: true };
        }
      }
    }
    return { suggestions: [], exclusive: false };
  }
};

// packages/cli/src/ui/hooks/shell-completions/npmProvider.ts
import * as fs3 from "node:fs/promises";
import * as path9 from "node:path";
var NPM_SUBCOMMANDS = [
  "build",
  "ci",
  "dev",
  "install",
  "publish",
  "run",
  "start",
  "test"
];
var npmProvider = {
  command: "npm",
  async getCompletions(tokens, cursorIndex, cwd5, signal) {
    if (cursorIndex === 1) {
      const partial = tokens[1] || "";
      return {
        suggestions: NPM_SUBCOMMANDS.filter(
          (cmd) => cmd.startsWith(partial)
        ).map((cmd) => ({
          label: cmd,
          value: cmd,
          description: "npm command"
        })),
        exclusive: true
      };
    }
    if (cursorIndex === 2 && tokens[1] === "run") {
      const partial = tokens[2] || "";
      try {
        if (signal?.aborted) return { suggestions: [], exclusive: true };
        const pkgJsonPath = path9.join(cwd5, "package.json");
        const content = await fs3.readFile(pkgJsonPath, "utf8");
        const pkg = JSON.parse(content);
        const scripts = pkg && typeof pkg === "object" && "scripts" in pkg && pkg.scripts && typeof pkg.scripts === "object" ? Object.keys(pkg.scripts) : [];
        return {
          suggestions: scripts.filter((s) => s.startsWith(partial)).map((s) => ({
            label: s,
            value: escapeShellPath(s),
            description: "npm script"
          })),
          exclusive: true
        };
      } catch {
        return { suggestions: [], exclusive: true };
      }
    }
    return { suggestions: [], exclusive: false };
  }
};

// packages/cli/src/ui/hooks/shell-completions/index.ts
var providers = [gitProvider, npmProvider];
async function getArgumentCompletions(commandToken, tokens, cursorIndex, cwd5, signal) {
  const provider = providers.find((p) => p.command === commandToken);
  if (!provider) {
    return null;
  }
  return provider.getCompletions(tokens, cursorIndex, cwd5, signal);
}

// packages/cli/src/ui/hooks/useShellCompletion.ts
var MAX_SHELL_SUGGESTIONS = 100;
var FS_COMPLETION_DEBOUNCE_MS = 50;
var UNIX_SHELL_SPECIAL_CHARS = /[ \t\n\r'"()&|;<>!#$`{}[\]*?\\]/g;
function escapeShellPath(segment) {
  if (process.platform === "win32") {
    return segment;
  }
  return segment.replace(UNIX_SHELL_SPECIAL_CHARS, "\\$&");
}
function getTokenAtCursor(line, cursorCol) {
  const tokensInfo = [];
  let i = 0;
  while (i < line.length) {
    if (line[i] === " " || line[i] === "	") {
      i++;
      continue;
    }
    const tokenStart = i;
    let token = "";
    while (i < line.length) {
      const ch = line[i];
      if (ch === "\\" && i + 1 < line.length) {
        token += line[i + 1];
        i += 2;
        continue;
      }
      if (ch === "'") {
        i++;
        while (i < line.length && line[i] !== "'") {
          token += line[i];
          i++;
        }
        if (i < line.length) i++;
        continue;
      }
      if (ch === '"') {
        i++;
        while (i < line.length && line[i] !== '"') {
          if (line[i] === "\\" && i + 1 < line.length) {
            token += line[i + 1];
            i += 2;
          } else {
            token += line[i];
            i++;
          }
        }
        if (i < line.length) i++;
        continue;
      }
      if (ch === " " || ch === "	") {
        break;
      }
      token += ch;
      i++;
    }
    tokensInfo.push({ token, start: tokenStart, end: i });
  }
  const rawTokens = tokensInfo.map((t) => t.token);
  const commandToken = rawTokens.length > 0 ? rawTokens[0] : "";
  if (tokensInfo.length === 0) {
    return {
      token: "",
      start: cursorCol,
      end: cursorCol,
      isFirstToken: true,
      tokens: [""],
      cursorIndex: 0,
      commandToken: ""
    };
  }
  for (let idx = 0; idx < tokensInfo.length; idx++) {
    const t = tokensInfo[idx];
    if (cursorCol >= t.start && cursorCol <= t.end) {
      return {
        token: t.token,
        start: t.start,
        end: t.end,
        isFirstToken: idx === 0,
        tokens: rawTokens,
        cursorIndex: idx,
        commandToken
      };
    }
  }
  let insertIndex = tokensInfo.length;
  for (let idx = 0; idx < tokensInfo.length; idx++) {
    if (cursorCol < tokensInfo[idx].start) {
      insertIndex = idx;
      break;
    }
  }
  const newTokens = [
    ...rawTokens.slice(0, insertIndex),
    "",
    ...rawTokens.slice(insertIndex)
  ];
  return {
    token: "",
    start: cursorCol,
    end: cursorCol,
    isFirstToken: insertIndex === 0,
    tokens: newTokens,
    cursorIndex: insertIndex,
    commandToken: newTokens.length > 0 ? newTokens[0] : ""
  };
}
async function scanPathExecutables(signal) {
  const pathEnv = process.env["PATH"] ?? "";
  const dirs = pathEnv.split(path10.delimiter).filter(Boolean);
  const isWindows2 = process.platform === "win32";
  const pathExtList = isWindows2 ? (process.env["PATHEXT"] ?? ".EXE;.CMD;.BAT;.COM").split(";").filter(Boolean).map((e) => e.toLowerCase()) : [];
  const seen = /* @__PURE__ */ new Set();
  const executables = [];
  if (isWindows2) {
    const builtins = [
      "assoc",
      "break",
      "call",
      "cd",
      "chcp",
      "chdir",
      "cls",
      "color",
      "copy",
      "date",
      "del",
      "dir",
      "echo",
      "endlocal",
      "erase",
      "exit",
      "for",
      "ftype",
      "goto",
      "if",
      "md",
      "mkdir",
      "mklink",
      "move",
      "path",
      "pause",
      "popd",
      "prompt",
      "pushd",
      "rd",
      "rem",
      "ren",
      "rename",
      "rmdir",
      "set",
      "setlocal",
      "shift",
      "start",
      "time",
      "title",
      "type",
      "ver",
      "verify",
      "vol"
    ];
    for (const builtin of builtins) {
      seen.add(builtin);
      executables.push(builtin);
    }
  }
  const dirResults = await Promise.all(
    dirs.map(async (dir) => {
      if (signal?.aborted) return [];
      try {
        const entries = await fs4.readdir(dir, { withFileTypes: true });
        const validEntries = [];
        await Promise.all(
          entries.map(async (entry) => {
            if (signal?.aborted) return;
            if (!entry.isFile() && !entry.isSymbolicLink()) return;
            const name = entry.name;
            if (isWindows2) {
              const ext = path10.extname(name).toLowerCase();
              if (pathExtList.length > 0 && !pathExtList.includes(ext)) return;
            }
            try {
              await fs4.access(
                path10.join(dir, name),
                fs4.constants.R_OK | fs4.constants.X_OK
              );
              validEntries.push(name);
            } catch {
            }
          })
        );
        return validEntries;
      } catch {
        return [];
      }
    })
  );
  for (const names of dirResults) {
    for (const name of names) {
      if (!seen.has(name)) {
        seen.add(name);
        executables.push(name);
      }
    }
  }
  executables.sort();
  return executables;
}
function expandTilde(inputPath) {
  if (inputPath === "~" || inputPath.startsWith("~/") || inputPath.startsWith("~" + path10.sep)) {
    return [path10.join(os.homedir(), inputPath.slice(1)), true];
  }
  return [inputPath, false];
}
async function resolvePathCompletions(partial, cwd5, signal) {
  if (partial == null) return [];
  let strippedPartial = partial;
  if (strippedPartial.startsWith('"') || strippedPartial.startsWith("'")) {
    strippedPartial = strippedPartial.slice(1);
  }
  if (strippedPartial.endsWith('"') || strippedPartial.endsWith("'")) {
    strippedPartial = strippedPartial.slice(0, -1);
  }
  const normalizedPartial = strippedPartial.replace(/\\/g, "/");
  const [expandedPartial, didExpandTilde] = expandTilde(normalizedPartial);
  const endsWithSep = normalizedPartial.endsWith("/") || normalizedPartial === "";
  const dirToRead = endsWithSep ? path10.resolve(cwd5, expandedPartial) : path10.resolve(cwd5, path10.dirname(expandedPartial));
  const prefix = endsWithSep ? "" : path10.basename(expandedPartial);
  const prefixLower = prefix.toLowerCase();
  const showDotfiles = prefix.startsWith(".");
  let entries;
  try {
    if (signal?.aborted) return [];
    entries = await fs4.readdir(dirToRead, { withFileTypes: true });
  } catch {
    return [];
  }
  if (signal?.aborted) return [];
  const suggestions = [];
  for (const entry of entries) {
    if (signal?.aborted) break;
    const name = entry.name;
    if (name.startsWith(".") && !showDotfiles) continue;
    if (!name.toLowerCase().startsWith(prefixLower)) continue;
    const isDir = entry.isDirectory();
    const displayName = isDir ? name + "/" : name;
    let completionValue;
    if (endsWithSep) {
      completionValue = normalizedPartial + displayName;
    } else {
      const parentPart = normalizedPartial.slice(
        0,
        normalizedPartial.length - path10.basename(normalizedPartial).length
      );
      completionValue = parentPart + displayName;
    }
    if (didExpandTilde) {
      const homeDir = os.homedir().replace(/\\/g, "/");
      if (completionValue.startsWith(homeDir)) {
        completionValue = "~" + completionValue.slice(homeDir.length);
      }
    }
    const escapedValue = escapeShellPath(completionValue);
    suggestions.push({
      label: displayName,
      value: escapedValue,
      description: isDir ? "directory" : "file"
    });
    if (suggestions.length >= MAX_SHELL_SUGGESTIONS) break;
  }
  suggestions.sort((a, b) => {
    const aIsDir = a.description === "directory";
    const bIsDir = b.description === "directory";
    if (aIsDir !== bIsDir) return aIsDir ? -1 : 1;
    return a.label.localeCompare(b.label);
  });
  return suggestions;
}
var EMPTY_TOKENS = [];
function useShellCompletion({
  enabled,
  line,
  cursorCol,
  cwd: cwd5,
  setSuggestions,
  setIsLoadingSuggestions
}) {
  const pathCachePromiseRef = (0, import_react79.useRef)(null);
  const pathEnvRef = (0, import_react79.useRef)(process.env["PATH"] ?? "");
  const abortRef = (0, import_react79.useRef)(null);
  const debounceRef = (0, import_react79.useRef)(null);
  const [activeStart, setActiveStart] = (0, import_react79.useState)(-1);
  const tokenInfo = (0, import_react79.useMemo)(
    () => enabled ? getTokenAtCursor(line, cursorCol) : null,
    [enabled, line, cursorCol]
  );
  const {
    token: query = "",
    start: completionStart = -1,
    end: completionEnd = -1,
    isFirstToken: isCommandPosition = false,
    tokens = EMPTY_TOKENS,
    cursorIndex = -1,
    commandToken = ""
  } = tokenInfo || {};
  if (enabled && activeStart !== -1 && completionStart !== activeStart) {
    setSuggestions([]);
    setActiveStart(-1);
  }
  (0, import_react79.useEffect)(() => {
    const currentPath = process.env["PATH"] ?? "";
    if (currentPath !== pathEnvRef.current) {
      pathCachePromiseRef.current = null;
      pathEnvRef.current = currentPath;
    }
  });
  const performCompletion = (0, import_react79.useCallback)(async () => {
    if (!enabled || !tokenInfo) {
      setSuggestions([]);
      return;
    }
    if (query.startsWith("-")) {
      setSuggestions([]);
      return;
    }
    if (abortRef.current) {
      abortRef.current.abort();
    }
    const controller = new AbortController();
    abortRef.current = controller;
    const { signal } = controller;
    try {
      let results;
      if (isCommandPosition) {
        setIsLoadingSuggestions(true);
        if (!pathCachePromiseRef.current) {
          pathCachePromiseRef.current = scanPathExecutables();
        }
        const executables = await pathCachePromiseRef.current;
        if (signal.aborted) return;
        const queryLower = query.toLowerCase();
        results = executables.filter((cmd) => cmd.toLowerCase().startsWith(queryLower)).sort((a, b) => {
          if (a.length !== b.length) {
            return a.length - b.length;
          }
          return a.localeCompare(b);
        }).slice(0, MAX_SHELL_SUGGESTIONS).map((cmd) => ({
          label: cmd,
          value: escapeShellPath(cmd),
          description: "command"
        }));
      } else {
        const argumentCompletions = await getArgumentCompletions(
          commandToken,
          tokens,
          cursorIndex,
          cwd5,
          signal
        );
        if (signal.aborted) return;
        if (argumentCompletions?.exclusive) {
          results = argumentCompletions.suggestions;
        } else {
          const pathSuggestions = await resolvePathCompletions(
            query,
            cwd5,
            signal
          );
          if (signal.aborted) return;
          results = [
            ...argumentCompletions?.suggestions ?? [],
            ...pathSuggestions
          ].slice(0, MAX_SHELL_SUGGESTIONS);
        }
      }
      if (signal.aborted) return;
      setSuggestions(results);
      setActiveStart(completionStart);
    } catch (error) {
      if (!(signal.aborted || error instanceof Error && error.name === "AbortError")) {
        debugLogger.warn(
          `[WARN] shell completion failed: ${error instanceof Error ? error.message : String(error)}`
        );
      }
      if (!signal.aborted) {
        setSuggestions([]);
        setActiveStart(completionStart);
      }
    } finally {
      if (!signal.aborted) {
        setIsLoadingSuggestions(false);
      }
    }
  }, [
    enabled,
    tokenInfo,
    query,
    isCommandPosition,
    tokens,
    cursorIndex,
    commandToken,
    cwd5,
    completionStart,
    setSuggestions,
    setIsLoadingSuggestions
  ]);
  (0, import_react79.useEffect)(() => {
    if (!enabled) {
      abortRef.current?.abort();
      setSuggestions([]);
      setActiveStart(-1);
      setIsLoadingSuggestions(false);
    }
  }, [enabled, setSuggestions, setIsLoadingSuggestions]);
  (0, import_react79.useEffect)(() => {
    if (!enabled) return;
    if (debounceRef.current) {
      clearTimeout(debounceRef.current);
    }
    debounceRef.current = setTimeout(() => {
      performCompletion();
    }, FS_COMPLETION_DEBOUNCE_MS);
    return () => {
      if (debounceRef.current) {
        clearTimeout(debounceRef.current);
      }
    };
  }, [enabled, performCompletion]);
  (0, import_react79.useEffect)(
    () => () => {
      abortRef.current?.abort();
      if (debounceRef.current) {
        clearTimeout(debounceRef.current);
      }
    },
    []
  );
  return {
    completionStart,
    completionEnd,
    query,
    activeStart
  };
}

// packages/cli/src/ui/hooks/usePromptCompletion.ts
var import_react80 = __toESM(require_react(), 1);
var PROMPT_COMPLETION_MIN_LENGTH = 5;
var PROMPT_COMPLETION_DEBOUNCE_MS = 250;
function usePromptCompletion({
  buffer,
  config
}) {
  const [ghostText, setGhostText] = (0, import_react80.useState)("");
  const [isLoadingGhostText, setIsLoadingGhostText] = (0, import_react80.useState)(false);
  const abortControllerRef = (0, import_react80.useRef)(null);
  const [justSelectedSuggestion, setJustSelectedSuggestion] = (0, import_react80.useState)(false);
  const lastSelectedTextRef = (0, import_react80.useRef)("");
  const lastRequestedTextRef = (0, import_react80.useRef)("");
  const isPromptCompletionEnabled = false;
  const clearGhostText = (0, import_react80.useCallback)(() => {
    setGhostText("");
    setIsLoadingGhostText(false);
  }, []);
  const acceptGhostText = (0, import_react80.useCallback)(() => {
    if (ghostText && ghostText.length > buffer.text.length) {
      buffer.setText(ghostText);
      setGhostText("");
      setJustSelectedSuggestion(true);
      lastSelectedTextRef.current = ghostText;
    }
  }, [ghostText, buffer]);
  const markSuggestionSelected = (0, import_react80.useCallback)((selectedText) => {
    setJustSelectedSuggestion(true);
    lastSelectedTextRef.current = selectedText;
  }, []);
  const generatePromptSuggestions = (0, import_react80.useCallback)(async () => {
    const trimmedText = buffer.text.trim();
    const geminiClient = config?.getGeminiClient();
    if (trimmedText === lastRequestedTextRef.current) {
      return;
    }
    if (abortControllerRef.current) {
      abortControllerRef.current.abort();
    }
    if (trimmedText.length < PROMPT_COMPLETION_MIN_LENGTH || !geminiClient || isSlashCommand(trimmedText) || trimmedText.includes("@") || !isPromptCompletionEnabled) {
      clearGhostText();
      lastRequestedTextRef.current = "";
      return;
    }
    lastRequestedTextRef.current = trimmedText;
    setIsLoadingGhostText(true);
    abortControllerRef.current = new AbortController();
    const signal = abortControllerRef.current.signal;
    try {
      const contents = [
        {
          role: "user",
          parts: [
            {
              text: `You are a professional prompt engineering assistant. Complete the user's partial prompt with expert precision and clarity. User's input: "${trimmedText}" Continue this prompt by adding specific, actionable details that align with the user's intent. Focus on: clear, precise language; structured requirements; professional terminology; measurable outcomes. Length Guidelines: Keep suggestions concise (ideally 10-20 characters); prioritize brevity while maintaining clarity; use essential keywords only; avoid redundant phrases. Start your response with the exact user text ("${trimmedText}") followed by your completion. Provide practical, implementation-focused suggestions rather than creative interpretations. Format: Plain text only. Single completion. Match the user's language. Emphasize conciseness over elaboration.`
            }
          ]
        }
      ];
      const response = await geminiClient.generateContent(
        { model: "prompt-completion" },
        contents,
        signal,
        LlmRole.UTILITY_AUTOCOMPLETE
      );
      if (signal.aborted) {
        return;
      }
      if (response) {
        const responseText = getResponseText(response);
        if (responseText) {
          const suggestionText = responseText.trim();
          if (suggestionText.length > 0 && suggestionText.startsWith(trimmedText)) {
            setGhostText(suggestionText);
          } else {
            clearGhostText();
          }
        }
      }
    } catch (error) {
      if (!(signal.aborted || error instanceof Error && error.name === "AbortError")) {
        debugLogger.warn(
          `[WARN] prompt completion failed: : (${error instanceof Error ? error.message : String(error)})`
        );
      }
      clearGhostText();
    } finally {
      if (!signal.aborted) {
        setIsLoadingGhostText(false);
      }
    }
  }, [buffer.text, config, clearGhostText, isPromptCompletionEnabled]);
  const isCursorAtEnd = (0, import_react80.useCallback)(() => {
    const [cursorRow, cursorCol] = buffer.cursor;
    const totalLines = buffer.lines.length;
    if (cursorRow !== totalLines - 1) {
      return false;
    }
    const lastLine = buffer.lines[cursorRow] || "";
    return cursorCol === lastLine.length;
  }, [buffer.cursor, buffer.lines]);
  const handlePromptCompletion = (0, import_react80.useCallback)(() => {
    if (!isCursorAtEnd()) {
      clearGhostText();
      return;
    }
    const trimmedText = buffer.text.trim();
    if (justSelectedSuggestion && trimmedText === lastSelectedTextRef.current) {
      return;
    }
    if (trimmedText !== lastSelectedTextRef.current) {
      setJustSelectedSuggestion(false);
      lastSelectedTextRef.current = "";
    }
    generatePromptSuggestions();
  }, [
    buffer.text,
    generatePromptSuggestions,
    justSelectedSuggestion,
    isCursorAtEnd,
    clearGhostText
  ]);
  (0, import_react80.useEffect)(() => {
    const timeoutId2 = setTimeout(
      handlePromptCompletion,
      PROMPT_COMPLETION_DEBOUNCE_MS
    );
    return () => clearTimeout(timeoutId2);
  }, [buffer.text, buffer.cursor, handlePromptCompletion]);
  (0, import_react80.useEffect)(() => {
    const currentText = buffer.text.trim();
    if (ghostText && !isCursorAtEnd()) {
      clearGhostText();
      return;
    }
    if (ghostText && currentText.length > 0 && !ghostText.startsWith(currentText)) {
      clearGhostText();
    }
  }, [buffer.text, buffer.cursor, ghostText, clearGhostText, isCursorAtEnd]);
  (0, import_react80.useEffect)(() => () => abortControllerRef.current?.abort(), []);
  const isActive = (0, import_react80.useMemo)(() => {
    if (!isPromptCompletionEnabled) return false;
    if (!isCursorAtEnd()) return false;
    const trimmedText = buffer.text.trim();
    return trimmedText.length >= PROMPT_COMPLETION_MIN_LENGTH && !isSlashCommand(trimmedText) && !trimmedText.includes("@");
  }, [buffer.text, isPromptCompletionEnabled, isCursorAtEnd]);
  return {
    text: ghostText,
    isLoading: isLoadingGhostText,
    isActive,
    accept: acceptGhostText,
    clear: clearGhostText,
    markSelected: markSuggestionSelected
  };
}

// packages/cli/src/ui/hooks/useCommandCompletion.tsx
function useCommandCompletion({
  buffer,
  cwd: cwd5,
  slashCommands,
  commandContext,
  reverseSearchActive = false,
  shellModeActive,
  config,
  active
}) {
  const [forceShowShellSuggestions, setForceShowShellSuggestions] = (0, import_react81.useState)(false);
  const {
    suggestions,
    activeSuggestionIndex,
    visibleStartIndex,
    isLoadingSuggestions,
    isPerfectMatch,
    setSuggestions,
    setActiveSuggestionIndex,
    setIsLoadingSuggestions,
    setIsPerfectMatch,
    setVisibleStartIndex,
    resetCompletionState: baseResetCompletionState,
    navigateUp,
    navigateDown
  } = useCompletion();
  const resetCompletionState = (0, import_react81.useCallback)(() => {
    baseResetCompletionState();
    setForceShowShellSuggestions(false);
  }, [baseResetCompletionState]);
  const cursorRow = buffer.cursor[0];
  const cursorCol = buffer.cursor[1];
  const {
    completionMode,
    query: memoQuery,
    completionStart,
    completionEnd
  } = (0, import_react81.useMemo)(() => {
    const currentLine = buffer.lines[cursorRow] || "";
    const codePoints = toCodePoints(currentLine);
    if (shellModeActive) {
      return {
        completionMode: currentLine.trim().length === 0 ? "IDLE" /* IDLE */ : "SHELL" /* SHELL */,
        query: "",
        completionStart: -1,
        completionEnd: -1
      };
    }
    for (let i = cursorCol - 1; i >= 0; i--) {
      const char = codePoints[i];
      if (char === " ") {
        let backslashCount = 0;
        for (let j = i - 1; j >= 0 && codePoints[j] === "\\"; j--) {
          backslashCount++;
        }
        if (backslashCount % 2 === 0) {
          break;
        }
      } else if (char === "@") {
        let end = codePoints.length;
        for (let i2 = cursorCol; i2 < codePoints.length; i2++) {
          if (codePoints[i2] === " ") {
            let backslashCount = 0;
            for (let j = i2 - 1; j >= 0 && codePoints[j] === "\\"; j--) {
              backslashCount++;
            }
            if (backslashCount % 2 === 0) {
              end = i2;
              break;
            }
          }
        }
        const pathStart = i + 1;
        const partialPath = currentLine.substring(pathStart, end);
        return {
          completionMode: "AT" /* AT */,
          query: partialPath,
          completionStart: pathStart,
          completionEnd: end
        };
      }
    }
    if (cursorRow === 0 && isSlashCommand(currentLine.trim())) {
      return {
        completionMode: "SLASH" /* SLASH */,
        query: currentLine,
        completionStart: 0,
        completionEnd: currentLine.length
      };
    }
    const trimmedText = buffer.text.trim();
    const isPromptCompletionEnabled = false;
    if (isPromptCompletionEnabled && trimmedText.length >= PROMPT_COMPLETION_MIN_LENGTH && !isSlashCommand(trimmedText) && !trimmedText.includes("@")) {
      return {
        completionMode: "PROMPT" /* PROMPT */,
        query: trimmedText,
        completionStart: 0,
        completionEnd: trimmedText.length
      };
    }
    return {
      completionMode: "IDLE" /* IDLE */,
      query: null,
      completionStart: -1,
      completionEnd: -1
    };
  }, [cursorRow, cursorCol, buffer.lines, buffer.text, shellModeActive]);
  useAtCompletion({
    enabled: active && completionMode === "AT" /* AT */,
    pattern: memoQuery || "",
    config,
    cwd: cwd5,
    setSuggestions,
    setIsLoadingSuggestions
  });
  const slashCompletionRange = useSlashCompletion({
    enabled: active && completionMode === "SLASH" /* SLASH */ && !shellModeActive,
    query: memoQuery,
    slashCommands,
    commandContext,
    setSuggestions,
    setIsLoadingSuggestions,
    setIsPerfectMatch
  });
  const shellCompletionRange = useShellCompletion({
    enabled: active && completionMode === "SHELL" /* SHELL */,
    line: buffer.lines[cursorRow] || "",
    cursorCol,
    cwd: cwd5,
    setSuggestions,
    setIsLoadingSuggestions
  });
  const query = completionMode === "SHELL" /* SHELL */ ? shellCompletionRange.query : memoQuery;
  const basePromptCompletion = usePromptCompletion({
    buffer
  });
  const isShellSuggestionsVisible = completionMode !== "SHELL" /* SHELL */ || forceShowShellSuggestions;
  const promptCompletion = (0, import_react81.useMemo)(() => {
    if (completionMode === "SHELL" /* SHELL */ && suggestions.length === 1 && query != null && shellCompletionRange.completionStart === shellCompletionRange.activeStart) {
      const suggestion = suggestions[0];
      const textToInsertBase = suggestion.value;
      if (textToInsertBase.startsWith(query) && textToInsertBase.length > query.length) {
        const currentLine = buffer.lines[cursorRow] || "";
        const start = shellCompletionRange.completionStart;
        const end = shellCompletionRange.completionEnd;
        let textToInsert = textToInsertBase;
        const charAfterCompletion = currentLine[end];
        if (charAfterCompletion !== " " && !textToInsert.endsWith("/") && !textToInsert.endsWith("\\")) {
          textToInsert += " ";
        }
        const newText = currentLine.substring(0, start) + textToInsert + currentLine.substring(end);
        return {
          text: newText,
          isActive: true,
          isLoading: false,
          accept: () => {
            buffer.replaceRangeByOffset(
              logicalPosToOffset(buffer.lines, cursorRow, start),
              logicalPosToOffset(buffer.lines, cursorRow, end),
              textToInsert
            );
          },
          clear: () => {
          },
          markSelected: () => {
          }
        };
      }
    }
    return basePromptCompletion;
  }, [
    completionMode,
    suggestions,
    query,
    basePromptCompletion,
    buffer,
    cursorRow,
    shellCompletionRange
  ]);
  (0, import_react81.useEffect)(() => {
    setActiveSuggestionIndex(suggestions.length > 0 ? 0 : -1);
    setVisibleStartIndex(0);
    if (completionMode !== "SLASH" /* SLASH */) {
      if (suggestions.length > 0) {
        const firstSuggestion = suggestions[0];
        setIsPerfectMatch(firstSuggestion.value === query);
      } else {
        setIsPerfectMatch(false);
      }
    }
  }, [
    suggestions,
    setActiveSuggestionIndex,
    setVisibleStartIndex,
    completionMode,
    query,
    setIsPerfectMatch
  ]);
  (0, import_react81.useEffect)(() => {
    if (!active || completionMode === "IDLE" /* IDLE */ || reverseSearchActive) {
      resetCompletionState();
    }
  }, [active, completionMode, reverseSearchActive, resetCompletionState]);
  const showSuggestions = active && completionMode !== "IDLE" /* IDLE */ && !reverseSearchActive && isShellSuggestionsVisible && (isLoadingSuggestions || suggestions.length > 0);
  const getCompletedText = (0, import_react81.useCallback)(
    (suggestion) => {
      const currentLine = buffer.lines[cursorRow] || "";
      let start = completionStart;
      let end = completionEnd;
      if (completionMode === "SLASH" /* SLASH */) {
        start = slashCompletionRange.completionStart;
        end = slashCompletionRange.completionEnd;
      } else if (completionMode === "SHELL" /* SHELL */) {
        start = shellCompletionRange.completionStart;
        end = shellCompletionRange.completionEnd;
      }
      if (start === -1 || end === -1) {
        return null;
      }
      let suggestionText = suggestion.insertValue ?? suggestion.value;
      if (completionMode === "SLASH" /* SLASH */) {
        if (start === end && start > 1 && currentLine[start - 1] !== " ") {
          suggestionText = " " + suggestionText;
        }
      }
      return currentLine.substring(0, start) + suggestionText + currentLine.substring(end);
    },
    [
      cursorRow,
      buffer.lines,
      completionMode,
      completionStart,
      completionEnd,
      slashCompletionRange,
      shellCompletionRange
    ]
  );
  const handleAutocomplete = (0, import_react81.useCallback)(
    (indexToUse) => {
      if (indexToUse < 0 || indexToUse >= suggestions.length) {
        return;
      }
      const suggestion = suggestions[indexToUse];
      const completedText = getCompletedText(suggestion);
      if (completedText === null) {
        return;
      }
      let start = completionStart;
      let end = completionEnd;
      if (completionMode === "SLASH" /* SLASH */) {
        start = slashCompletionRange.completionStart;
        end = slashCompletionRange.completionEnd;
      } else if (completionMode === "SHELL" /* SHELL */) {
        start = shellCompletionRange.completionStart;
        end = shellCompletionRange.completionEnd;
      }
      let suggestionText = suggestion.insertValue ?? suggestion.value;
      if (completionMode === "SLASH" /* SLASH */) {
        if (start === end && start > 1 && (buffer.lines[cursorRow] || "")[start - 1] !== " ") {
          suggestionText = " " + suggestionText;
        }
      }
      const lineCodePoints = toCodePoints(buffer.lines[cursorRow] || "");
      const charAfterCompletion = lineCodePoints[end];
      let shouldAddSpace = true;
      if (completionMode === "SLASH" /* SLASH */) {
        const command = slashCompletionRange.getCommandFromSuggestion(suggestion);
        const isExecutableCommand = !!(command && command.action);
        const requiresArguments = !!(command && command.completion);
        shouldAddSpace = !isExecutableCommand || requiresArguments;
      }
      if (charAfterCompletion !== " " && !suggestionText.endsWith("/") && !suggestionText.endsWith("\\") && shouldAddSpace) {
        suggestionText += " ";
      }
      buffer.replaceRangeByOffset(
        logicalPosToOffset(buffer.lines, cursorRow, start),
        logicalPosToOffset(buffer.lines, cursorRow, end),
        suggestionText
      );
    },
    [
      cursorRow,
      buffer,
      suggestions,
      completionMode,
      completionStart,
      completionEnd,
      slashCompletionRange,
      shellCompletionRange,
      getCompletedText
    ]
  );
  return {
    suggestions,
    activeSuggestionIndex,
    visibleStartIndex,
    showSuggestions,
    isLoadingSuggestions,
    isPerfectMatch,
    forceShowShellSuggestions,
    setForceShowShellSuggestions,
    isShellSuggestionsVisible,
    setActiveSuggestionIndex,
    resetCompletionState,
    navigateUp,
    navigateDown,
    handleAutocomplete,
    promptCompletion,
    getCommandFromSuggestion: slashCompletionRange.getCommandFromSuggestion,
    slashCompletionRange,
    getCompletedText,
    completionMode
  };
}

// packages/cli/src/ui/utils/highlight.ts
var HIGHLIGHT_REGEX = new RegExp(
  `(^/[a-zA-Z0-9_-]+|(?<!\\\\)@${AT_COMMAND_PATH_REGEX_SOURCE}|${PASTED_TEXT_PLACEHOLDER_REGEX.source})`,
  "g"
);
var highlightCache = new import_lru_cache.default(
  LRU_BUFFER_PERF_CACHE_LIMIT
);
function parseInputForHighlighting(text, index, transformations = [], cursorCol) {
  let isCursorInsideTransform = false;
  if (cursorCol !== void 0) {
    for (const transform of transformations) {
      if (cursorCol >= transform.logStart && cursorCol <= transform.logEnd) {
        isCursorInsideTransform = true;
        break;
      }
    }
  }
  const cacheKey = `${index === 0 ? "F" : "N"}:${isCursorInsideTransform ? cursorCol : "NC"}:${text}`;
  const cached = highlightCache.get(cacheKey);
  if (cached !== void 0) return cached;
  HIGHLIGHT_REGEX.lastIndex = 0;
  if (!text) {
    return [{ text: "", type: "default" }];
  }
  const parseUntransformedInput = (text2) => {
    const tokens2 = [];
    if (!text2) return tokens2;
    HIGHLIGHT_REGEX.lastIndex = 0;
    let last = 0;
    let match;
    while ((match = HIGHLIGHT_REGEX.exec(text2)) !== null) {
      const [fullMatch] = match;
      const matchIndex = match.index;
      if (matchIndex > last) {
        tokens2.push({ text: text2.slice(last, matchIndex), type: "default" });
      }
      const type = fullMatch.startsWith("/") ? "command" : fullMatch.startsWith("@") ? "file" : "paste";
      if (type === "command" && index !== 0) {
        tokens2.push({ text: fullMatch, type: "default" });
      } else {
        tokens2.push({ text: fullMatch, type });
      }
      last = matchIndex + fullMatch.length;
    }
    if (last < text2.length) {
      tokens2.push({ text: text2.slice(last), type: "default" });
    }
    return tokens2;
  };
  const tokens = [];
  let column = 0;
  const sortedTransformations = (transformations ?? []).slice().sort((a, b) => a.logStart - b.logStart);
  for (const transformation of sortedTransformations) {
    const textBeforeTransformation = cpSlice(
      text,
      column,
      transformation.logStart
    );
    tokens.push(...parseUntransformedInput(textBeforeTransformation));
    const isCursorInside = cursorCol !== void 0 && cursorCol >= transformation.logStart && cursorCol <= transformation.logEnd;
    const transformationText = isCursorInside ? transformation.logicalText : transformation.collapsedText;
    tokens.push({ text: transformationText, type: "file" });
    column = transformation.logEnd;
  }
  const textAfterFinalTransformation = cpSlice(text, column);
  tokens.push(...parseUntransformedInput(textAfterFinalTransformation));
  highlightCache.set(cacheKey, tokens);
  return tokens;
}
function parseSegmentsFromTokens(tokens, sliceStart, sliceEnd) {
  if (sliceStart >= sliceEnd) return [];
  const segments = [];
  let tokenCpStart = 0;
  for (const token of tokens) {
    const tokenLen = cpLen(token.text);
    const tokenStart = tokenCpStart;
    const tokenEnd = tokenStart + tokenLen;
    const overlapStart = Math.max(tokenStart, sliceStart);
    const overlapEnd = Math.min(tokenEnd, sliceEnd);
    if (overlapStart < overlapEnd) {
      const sliceStartInToken = overlapStart - tokenStart;
      const sliceEndInToken = overlapEnd - tokenStart;
      const rawSlice = cpSlice(token.text, sliceStartInToken, sliceEndInToken);
      const last = segments[segments.length - 1];
      if (last && last.type === token.type) {
        last.text += rawSlice;
      } else {
        segments.push({ type: token.type, text: rawSlice });
      }
    }
    tokenCpStart += tokenLen;
  }
  return segments;
}

// packages/cli/src/ui/hooks/useKittyKeyboardProtocol.ts
var import_react82 = __toESM(require_react(), 1);
function useKittyKeyboardProtocol() {
  const [status] = (0, import_react82.useState)({
    enabled: terminalCapabilityManager.isKittyProtocolEnabled(),
    checking: false
  });
  return status;
}

// packages/cli/src/ui/components/InputPrompt.tsx
import * as path11 from "node:path";

// packages/cli/src/ui/contexts/ShellFocusContext.tsx
var import_react83 = __toESM(require_react(), 1);
var ShellFocusContext = (0, import_react83.createContext)(true);
var useShellFocusState = () => (0, import_react83.useContext)(ShellFocusContext);

// packages/cli/src/ui/utils/shortcutsHelp.ts
function useIsHelpDismissKey() {
  const keyMatchers = useKeyMatchers();
  return (key) => Object.values(Command).some((command) => keyMatchers[command](key));
}

// packages/cli/src/ui/hooks/useRepeatedKeyPress.ts
var import_react84 = __toESM(require_react(), 1);
function useRepeatedKeyPress(options) {
  const [pressCount, setPressCount] = (0, import_react84.useState)(0);
  const pressCountRef = (0, import_react84.useRef)(0);
  const timerRef = (0, import_react84.useRef)(null);
  const optionsRef = (0, import_react84.useRef)(options);
  (0, import_react84.useEffect)(() => {
    optionsRef.current = options;
  }, [options]);
  const resetCount = (0, import_react84.useCallback)(() => {
    if (timerRef.current) {
      clearTimeout(timerRef.current);
      timerRef.current = null;
    }
    if (pressCountRef.current > 0) {
      pressCountRef.current = 0;
      setPressCount(0);
      optionsRef.current.onReset?.();
    }
  }, []);
  const handlePress = (0, import_react84.useCallback)(() => {
    const newCount = pressCountRef.current + 1;
    pressCountRef.current = newCount;
    setPressCount(newCount);
    if (timerRef.current) {
      clearTimeout(timerRef.current);
    }
    timerRef.current = setTimeout(() => {
      pressCountRef.current = 0;
      setPressCount(0);
      timerRef.current = null;
      optionsRef.current.onReset?.();
    }, optionsRef.current.windowMs);
    optionsRef.current.onRepeat?.(newCount);
    return newCount;
  }, []);
  (0, import_react84.useEffect)(
    () => () => {
      if (timerRef.current) {
        clearTimeout(timerRef.current);
      }
    },
    []
  );
  return { pressCount, handlePress, resetCount };
}

// packages/cli/src/ui/components/InputPrompt.tsx
var import_jsx_runtime114 = __toESM(require_jsx_runtime(), 1);
function isTerminalPasteTrusted(kittyProtocolSupported) {
  return kittyProtocolSupported;
}
var calculatePromptWidths = (mainContentWidth) => {
  const FRAME_PADDING_AND_BORDER = 4;
  const PROMPT_PREFIX_WIDTH = 2;
  const FRAME_OVERHEAD = FRAME_PADDING_AND_BORDER + PROMPT_PREFIX_WIDTH;
  const suggestionsWidth = Math.max(20, mainContentWidth);
  return {
    inputWidth: Math.max(mainContentWidth - FRAME_OVERHEAD, 1),
    containerWidth: mainContentWidth,
    suggestionsWidth,
    frameOverhead: FRAME_OVERHEAD
  };
};
function isLargePaste(text) {
  const pasteLineCount = text.split("\n").length;
  return pasteLineCount > LARGE_PASTE_LINE_THRESHOLD || text.length > LARGE_PASTE_CHAR_THRESHOLD;
}
var DOUBLE_TAB_CLEAN_UI_TOGGLE_WINDOW_MS = 350;
function tryTogglePasteExpansion(buffer) {
  if (!buffer.pastedContent || Object.keys(buffer.pastedContent).length === 0) {
    return false;
  }
  const [row, col] = buffer.cursor;
  const transform = getTransformUnderCursor(
    row,
    col,
    buffer.transformationsByLine,
    { includeEdge: true }
  );
  if (transform?.type === "paste" && transform.id) {
    buffer.togglePasteExpansion(transform.id, row, col);
    return true;
  }
  const expandedId = buffer.getExpandedPasteAtLine(row);
  if (expandedId) {
    buffer.togglePasteExpansion(expandedId, row, col);
    return true;
  }
  appEvents.emit("transient-message" /* TransientMessage */, {
    message: "Move cursor within placeholder to expand",
    type: "hint" /* Hint */
  });
  return true;
}
var InputPrompt = ({
  onSubmit,
  onClearScreen,
  config,
  slashCommands,
  commandContext,
  placeholder = "  Type your message or @path/to/file",
  focus = true,
  setShellModeActive,
  approvalMode,
  onEscapePromptChange,
  onSuggestionsVisibilityChange,
  vimHandleInput,
  isEmbeddedShellFocused,
  setQueueErrorMessage,
  streamingState,
  popAllMessages,
  onQueueMessage,
  suggestionsPosition = "below",
  setBannerVisible
}) => {
  const inputState = useInputState();
  const {
    buffer,
    userMessages,
    shellModeActive,
    copyModeEnabled,
    inputWidth,
    suggestionsWidth
  } = inputState;
  const isHelpDismissKey = useIsHelpDismissKey();
  const keyMatchers = useKeyMatchers();
  const { stdout } = use_stdout_default();
  const { merged: settings } = useSettings();
  const kittyProtocol = useKittyKeyboardProtocol();
  const isShellFocused = useShellFocusState();
  const {
    setEmbeddedShellFocused,
    setShortcutsHelpVisible,
    toggleCleanUiDetailsVisible
  } = useUIActions();
  const {
    terminalWidth,
    activePtyId,
    history,
    backgroundTasks,
    backgroundTaskHeight,
    shortcutsHelpVisible
  } = useUIState();
  const [suppressCompletion, setSuppressCompletion] = (0, import_react85.useState)(false);
  const { handlePress: registerPlainTabPress, resetCount: resetPlainTabPress } = useRepeatedKeyPress({
    windowMs: DOUBLE_TAB_CLEAN_UI_TOGGLE_WINDOW_MS
  });
  const [showEscapePrompt, setShowEscapePrompt] = (0, import_react85.useState)(false);
  const { handlePress: handleEscPress, resetCount: resetEscapeState } = useRepeatedKeyPress({
    windowMs: 500,
    onRepeat: (count) => {
      if (count === 1) {
        setShowEscapePrompt(true);
      } else if (count === 2) {
        resetEscapeState();
        if (buffer.text.length > 0) {
          buffer.setText("");
          resetCompletionState();
        } else if (history.length > 0) {
          onSubmit("/rewind");
        } else {
          coreEvents.emitFeedback("info", "Nothing to rewind to");
        }
      }
    },
    onReset: () => setShowEscapePrompt(false)
  });
  const [recentUnsafePasteTime, setRecentUnsafePasteTime] = (0, import_react85.useState)(null);
  const pasteTimeoutRef = (0, import_react85.useRef)(null);
  const innerBoxRef = (0, import_react85.useRef)(null);
  const hasUserNavigatedSuggestions = (0, import_react85.useRef)(false);
  const listRef = (0, import_react85.useRef)(null);
  const [reverseSearchActive, setReverseSearchActive] = (0, import_react85.useState)(false);
  const [commandSearchActive, setCommandSearchActive] = (0, import_react85.useState)(false);
  const [textBeforeReverseSearch, setTextBeforeReverseSearch] = (0, import_react85.useState)("");
  const [cursorPosition, setCursorPosition] = (0, import_react85.useState)([
    0,
    0
  ]);
  const [expandedSuggestionIndex, setExpandedSuggestionIndex] = (0, import_react85.useState)(-1);
  const shellHistory = useShellHistory(config.getProjectRoot(), config.storage);
  const shellHistoryData = shellHistory.history;
  const completion = useCommandCompletion({
    buffer,
    cwd: config.getTargetDir(),
    slashCommands,
    commandContext,
    reverseSearchActive,
    shellModeActive,
    config,
    active: !suppressCompletion
  });
  const reverseSearchCompletion = useReverseSearchCompletion(
    buffer,
    shellHistoryData,
    reverseSearchActive
  );
  const reversedUserMessages = (0, import_react85.useMemo)(
    () => [...userMessages].reverse(),
    [userMessages]
  );
  const commandSearchCompletion = useReverseSearchCompletion(
    buffer,
    reversedUserMessages,
    commandSearchActive
  );
  const resetCompletionState = completion.resetCompletionState;
  const resetReverseSearchCompletionState = reverseSearchCompletion.resetCompletionState;
  const resetCommandSearchCompletionState = commandSearchCompletion.resetCompletionState;
  const getActiveCompletion = (0, import_react85.useCallback)(() => {
    if (commandSearchActive) return commandSearchCompletion;
    if (reverseSearchActive) return reverseSearchCompletion;
    return completion;
  }, [
    commandSearchActive,
    commandSearchCompletion,
    reverseSearchActive,
    reverseSearchCompletion,
    completion
  ]);
  const activeCompletion = getActiveCompletion();
  const shouldShowSuggestions = activeCompletion.showSuggestions;
  const {
    forceShowShellSuggestions,
    setForceShowShellSuggestions,
    isShellSuggestionsVisible
  } = completion;
  const showCursor = focus && isShellFocused && !isEmbeddedShellFocused && !copyModeEnabled;
  (0, import_react85.useEffect)(() => {
    appEvents.emit("scroll-to-bottom" /* ScrollToBottom */);
  }, [buffer.text, buffer.cursor]);
  (0, import_react85.useEffect)(() => {
    if (onEscapePromptChange) {
      onEscapePromptChange(showEscapePrompt);
    }
  }, [showEscapePrompt, onEscapePromptChange]);
  (0, import_react85.useEffect)(
    () => () => {
      if (pasteTimeoutRef.current) {
        clearTimeout(pasteTimeoutRef.current);
      }
    },
    []
  );
  const handleSubmitAndClear = (0, import_react85.useCallback)(
    (submittedValue) => {
      let processedValue = submittedValue;
      if (buffer.pastedContent) {
        processedValue = expandPastePlaceholders(
          processedValue,
          buffer.pastedContent
        );
      }
      if (shellModeActive) {
        shellHistory.addCommandToHistory(processedValue);
      }
      buffer.setText("");
      onSubmit(processedValue);
      resetCompletionState();
      resetReverseSearchCompletionState();
    },
    [
      buffer,
      onSubmit,
      resetCompletionState,
      shellModeActive,
      shellHistory,
      resetReverseSearchCompletionState
    ]
  );
  const customSetTextAndResetCompletionSignal = (0, import_react85.useCallback)(
    (newText, cursorPosition2) => {
      buffer.setText(newText, cursorPosition2);
      setSuppressCompletion(true);
    },
    [buffer, setSuppressCompletion]
  );
  const inputHistory = useInputHistory({
    userMessages,
    onSubmit: handleSubmitAndClear,
    isActive: (!(completion.showSuggestions && isShellSuggestionsVisible) || completion.suggestions.length === 1) && !shellModeActive,
    currentQuery: buffer.text,
    currentCursorOffset: buffer.getOffset(),
    onChange: customSetTextAndResetCompletionSignal
  });
  const handleSubmit = (0, import_react85.useCallback)(
    (submittedValue) => {
      const trimmedMessage = submittedValue.trim();
      const isSlash = isSlashCommand(trimmedMessage);
      const isShell = shellModeActive;
      if ((isSlash || isShell) && streamingState === "responding" /* Responding */) {
        if (isSlash) {
          const { commandToExecute } = parseSlashCommand(
            trimmedMessage,
            slashCommands
          );
          if (commandToExecute?.isSafeConcurrent) {
            handleSubmitAndClear(trimmedMessage);
            return;
          }
        }
        setQueueErrorMessage(
          `${isShell ? "Shell" : "Slash"} commands cannot be queued`
        );
        return;
      }
      inputHistory.handleSubmit(trimmedMessage);
    },
    [
      inputHistory,
      shellModeActive,
      streamingState,
      setQueueErrorMessage,
      slashCommands,
      handleSubmitAndClear
    ]
  );
  (0, import_react85.useEffect)(() => {
    if (suppressCompletion) {
      resetCompletionState();
      resetReverseSearchCompletionState();
      resetCommandSearchCompletionState();
      setExpandedSuggestionIndex(-1);
    }
  }, [
    suppressCompletion,
    buffer.text,
    resetCompletionState,
    setSuppressCompletion,
    resetReverseSearchCompletionState,
    resetCommandSearchCompletionState,
    setExpandedSuggestionIndex
  ]);
  const tryLoadQueuedMessages = (0, import_react85.useCallback)(() => {
    if (buffer.text.trim() === "" && popAllMessages) {
      const allMessages = popAllMessages();
      if (allMessages) {
        buffer.setText(allMessages);
        return true;
      } else {
        inputHistory.navigateUp();
      }
      return true;
    }
    return false;
  }, [buffer, popAllMessages, inputHistory]);
  const handleClipboardPaste = (0, import_react85.useCallback)(async () => {
    if (shortcutsHelpVisible) {
      setShortcutsHelpVisible(false);
    }
    try {
      if (await clipboardHasImage()) {
        const imagePath = await saveClipboardImage(config.getTargetDir());
        if (imagePath) {
          cleanupOldClipboardImages(config.getTargetDir()).catch(() => {
          });
          const relativePath = path11.relative(config.getTargetDir(), imagePath);
          const insertText = `@${relativePath}`;
          const currentText = buffer.text;
          const offset = buffer.getOffset();
          let textToInsert = insertText;
          const charBefore = offset > 0 ? currentText[offset - 1] : "";
          const charAfter = offset < currentText.length ? currentText[offset] : "";
          if (charBefore && charBefore !== " " && charBefore !== "\n") {
            textToInsert = " " + textToInsert;
          }
          if (!charAfter || charAfter !== " " && charAfter !== "\n") {
            textToInsert = textToInsert + " ";
          }
          buffer.replaceRangeByOffset(offset, offset, textToInsert);
        }
      }
      if (settings.experimental?.useOSC52Paste) {
        stdout.write("\x1B]52;c;?\x07");
      } else {
        const textToInsert = await clipboardy_default.read();
        const escapedText = settings.ui?.escapePastedAtSymbols ? escapeAtSymbols(textToInsert) : textToInsert;
        buffer.insert(escapedText, { paste: true });
        if (isLargePaste(textToInsert)) {
          appEvents.emit("transient-message" /* TransientMessage */, {
            message: `Press ${formatCommand("app.expandPaste" /* EXPAND_PASTE */)} to expand pasted text`,
            type: "hint" /* Hint */
          });
        }
      }
    } catch (error) {
      debugLogger.error("Error handling paste:", error);
    }
  }, [
    buffer,
    config,
    stdout,
    settings,
    shortcutsHelpVisible,
    setShortcutsHelpVisible
  ]);
  useMouseClick(
    innerBoxRef,
    (_event, relX, relY) => {
      setSuppressCompletion(true);
      if (isEmbeddedShellFocused) {
        setEmbeddedShellFocused(false);
      }
      const currentScrollTop = Math.round(
        listRef.current?.getScrollState().scrollTop ?? buffer.visualScrollRow
      );
      const visualRow = currentScrollTop + relY;
      buffer.moveToVisualPosition(visualRow, relX);
    },
    { isActive: focus }
  );
  const isAlternateBuffer = useAlternateBuffer();
  useMouseClick(
    innerBoxRef,
    (_event, relX, relY) => {
      if (!isAlternateBuffer) return;
      const currentScrollTop = Math.round(
        listRef.current?.getScrollState().scrollTop ?? buffer.visualScrollRow
      );
      const visualLine = buffer.allVisualLines[currentScrollTop + relY];
      if (!visualLine) return;
      const isPastEndOfLine = relX >= stringWidth(visualLine);
      const logicalPos = isPastEndOfLine ? null : buffer.getLogicalPositionFromVisual(currentScrollTop + relY, relX);
      if (logicalPos) {
        const transform = getTransformUnderCursor(
          logicalPos.row,
          logicalPos.col,
          buffer.transformationsByLine,
          { includeEdge: true }
        );
        if (transform?.type === "paste" && transform.id) {
          buffer.togglePasteExpansion(
            transform.id,
            logicalPos.row,
            logicalPos.col
          );
          return;
        }
      }
      const visualRow = currentScrollTop + relY;
      const mapEntry = buffer.visualToLogicalMap[visualRow];
      const row = mapEntry ? mapEntry[0] : visualRow;
      const expandedId = buffer.getExpandedPasteAtLine(row);
      if (expandedId) {
        buffer.togglePasteExpansion(
          expandedId,
          row,
          logicalPos?.col ?? relX
          // Fallback to relX if past end of line
        );
      }
    },
    { isActive: focus, name: "double-click" }
  );
  useMouse(
    (event) => {
      if (event.name === "right-release") {
        setSuppressCompletion(false);
        handleClipboardPaste();
      }
    },
    { isActive: focus }
  );
  const handleInput = (0, import_react85.useCallback)(
    (key) => {
      const isHistoryUp = !shellModeActive && (keyMatchers["history.previous" /* HISTORY_UP */](key) || keyMatchers["nav.up" /* NAVIGATION_UP */](key) && (buffer.allVisualLines.length === 1 || buffer.visualCursor[0] === 0 && buffer.visualScrollRow === 0));
      const isHistoryDown = !shellModeActive && (keyMatchers["history.next" /* HISTORY_DOWN */](key) || keyMatchers["nav.down" /* NAVIGATION_DOWN */](key) && (buffer.allVisualLines.length === 1 || buffer.visualCursor[0] === buffer.allVisualLines.length - 1));
      const isHistoryNav = isHistoryUp || isHistoryDown;
      const isCursorMovement = keyMatchers["cursor.left" /* MOVE_LEFT */](key) || keyMatchers["cursor.right" /* MOVE_RIGHT */](key) || keyMatchers["cursor.up" /* MOVE_UP */](key) || keyMatchers["cursor.down" /* MOVE_DOWN */](key) || keyMatchers["cursor.wordLeft" /* MOVE_WORD_LEFT */](key) || keyMatchers["cursor.wordRight" /* MOVE_WORD_RIGHT */](key) || keyMatchers["cursor.home" /* HOME */](key) || keyMatchers["cursor.end" /* END */](key);
      const isSuggestionsNav = shouldShowSuggestions && (keyMatchers["suggest.focusPrevious" /* COMPLETION_UP */](key) || keyMatchers["suggest.focusNext" /* COMPLETION_DOWN */](key) || keyMatchers["suggest.expand" /* EXPAND_SUGGESTION */](key) || keyMatchers["suggest.collapse" /* COLLAPSE_SUGGESTION */](key) || keyMatchers["suggest.accept" /* ACCEPT_SUGGESTION */](key));
      if (!isSuggestionsNav) {
        setSuppressCompletion(
          isHistoryNav || isCursorMovement || keyMatchers["basic.cancel" /* ESCAPE */](key)
        );
        hasUserNavigatedSuggestions.current = false;
        if (key.name !== "tab") {
          setForceShowShellSuggestions(false);
        }
      }
      if (!focus && key.name !== "paste") {
        return false;
      }
      if (shortcutsHelpVisible && key.name === "escape") {
        setShortcutsHelpVisible(false);
        return true;
      }
      const isGenerating = streamingState === "responding" /* Responding */ || streamingState === "waiting_for_confirmation" /* WaitingForConfirmation */;
      const isQueueMessageKey = keyMatchers["input.queueMessage" /* QUEUE_MESSAGE */](key);
      const isPlainTab = key.name === "tab" && !key.shift && !key.alt && !key.ctrl && !key.cmd;
      const hasTabCompletionInteraction = completion.showSuggestions && isShellSuggestionsVisible || Boolean(completion.promptCompletion.text) || reverseSearchActive || commandSearchActive;
      if (isGenerating && isQueueMessageKey && !hasTabCompletionInteraction && buffer.text.trim().length > 0) {
        const trimmedMessage = buffer.text.trim();
        const isSlash = isSlashCommand(trimmedMessage);
        if (isSlash || shellModeActive) {
          setQueueErrorMessage(
            `${shellModeActive ? "Shell" : "Slash"} commands cannot be queued`
          );
        } else if (onQueueMessage) {
          onQueueMessage(buffer.text);
          buffer.setText("");
          resetCompletionState();
          resetReverseSearchCompletionState();
        }
        resetPlainTabPress();
        return true;
      }
      if (isPlainTab && shellModeActive) {
        resetPlainTabPress();
        if (!shouldShowSuggestions) {
          setSuppressCompletion(false);
          if (completion.promptCompletion.text) {
            completion.promptCompletion.accept();
            return true;
          } else if (completion.suggestions.length > 0 && !forceShowShellSuggestions) {
            setForceShowShellSuggestions(true);
            return true;
          }
        }
      } else if (isPlainTab) {
        if (!hasTabCompletionInteraction) {
          if (registerPlainTabPress() === 2) {
            toggleCleanUiDetailsVisible();
            resetPlainTabPress();
            return true;
          }
        } else {
          resetPlainTabPress();
        }
      } else {
        resetPlainTabPress();
      }
      if (key.name === "paste") {
        if (shortcutsHelpVisible) {
          setShortcutsHelpVisible(false);
        }
        if (!isTerminalPasteTrusted(kittyProtocol.enabled)) {
          setRecentUnsafePasteTime(Date.now());
          if (pasteTimeoutRef.current) {
            clearTimeout(pasteTimeoutRef.current);
          }
          pasteTimeoutRef.current = setTimeout(() => {
            setRecentUnsafePasteTime(null);
            pasteTimeoutRef.current = null;
          }, 40);
        }
        if (settings.ui?.escapePastedAtSymbols) {
          buffer.handleInput({
            ...key,
            sequence: escapeAtSymbols(key.sequence || "")
          });
        } else {
          buffer.handleInput(key);
        }
        if (key.sequence && isLargePaste(key.sequence)) {
          appEvents.emit("transient-message" /* TransientMessage */, {
            message: `Press ${formatCommand("app.expandPaste" /* EXPAND_PASTE */)} to expand pasted text`,
            type: "hint" /* Hint */
          });
        }
        return true;
      }
      if (shortcutsHelpVisible && isHelpDismissKey(key)) {
        setShortcutsHelpVisible(false);
      }
      if (shortcutsHelpVisible) {
        if (key.sequence === "?" && key.insertable) {
          setShortcutsHelpVisible(false);
          buffer.handleInput(key);
          return true;
        }
        if (key.name === "backspace" || key.sequence === "\b") {
          setShortcutsHelpVisible(false);
          return true;
        }
        if (key.insertable) {
          setShortcutsHelpVisible(false);
        }
      }
      if (key.sequence === "?" && key.insertable && !shortcutsHelpVisible && buffer.text.length === 0) {
        setShortcutsHelpVisible(true);
        return true;
      }
      if (vimHandleInput && vimHandleInput(key)) {
        return true;
      }
      if (key.name !== "escape") {
        resetEscapeState();
      }
      if (keyMatchers["app.expandPaste" /* EXPAND_PASTE */](key)) {
        const handled2 = tryTogglePasteExpansion(buffer);
        if (handled2) return true;
      }
      if (key.sequence === "!" && buffer.text === "" && !(completion.showSuggestions && isShellSuggestionsVisible)) {
        setShellModeActive(!shellModeActive);
        buffer.setText("");
        return true;
      }
      if (keyMatchers["basic.cancel" /* ESCAPE */](key)) {
        const cancelSearch = (setActive, resetCompletion) => {
          setActive(false);
          resetCompletion();
          buffer.setText(textBeforeReverseSearch);
          const offset = logicalPosToOffset(
            buffer.lines,
            cursorPosition[0],
            cursorPosition[1]
          );
          buffer.moveToOffset(offset);
          setExpandedSuggestionIndex(-1);
        };
        if (reverseSearchActive) {
          cancelSearch(
            setReverseSearchActive,
            reverseSearchCompletion.resetCompletionState
          );
          return true;
        }
        if (commandSearchActive) {
          cancelSearch(
            setCommandSearchActive,
            commandSearchCompletion.resetCompletionState
          );
          return true;
        }
        if (completion.showSuggestions && isShellSuggestionsVisible) {
          completion.resetCompletionState();
          setExpandedSuggestionIndex(-1);
          resetEscapeState();
          return true;
        }
        if (shellModeActive) {
          setShellModeActive(false);
          resetEscapeState();
          return true;
        }
        if (isGenerating) {
          return false;
        }
        handleEscPress();
        return true;
      }
      if (keyMatchers["app.clearScreen" /* CLEAR_SCREEN */](key)) {
        setBannerVisible(false);
        onClearScreen();
        return true;
      }
      if (shellModeActive && keyMatchers["history.search.start" /* REVERSE_SEARCH */](key)) {
        setReverseSearchActive(true);
        setTextBeforeReverseSearch(buffer.text);
        setCursorPosition(buffer.cursor);
        return true;
      }
      if (reverseSearchActive || commandSearchActive) {
        const isCommandSearch = commandSearchActive;
        const sc = isCommandSearch ? commandSearchCompletion : reverseSearchCompletion;
        const {
          activeSuggestionIndex,
          navigateUp,
          navigateDown,
          showSuggestions,
          suggestions
        } = sc;
        const setActive = isCommandSearch ? setCommandSearchActive : setReverseSearchActive;
        const resetState = sc.resetCompletionState;
        if (showSuggestions) {
          if (keyMatchers["nav.up" /* NAVIGATION_UP */](key)) {
            navigateUp();
            return true;
          }
          if (keyMatchers["nav.down" /* NAVIGATION_DOWN */](key)) {
            navigateDown();
            return true;
          }
          if (keyMatchers["suggest.collapse" /* COLLAPSE_SUGGESTION */](key)) {
            if (suggestions[activeSuggestionIndex].value.length >= MAX_WIDTH) {
              setExpandedSuggestionIndex(-1);
              return true;
            }
          }
          if (keyMatchers["suggest.expand" /* EXPAND_SUGGESTION */](key)) {
            if (suggestions[activeSuggestionIndex].value.length >= MAX_WIDTH) {
              setExpandedSuggestionIndex(activeSuggestionIndex);
              return true;
            }
          }
          if (keyMatchers["history.search.accept" /* ACCEPT_SUGGESTION_REVERSE_SEARCH */](key)) {
            sc.handleAutocomplete(activeSuggestionIndex);
            resetState();
            setActive(false);
            return true;
          }
        }
        if (keyMatchers["history.search.submit" /* SUBMIT_REVERSE_SEARCH */](key)) {
          const textToSubmit = showSuggestions && activeSuggestionIndex > -1 ? suggestions[activeSuggestionIndex].value : buffer.text;
          handleSubmit(textToSubmit);
          resetState();
          setActive(false);
          return true;
        }
        if (keyMatchers["nav.up" /* NAVIGATION_UP */](key) || keyMatchers["nav.down" /* NAVIGATION_DOWN */](key)) {
          return true;
        }
      }
      if (completion.isPerfectMatch && keyMatchers["input.submit" /* SUBMIT */](key) && recentUnsafePasteTime === null && (!(completion.showSuggestions && isShellSuggestionsVisible) || completion.activeSuggestionIndex <= 0 && !hasUserNavigatedSuggestions.current)) {
        handleSubmit(buffer.text);
        return true;
      }
      if (keyMatchers["input.newline" /* NEWLINE */](key)) {
        buffer.newline();
        return true;
      }
      if (completion.showSuggestions && isShellSuggestionsVisible) {
        if (completion.suggestions.length > 1) {
          if (keyMatchers["suggest.focusPrevious" /* COMPLETION_UP */](key)) {
            completion.navigateUp();
            hasUserNavigatedSuggestions.current = true;
            setExpandedSuggestionIndex(-1);
            return true;
          }
          if (keyMatchers["suggest.focusNext" /* COMPLETION_DOWN */](key)) {
            completion.navigateDown();
            hasUserNavigatedSuggestions.current = true;
            setExpandedSuggestionIndex(-1);
            return true;
          }
        }
        if (keyMatchers["suggest.accept" /* ACCEPT_SUGGESTION */](key)) {
          if (completion.suggestions.length > 0) {
            const targetIndex = completion.activeSuggestionIndex === -1 ? 0 : completion.activeSuggestionIndex;
            if (targetIndex < completion.suggestions.length) {
              const suggestion = completion.suggestions[targetIndex];
              const isEnterKey = key.name === "enter" && !key.ctrl;
              if (isEnterKey && shellModeActive) {
                if (hasUserNavigatedSuggestions.current) {
                  completion.handleAutocomplete(
                    completion.activeSuggestionIndex
                  );
                  setExpandedSuggestionIndex(-1);
                  hasUserNavigatedSuggestions.current = false;
                  return true;
                }
                completion.resetCompletionState();
                setExpandedSuggestionIndex(-1);
                hasUserNavigatedSuggestions.current = false;
                if (buffer.text.trim()) {
                  handleSubmit(buffer.text);
                }
                return true;
              }
              if (isEnterKey && buffer.text.startsWith("/")) {
                if (suggestion.submitValue) {
                  setExpandedSuggestionIndex(-1);
                  handleSubmit(suggestion.submitValue.trim());
                  return true;
                }
                const { isArgumentCompletion, leafCommand } = completion.slashCompletionRange;
                if (isArgumentCompletion && isAutoExecutableCommand(leafCommand)) {
                  const completedText = completion.getCompletedText(suggestion);
                  if (completedText) {
                    setExpandedSuggestionIndex(-1);
                    handleSubmit(completedText.trim());
                    return true;
                  }
                } else if (!isArgumentCompletion) {
                  const command = completion.getCommandFromSuggestion(suggestion);
                  if (command && isAutoExecutableCommand(command) && !command.completion) {
                    const completedText = completion.getCompletedText(suggestion);
                    if (completedText) {
                      setExpandedSuggestionIndex(-1);
                      handleSubmit(completedText.trim());
                      return true;
                    }
                  }
                }
              }
              completion.handleAutocomplete(targetIndex);
              setExpandedSuggestionIndex(-1);
            }
          }
          return true;
        }
      }
      if (key.name === "tab" && !key.shift && !(completion.showSuggestions && isShellSuggestionsVisible) && completion.promptCompletion.text) {
        completion.promptCompletion.accept();
        return true;
      }
      if (!shellModeActive) {
        if (keyMatchers["history.search.start" /* REVERSE_SEARCH */](key)) {
          setCommandSearchActive(true);
          setTextBeforeReverseSearch(buffer.text);
          setCursorPosition(buffer.cursor);
          return true;
        }
        if (isHistoryUp) {
          if (keyMatchers["nav.up" /* NAVIGATION_UP */](key) && buffer.visualCursor[1] > 0) {
            buffer.move("home");
            return true;
          }
          if (tryLoadQueuedMessages()) {
            return true;
          }
          inputHistory.navigateUp();
          return true;
        }
        if (isHistoryDown) {
          if (keyMatchers["nav.down" /* NAVIGATION_DOWN */](key) && buffer.visualCursor[1] < cpLen(buffer.allVisualLines[buffer.visualCursor[0]] || "")) {
            buffer.move("end");
            return true;
          }
          inputHistory.navigateDown();
          return true;
        }
      } else {
        if (keyMatchers["nav.up" /* NAVIGATION_UP */](key)) {
          if ((buffer.allVisualLines.length === 1 || buffer.visualCursor[0] === 0 && buffer.visualScrollRow === 0) && buffer.visualCursor[1] > 0) {
            buffer.move("home");
            return true;
          }
          const prevCommand = shellHistory.getPreviousCommand();
          if (prevCommand !== null) buffer.setText(prevCommand);
          return true;
        }
        if (keyMatchers["nav.down" /* NAVIGATION_DOWN */](key)) {
          if ((buffer.allVisualLines.length === 1 || buffer.visualCursor[0] === buffer.allVisualLines.length - 1) && buffer.visualCursor[1] < cpLen(buffer.allVisualLines[buffer.visualCursor[0]] || "")) {
            buffer.move("end");
            return true;
          }
          const nextCommand = shellHistory.getNextCommand();
          if (nextCommand !== null) buffer.setText(nextCommand);
          return true;
        }
      }
      if (keyMatchers["input.submit" /* SUBMIT */](key)) {
        if (buffer.text.trim()) {
          if (recentUnsafePasteTime !== null) {
            buffer.newline();
            return true;
          }
          const [row, col] = buffer.cursor;
          const line = buffer.lines[row];
          const charBefore = col > 0 ? cpSlice(line, col - 1, col) : "";
          if (charBefore === "\\") {
            buffer.backspace();
            buffer.newline();
          } else {
            handleSubmit(buffer.text);
          }
        }
        return true;
      }
      if (keyMatchers["cursor.home" /* HOME */](key)) {
        buffer.move("home");
        return true;
      }
      if (keyMatchers["cursor.end" /* END */](key)) {
        buffer.move("end");
        return true;
      }
      if (keyMatchers["edit.deleteRightAll" /* KILL_LINE_RIGHT */](key)) {
        buffer.killLineRight();
        return true;
      }
      if (keyMatchers["edit.deleteLeftAll" /* KILL_LINE_LEFT */](key)) {
        buffer.killLineLeft();
        return true;
      }
      if (keyMatchers["edit.deleteWordLeft" /* DELETE_WORD_BACKWARD */](key)) {
        buffer.deleteWordLeft();
        return true;
      }
      if (keyMatchers["input.openExternalEditor" /* OPEN_EXTERNAL_EDITOR */](key)) {
        buffer.openInExternalEditor();
        return true;
      }
      if (keyMatchers["input.deprecatedOpenExternalEditor" /* DEPRECATED_OPEN_EXTERNAL_EDITOR */](key)) {
        const cmdKey = formatCommand("input.openExternalEditor" /* OPEN_EXTERNAL_EDITOR */);
        appEvents.emit("transient-message" /* TransientMessage */, {
          message: `Use ${cmdKey} to open the external editor.`,
          type: "hint" /* Hint */
        });
        return true;
      }
      if (keyMatchers["input.paste" /* PASTE_CLIPBOARD */](key)) {
        handleClipboardPaste();
        return true;
      }
      if (keyMatchers["background.toggle" /* TOGGLE_BACKGROUND_SHELL */](key)) {
        return false;
      }
      if (keyMatchers["app.focusShellInput" /* FOCUS_SHELL_INPUT */](key)) {
        if (activePtyId || backgroundTasks.size > 0 && backgroundTaskHeight > 0) {
          setEmbeddedShellFocused(true);
          return true;
        }
        return false;
      }
      const handled = buffer.handleInput(key);
      if (handled) {
        if (keyMatchers["edit.clear" /* CLEAR_INPUT */](key)) {
          resetCompletionState();
        }
        if (completion.promptCompletion.text && key.sequence && key.sequence.length === 1 && !key.alt && !key.ctrl && !key.cmd) {
          completion.promptCompletion.clear();
          setExpandedSuggestionIndex(-1);
        }
      }
      return handled;
    },
    [
      focus,
      buffer,
      completion,
      setForceShowShellSuggestions,
      shellModeActive,
      setShellModeActive,
      onClearScreen,
      inputHistory,
      handleSubmit,
      shellHistory,
      reverseSearchCompletion,
      handleClipboardPaste,
      resetCompletionState,
      resetEscapeState,
      vimHandleInput,
      reverseSearchActive,
      textBeforeReverseSearch,
      cursorPosition,
      recentUnsafePasteTime,
      commandSearchActive,
      commandSearchCompletion,
      kittyProtocol.enabled,
      shortcutsHelpVisible,
      setShortcutsHelpVisible,
      tryLoadQueuedMessages,
      onQueueMessage,
      setQueueErrorMessage,
      resetReverseSearchCompletionState,
      setBannerVisible,
      activePtyId,
      setEmbeddedShellFocused,
      backgroundTasks.size,
      backgroundTaskHeight,
      streamingState,
      handleEscPress,
      registerPlainTabPress,
      resetPlainTabPress,
      toggleCleanUiDetailsVisible,
      shouldShowSuggestions,
      isShellSuggestionsVisible,
      forceShowShellSuggestions,
      keyMatchers,
      isHelpDismissKey,
      settings
    ]
  );
  useKeypress(handleInput, {
    isActive: !isEmbeddedShellFocused && !copyModeEnabled,
    priority: true
  });
  const [cursorVisualRowAbsolute, cursorVisualColAbsolute] = buffer.visualCursor;
  const getGhostTextLines = (0, import_react85.useCallback)(() => {
    if (!completion.promptCompletion.text || !buffer.text || !completion.promptCompletion.text.startsWith(buffer.text)) {
      return { inlineGhost: "", additionalLines: [] };
    }
    const ghostSuffix = completion.promptCompletion.text.slice(
      buffer.text.length
    );
    if (!ghostSuffix) {
      return { inlineGhost: "", additionalLines: [] };
    }
    const currentLogicalLine = buffer.lines[buffer.cursor[0]] || "";
    const cursorCol = buffer.cursor[1];
    const textBeforeCursor = cpSlice(currentLogicalLine, 0, cursorCol);
    const usedWidth = stringWidth(textBeforeCursor);
    const remainingWidth = Math.max(0, inputWidth - usedWidth);
    const ghostTextLinesRaw = ghostSuffix.split("\n");
    const firstLineRaw = ghostTextLinesRaw.shift() || "";
    let inlineGhost2 = "";
    let remainingFirstLine = "";
    if (stringWidth(firstLineRaw) <= remainingWidth) {
      inlineGhost2 = firstLineRaw;
    } else {
      const words = firstLineRaw.split(" ");
      let currentLine = "";
      let wordIdx = 0;
      for (const word of words) {
        const prospectiveLine = currentLine ? `${currentLine} ${word}` : word;
        if (stringWidth(prospectiveLine) > remainingWidth) {
          break;
        }
        currentLine = prospectiveLine;
        wordIdx++;
      }
      inlineGhost2 = currentLine;
      if (words.length > wordIdx) {
        remainingFirstLine = words.slice(wordIdx).join(" ");
      }
    }
    const linesToWrap = [];
    if (remainingFirstLine) {
      linesToWrap.push(remainingFirstLine);
    }
    linesToWrap.push(...ghostTextLinesRaw);
    const remainingGhostText = linesToWrap.join("\n");
    const additionalLines2 = [];
    if (remainingGhostText) {
      const textLines = remainingGhostText.split("\n");
      for (const textLine of textLines) {
        const words = textLine.split(" ");
        let currentLine = "";
        for (const word of words) {
          const prospectiveLine = currentLine ? `${currentLine} ${word}` : word;
          const prospectiveWidth = stringWidth(prospectiveLine);
          if (prospectiveWidth > inputWidth) {
            if (currentLine) {
              additionalLines2.push(currentLine);
            }
            let wordToProcess = word;
            while (stringWidth(wordToProcess) > inputWidth) {
              let part = "";
              const wordCP = toCodePoints(wordToProcess);
              let partWidth = 0;
              let splitIndex = 0;
              for (let i = 0; i < wordCP.length; i++) {
                const char = wordCP[i];
                const charWidth = stringWidth(char);
                if (partWidth + charWidth > inputWidth) {
                  break;
                }
                part += char;
                partWidth += charWidth;
                splitIndex = i + 1;
              }
              additionalLines2.push(part);
              wordToProcess = cpSlice(wordToProcess, splitIndex);
            }
            currentLine = wordToProcess;
          } else {
            currentLine = prospectiveLine;
          }
        }
        if (currentLine) {
          additionalLines2.push(currentLine);
        }
      }
    }
    return { inlineGhost: inlineGhost2, additionalLines: additionalLines2 };
  }, [
    completion.promptCompletion.text,
    buffer.text,
    buffer.lines,
    buffer.cursor,
    inputWidth
  ]);
  const { inlineGhost, additionalLines } = getGhostTextLines();
  const scrollableData = (0, import_react85.useMemo)(() => {
    const items = buffer.allVisualLines.map(
      (lineText, index) => ({
        type: "visualLine",
        lineText,
        absoluteVisualIdx: index
      })
    );
    additionalLines.forEach((ghostLine, index) => {
      items.push({
        type: "ghostLine",
        ghostLine,
        index
      });
    });
    return items;
  }, [buffer.allVisualLines, additionalLines]);
  const renderItem = (0, import_react85.useCallback)(
    ({ item }) => {
      if (item.type === "ghostLine") {
        const padding = Math.max(0, inputWidth - stringWidth(item.ghostLine));
        return /* @__PURE__ */ (0, import_jsx_runtime114.jsx)(Box_default, { height: 1, children: /* @__PURE__ */ (0, import_jsx_runtime114.jsxs)(Text, { color: theme.text.secondary, children: [
          item.ghostLine,
          " ".repeat(padding)
        ] }) });
      }
      const { lineText, absoluteVisualIdx } = item;
      const mapEntry = buffer.visualToLogicalMap[absoluteVisualIdx];
      if (!mapEntry) return /* @__PURE__ */ (0, import_jsx_runtime114.jsx)(Text, { children: " " });
      const isOnCursorLine = focus && absoluteVisualIdx === cursorVisualRowAbsolute;
      const renderedLine = [];
      const [logicalLineIdx] = mapEntry;
      const logicalLine = buffer.lines[logicalLineIdx] || "";
      const transformations = buffer.transformationsByLine[logicalLineIdx] ?? [];
      const tokens = parseInputForHighlighting(
        logicalLine,
        logicalLineIdx,
        transformations,
        ...focus && buffer.cursor[0] === logicalLineIdx ? [buffer.cursor[1]] : []
      );
      const visualStartCol = buffer.visualToTransformedMap[absoluteVisualIdx] ?? 0;
      const visualEndCol = visualStartCol + cpLen(lineText);
      const segments = parseSegmentsFromTokens(
        tokens,
        visualStartCol,
        visualEndCol
      );
      let charCount = 0;
      segments.forEach((seg, segIdx) => {
        const segLen = cpLen(seg.text);
        let display = seg.text;
        if (isOnCursorLine) {
          const relCol = cursorVisualColAbsolute;
          const segStart = charCount;
          const segEnd = segStart + segLen;
          if (relCol >= segStart && relCol < segEnd) {
            const charToHighlight = cpSlice(
              display,
              relCol - segStart,
              relCol - segStart + 1
            );
            const highlighted = showCursor ? import_chalk3.default.inverse(charToHighlight) : charToHighlight;
            display = cpSlice(display, 0, relCol - segStart) + highlighted + cpSlice(display, relCol - segStart + 1);
          }
          charCount = segEnd;
        } else {
          charCount += segLen;
        }
        const color = seg.type === "command" || seg.type === "file" || seg.type === "paste" ? theme.text.accent : theme.text.primary;
        renderedLine.push(
          /* @__PURE__ */ (0, import_jsx_runtime114.jsx)(Text, { color, children: display }, `token-${segIdx}`)
        );
      });
      const currentLineGhost = isOnCursorLine ? inlineGhost : "";
      if (isOnCursorLine && cursorVisualColAbsolute === cpLen(lineText) && !currentLineGhost) {
        renderedLine.push(
          /* @__PURE__ */ (0, import_jsx_runtime114.jsx)(Text, { children: showCursor ? import_chalk3.default.inverse(" ") : " " }, `cursor-end-${cursorVisualColAbsolute}`)
        );
      }
      const showCursorBeforeGhost = focus && isOnCursorLine && cursorVisualColAbsolute === cpLen(lineText) && currentLineGhost;
      return /* @__PURE__ */ (0, import_jsx_runtime114.jsx)(Box_default, { height: 1, children: /* @__PURE__ */ (0, import_jsx_runtime114.jsxs)(
        Text,
        {
          terminalCursorFocus: showCursor && isOnCursorLine,
          terminalCursorPosition: cpIndexToOffset(
            lineText,
            cursorVisualColAbsolute
          ),
          children: [
            renderedLine,
            showCursorBeforeGhost && (showCursor ? import_chalk3.default.inverse(" ") : " "),
            currentLineGhost && /* @__PURE__ */ (0, import_jsx_runtime114.jsx)(Text, { color: theme.text.secondary, children: currentLineGhost })
          ]
        }
      ) });
    },
    [
      buffer.visualToLogicalMap,
      buffer.lines,
      buffer.transformationsByLine,
      buffer.cursor,
      buffer.visualToTransformedMap,
      focus,
      cursorVisualRowAbsolute,
      cursorVisualColAbsolute,
      showCursor,
      inlineGhost,
      inputWidth
    ]
  );
  const useBackgroundColor = config.getUseBackgroundColor();
  const isLowColor = isLowColorDepth();
  const terminalBg = theme.background.primary || "black";
  const useLineFallback = (0, import_react85.useMemo)(() => {
    if (!useBackgroundColor) {
      return true;
    }
    if (isLowColor) {
      return !getSafeLowColorBackground(terminalBg);
    }
    return false;
  }, [useBackgroundColor, isLowColor, terminalBg]);
  const prevCursorRef = (0, import_react85.useRef)(buffer.visualCursor);
  const prevTextRef = (0, import_react85.useRef)(buffer.text);
  (0, import_react85.useEffect)(() => {
    const cursorChanged = prevCursorRef.current !== buffer.visualCursor;
    const textChanged = prevTextRef.current !== buffer.text;
    prevCursorRef.current = buffer.visualCursor;
    prevTextRef.current = buffer.text;
    if (!cursorChanged && !textChanged) return;
    if (!listRef.current || !focus) return;
    const { scrollTop, innerHeight } = listRef.current.getScrollState();
    if (innerHeight === 0) return;
    const cursorVisualRow = buffer.visualCursor[0];
    const actualScrollTop = Math.round(scrollTop);
    if (cursorVisualRow < actualScrollTop || cursorVisualRow >= actualScrollTop + innerHeight) {
      let newScrollTop = actualScrollTop;
      if (cursorVisualRow < actualScrollTop) {
        newScrollTop = cursorVisualRow;
      } else if (cursorVisualRow >= actualScrollTop + innerHeight) {
        newScrollTop = cursorVisualRow - innerHeight + 1;
      }
      listRef.current.scrollToIndex({ index: newScrollTop });
    }
  }, [buffer.visualCursor, buffer.text, focus]);
  const listBackgroundColor = useLineFallback || !useBackgroundColor ? void 0 : theme.background.input;
  (0, import_react85.useEffect)(() => {
    if (onSuggestionsVisibilityChange) {
      onSuggestionsVisibilityChange(shouldShowSuggestions);
    }
  }, [shouldShowSuggestions, onSuggestionsVisibilityChange]);
  const showAutoAcceptStyling = !shellModeActive && approvalMode === ApprovalMode.AUTO_EDIT;
  const showYoloStyling = !shellModeActive && approvalMode === ApprovalMode.YOLO;
  const showPlanStyling = !shellModeActive && approvalMode === ApprovalMode.PLAN;
  let statusColor;
  let statusText = "";
  if (shellModeActive) {
    statusColor = theme.ui.symbol;
    statusText = "Shell mode";
  } else if (showYoloStyling) {
    statusColor = theme.status.error;
    statusText = "YOLO mode";
  } else if (showPlanStyling) {
    statusColor = theme.status.success;
    statusText = "Plan mode";
  } else if (showAutoAcceptStyling) {
    statusColor = theme.status.warning;
    statusText = "Accepting edits";
  }
  const suggestionsNode = shouldShowSuggestions ? /* @__PURE__ */ (0, import_jsx_runtime114.jsx)(Box_default, { paddingRight: 2, children: /* @__PURE__ */ (0, import_jsx_runtime114.jsx)(
    SuggestionsDisplay,
    {
      suggestions: activeCompletion.suggestions,
      activeIndex: activeCompletion.activeSuggestionIndex,
      isLoading: activeCompletion.isLoadingSuggestions,
      width: suggestionsWidth,
      scrollOffset: activeCompletion.visibleStartIndex,
      userInput: buffer.text,
      mode: completion.completionMode === "AT" /* AT */ || completion.completionMode === "SHELL" /* SHELL */ ? "reverse" : buffer.text.startsWith("/") && !reverseSearchActive && !commandSearchActive ? "slash" : "reverse",
      expandedIndex: expandedSuggestionIndex
    }
  ) }) : null;
  const borderColor = isShellFocused && !isEmbeddedShellFocused ? statusColor ?? theme.ui.focus : theme.border.default;
  return /* @__PURE__ */ (0, import_jsx_runtime114.jsxs)(import_jsx_runtime114.Fragment, { children: [
    suggestionsPosition === "above" && suggestionsNode,
    useLineFallback ? /* @__PURE__ */ (0, import_jsx_runtime114.jsx)(
      Box_default,
      {
        borderStyle: "round",
        borderTop: true,
        borderBottom: false,
        borderLeft: false,
        borderRight: false,
        borderColor,
        width: terminalWidth,
        flexDirection: "row",
        alignItems: "flex-start",
        height: 0
      }
    ) : null,
    /* @__PURE__ */ (0, import_jsx_runtime114.jsx)(
      HalfLinePaddedBox,
      {
        backgroundBaseColor: theme.background.input,
        backgroundOpacity: 1,
        useBackgroundColor,
        children: /* @__PURE__ */ (0, import_jsx_runtime114.jsxs)(
          Box_default,
          {
            flexGrow: 1,
            flexDirection: "row",
            paddingX: 1,
            borderColor,
            borderStyle: useLineFallback ? "round" : void 0,
            borderTop: false,
            borderBottom: false,
            borderLeft: !useBackgroundColor,
            borderRight: !useBackgroundColor,
            children: [
              /* @__PURE__ */ (0, import_jsx_runtime114.jsxs)(
                Text,
                {
                  color: statusColor ?? theme.text.accent,
                  "aria-label": statusText || void 0,
                  children: [
                    shellModeActive ? reverseSearchActive ? /* @__PURE__ */ (0, import_jsx_runtime114.jsxs)(
                      Text,
                      {
                        color: theme.text.link,
                        "aria-label": SCREEN_READER_USER_PREFIX,
                        children: [
                          "(r:)",
                          " "
                        ]
                      }
                    ) : "!" : commandSearchActive ? /* @__PURE__ */ (0, import_jsx_runtime114.jsx)(Text, { color: theme.text.accent, children: "(r:) " }) : showYoloStyling ? "*" : ">",
                    " "
                  ]
                }
              ),
              /* @__PURE__ */ (0, import_jsx_runtime114.jsx)(Box_default, { flexGrow: 1, flexDirection: "column", ref: innerBoxRef, children: buffer.text.length === 0 && placeholder ? showCursor ? /* @__PURE__ */ (0, import_jsx_runtime114.jsxs)(
                Text,
                {
                  terminalCursorFocus: showCursor,
                  terminalCursorPosition: 0,
                  children: [
                    import_chalk3.default.inverse(placeholder.slice(0, 1)),
                    /* @__PURE__ */ (0, import_jsx_runtime114.jsx)(Text, { color: theme.text.secondary, children: placeholder.slice(1) })
                  ]
                }
              ) : /* @__PURE__ */ (0, import_jsx_runtime114.jsx)(Text, { color: theme.text.secondary, children: placeholder }) : /* @__PURE__ */ (0, import_jsx_runtime114.jsx)(
                Box_default,
                {
                  flexDirection: "column",
                  height: Math.min(buffer.viewportHeight, scrollableData.length),
                  width: "100%",
                  children: isAlternateBuffer ? /* @__PURE__ */ (0, import_jsx_runtime114.jsx)(
                    ScrollableListWithForwardRef,
                    {
                      ref: listRef,
                      hasFocus: focus,
                      data: scrollableData,
                      renderItem,
                      estimatedItemHeight: () => 1,
                      fixedItemHeight: true,
                      keyExtractor: (item) => item.type === "visualLine" ? `line-${item.absoluteVisualIdx}` : `ghost-${item.index}`,
                      width: inputWidth,
                      backgroundColor: listBackgroundColor,
                      containerHeight: Math.min(
                        buffer.viewportHeight,
                        scrollableData.length
                      )
                    }
                  ) : scrollableData.slice(
                    buffer.visualScrollRow,
                    buffer.visualScrollRow + buffer.viewportHeight
                  ).map((item, index) => {
                    const actualIndex = buffer.visualScrollRow + index;
                    const key = item.type === "visualLine" ? `line-${item.absoluteVisualIdx}` : `ghost-${item.index}`;
                    return /* @__PURE__ */ (0, import_jsx_runtime114.jsx)(import_react85.Fragment, { children: renderItem({ item, index: actualIndex }) }, key);
                  })
                }
              ) })
            ]
          }
        )
      }
    ),
    useLineFallback ? /* @__PURE__ */ (0, import_jsx_runtime114.jsx)(
      Box_default,
      {
        borderStyle: "round",
        borderTop: false,
        borderBottom: true,
        borderLeft: false,
        borderRight: false,
        borderColor,
        width: terminalWidth,
        flexDirection: "row",
        alignItems: "flex-start",
        height: 0
      }
    ) : null,
    suggestionsPosition === "below" && suggestionsNode
  ] });
};

// packages/cli/src/ui/components/StatusRow.tsx
var import_react89 = __toESM(require_react(), 1);

// packages/cli/src/ui/hooks/usePhraseCycler.ts
var import_react86 = __toESM(require_react(), 1);

// packages/cli/src/ui/constants/tips.ts
var INFORMATIVE_TIPS = [
  //Settings tips start here
  "Set your preferred editor for opening files (/settings)\u2026",
  "Toggle Vim mode for a modal editing experience (/settings)\u2026",
  "Disable automatic updates if you prefer manual control (/settings)\u2026",
  "Turn off nagging update notifications (settings.json)\u2026",
  "Enable checkpointing to recover your session after a crash (settings.json)\u2026",
  "Change CLI output format to JSON for scripting (/settings)\u2026",
  "Personalize your CLI with a new color theme (/settings)\u2026",
  "Create and use your own custom themes (settings.json)\u2026",
  "Hide window title for a more minimal UI (/settings)\u2026",
  "Don't like these tips? You can hide them (/settings)\u2026",
  "Hide the startup banner for a cleaner launch (/settings)\u2026",
  "Hide the context summary above the input (/settings)\u2026",
  "Reclaim vertical space by hiding the footer (/settings)\u2026",
  "Hide individual footer elements like CWD or sandbox status (/settings)\u2026",
  "Hide the context window percentage in the footer (/settings)\u2026",
  "Show memory usage for performance monitoring (/settings)\u2026",
  "Show line numbers in the chat for easier reference (/settings)\u2026",
  "Show citations to see where the model gets information (/settings)\u2026",
  "Customize loading phrases: tips, witty, all, or off (/settings)\u2026",
  "Add custom witty phrases to the loading screen (settings.json)\u2026",
  "Use alternate screen buffer to preserve shell history (/settings)\u2026",
  "Choose a specific Gemini model for conversations (/settings)\u2026",
  "Limit the number of turns in your session history (/settings)\u2026",
  "Automatically summarize large tool outputs to save tokens (settings.json)\u2026",
  "Control when chat history gets compressed based on context compression threshold (settings.json)\u2026",
  "Define custom context file names, like CONTEXT.md (settings.json)\u2026",
  "Set max directories to scan for context files (/settings)\u2026",
  "Expand your workspace with additional directories (/directory)\u2026",
  "Control how /memory reload loads context files (/settings)\u2026",
  "Toggle respect for .gitignore files in context (/settings)\u2026",
  "Toggle respect for .geminiignore files in context (/settings)\u2026",
  "Enable recursive file search for @-file completions (/settings)\u2026",
  "Disable fuzzy search when searching for files (/settings)\u2026",
  "Run tools in a secure sandbox environment (settings.json)\u2026",
  "Use an interactive terminal for shell commands (/settings)\u2026",
  "Show color in shell command output (/settings)\u2026",
  "Automatically accept safe read-only tool calls (/settings)\u2026",
  "Restrict available built-in tools (settings.json)\u2026",
  "Exclude specific tools from being used (settings.json)\u2026",
  "Bypass confirmation for trusted tools (settings.json)\u2026",
  "Use a custom command for tool discovery (settings.json)\u2026",
  "Define a custom command for calling discovered tools (settings.json)\u2026",
  "Define and manage connections to MCP servers (settings.json)\u2026",
  "Enable folder trust to enhance security (/settings)\u2026",
  "Disable YOLO mode to enforce confirmations (settings.json)\u2026",
  "Block Git extensions for enhanced security (settings.json)\u2026",
  "Change your authentication method (/settings)\u2026",
  "Enforce auth type for enterprise use (settings.json)\u2026",
  "Let Node.js auto-configure memory (settings.json)\u2026",
  "Retry on fetch failed errors automatically (settings.json)\u2026",
  "Customize the DNS resolution order (settings.json)\u2026",
  "Exclude env vars from the context (settings.json)\u2026",
  "Configure a custom command for filing bug reports (settings.json)\u2026",
  "Enable or disable telemetry collection (/settings)\u2026",
  "Send telemetry data to a local file or GCP (settings.json)\u2026",
  "Configure the OTLP endpoint for telemetry (settings.json)\u2026",
  "Choose whether to log prompt content (settings.json)\u2026",
  "Enable AI-powered prompt completion while typing (/settings)\u2026",
  "Enable debug logging of keystrokes to the console (/settings)\u2026",
  "Enable automatic session cleanup of old conversations (/settings)\u2026",
  "Show Gemini CLI status in the terminal window title (/settings)\u2026",
  "Use the entire width of the terminal for output (/settings)\u2026",
  "Enable screen reader mode for better accessibility (/settings)\u2026",
  "Skip the next speaker check for faster responses (/settings)\u2026",
  "Use ripgrep for faster file content search (/settings)\u2026",
  "Enable truncation of large tool outputs to save tokens (/settings)\u2026",
  "Set the character threshold for truncating tool outputs (/settings)\u2026",
  "Set the number of lines to keep when truncating outputs (/settings)\u2026",
  "Enable policy-based tool confirmation via message bus (/settings)\u2026",
  "Enable write_todos_list tool to generate task lists (/settings)\u2026",
  "Enable experimental subagents for task delegation (/settings)\u2026",
  "Enable extension management features (settings.json)\u2026",
  "Enable extension reloading within the CLI session (settings.json)\u2026",
  //Settings tips end here
  // Keyboard shortcut tips start here
  "Close dialogs and suggestions with Esc",
  "Cancel a request with Ctrl+C, or press twice to exit",
  "Exit the app with Ctrl+D on an empty line",
  "Clear your screen at any time with Ctrl+L",
  "Toggle the debug console display with F12",
  "Toggle the todo list display with Ctrl+T",
  "See full, untruncated responses with Ctrl+O",
  "Toggle auto-approval (YOLO mode) for all tools with Ctrl+Y",
  "Cycle through approval modes (Default, Auto-Edit, Plan) with Shift+Tab",
  "Toggle Markdown rendering (raw markdown mode) with Alt+M",
  "Toggle shell mode by typing ! in an empty prompt",
  "Insert a newline with a backslash (\\) followed by Enter",
  "Navigate your prompt history with the Up and Down arrows",
  "You can also use Ctrl+P (up) and Ctrl+N (down) for history",
  "Search through command history with Ctrl+R",
  "Accept an autocomplete suggestion with Tab or Enter",
  "Move to the start of the line with Ctrl+A or Home",
  "Move to the end of the line with Ctrl+E or End",
  "Move one character left or right with Ctrl+B/F or the arrow keys",
  "Move one word left or right with Ctrl+Left/Right Arrow",
  "Delete the character to the left with Ctrl+H or Backspace",
  "Delete the character to the right with Ctrl+D or Delete",
  "Delete the word to the left of the cursor with Ctrl+W",
  "Delete the word to the right of the cursor with Ctrl+Delete",
  "Delete from the cursor to the start of the line with Ctrl+U",
  "Delete from the cursor to the end of the line with Ctrl+K",
  "Clear the entire input prompt with a double-press of Esc",
  "Paste from your clipboard with Ctrl+V",
  "Undo text edits in the input with Alt+Z or Cmd+Z",
  "Redo undone text edits with Shift+Alt+Z or Shift+Cmd+Z",
  "Open the current prompt in an external editor with Ctrl+G",
  "In menus, move up/down with k/j or the arrow keys",
  "In menus, select an item by typing its number",
  "If you're using an IDE, see the context with F4",
  "Toggle background shells with Ctrl+B or /shells",
  "Toggle the background shell process list with Ctrl+L",
  // Keyboard shortcut tips end here
  // Command tips start here
  "Show version info with /about",
  "Change your authentication method with /auth",
  "File a bug report directly with /bug",
  "List your saved chat checkpoints with /resume list",
  "Save your current conversation with /resume save <tag>",
  "Resume a saved conversation with /resume resume <tag>",
  "Delete a conversation checkpoint with /resume delete <tag>",
  "Share your conversation to a file with /resume share <file>",
  "Clear the screen and history with /clear",
  "Save tokens by summarizing the context with /compress",
  "Copy the last response to your clipboard with /copy",
  "Open the full documentation in your browser with /docs",
  "Add directories to your workspace with /directory add <path>",
  "Show all directories in your workspace with /directory show",
  "Use /dir as a shortcut for /directory",
  "Set your preferred external editor with /editor",
  "List all active extensions with /extensions list",
  "Update all or specific extensions with /extensions update",
  "Get help on commands with /help",
  "Manage IDE integration with /ide",
  "Create a project-specific GEMINI.md file with /init",
  "List configured MCP servers and tools with /mcp list",
  "Authenticate with an OAuth-enabled MCP server with /mcp auth",
  "Reload MCP servers with /mcp reload",
  "See the current instructional context with /memory show",
  "Add content to the instructional memory with /memory add",
  "Reload instructional context from GEMINI.md files with /memory reload",
  "List the paths of the GEMINI.md files in use with /memory list",
  "Choose your Gemini model with /model",
  "Display the privacy notice with /privacy",
  "Restore project files to a previous state with /restore",
  "Exit the CLI with /quit or /exit",
  "Check model-specific usage stats with /stats model",
  "Check tool-specific usage stats with /stats tools",
  "Change the CLI's color theme with /theme",
  "List all available tools with /tools",
  "View and edit settings with the /settings editor",
  "Toggle Vim keybindings on and off with /vim",
  "Set up GitHub Actions with /setup-github",
  "Configure terminal keybindings for multiline input with /terminal-setup",
  "Find relevant documentation with /find-docs",
  "Execute any shell command with !<command>"
  // Command tips end here
];

// packages/cli/src/ui/constants/wittyPhrases.ts
var WITTY_LOADING_PHRASES = [
  "I'm Feeling Lucky",
  "Shipping awesomeness",
  "Painting the serifs back on",
  "Navigating the slime mold",
  "Consulting the digital spirits",
  "Reticulating splines",
  "Warming up the AI hamsters",
  "Asking the magic conch shell",
  "Generating witty retort",
  "Polishing the algorithms",
  "Don't rush perfection (or my code)",
  "Brewing fresh bytes",
  "Counting electrons",
  "Engaging cognitive processors",
  "Checking for syntax errors in the universe",
  "One moment, optimizing humor",
  "Shuffling punchlines",
  "Untangling neural nets",
  "Compiling brilliance",
  "Loading wit.exe",
  "Summoning the cloud of wisdom",
  "Preparing a witty response",
  "Just a sec, I'm debugging reality",
  "Confuzzling the options",
  "Tuning the cosmic frequencies",
  "Crafting a response worthy of your patience",
  "Compiling the 1s and 0s",
  "Resolving dependencies\u2026 and existential crises",
  "Defragmenting memories\u2026 both RAM and personal",
  "Rebooting the humor module",
  "Caching the essentials (mostly cat memes)",
  "Optimizing for ludicrous speed",
  "Swapping bits\u2026 don't tell the bytes",
  "Garbage collecting\u2026 be right back",
  "Assembling the interwebs",
  "Converting coffee into code",
  "Updating the syntax for reality",
  "Rewiring the synapses",
  "Looking for a misplaced semicolon",
  "Greasin' the cogs of the machine",
  "Pre-heating the servers",
  "Calibrating the flux capacitor",
  "Engaging the improbability drive",
  "Channeling the Force",
  "Aligning the stars for optimal response",
  "So say we all",
  "Loading the next great idea",
  "Just a moment, I'm in the zone",
  "Preparing to dazzle you with brilliance",
  "Just a tick, I'm polishing my wit",
  "Hold tight, I'm crafting a masterpiece",
  "Just a jiffy, I'm debugging the universe",
  "Just a moment, I'm aligning the pixels",
  "Just a sec, I'm optimizing the humor",
  "Just a moment, I'm tuning the algorithms",
  "Warp speed engaged",
  "Mining for more Dilithium crystals",
  "Don't panic",
  "Following the white rabbit",
  "The truth is in here\u2026 somewhere",
  "Blowing on the cartridge",
  "Loading\u2026 Do a barrel roll!",
  "Waiting for the respawn",
  "Finishing the Kessel Run in less than 12 parsecs",
  "The cake is not a lie, it's just still loading",
  "Fiddling with the character creation screen",
  "Just a moment, I'm finding the right meme",
  "Pressing 'A' to continue",
  "Herding digital cats",
  "Polishing the pixels",
  "Finding a suitable loading screen pun",
  "Distracting you with this witty phrase",
  "Almost there\u2026 probably",
  "Our hamsters are working as fast as they can",
  "Giving Cloudy a pat on the head",
  "Petting the cat",
  "Rickrolling my boss",
  "Slapping the bass",
  "Tasting the snozberries",
  "I'm going the distance, I'm going for speed",
  "Is this the real life? Is this just fantasy?",
  "I've got a good feeling about this",
  "Poking the bear",
  "Doing research on the latest memes",
  "Figuring out how to make this more witty",
  "Hmmm\u2026 let me think",
  "What do you call a fish with no eyes? A fsh",
  "Why did the computer go to therapy? It had too many bytes",
  "Why don't programmers like nature? It has too many bugs",
  "Why do programmers prefer dark mode? Because light attracts bugs",
  "Why did the developer go broke? Because they used up all their cache",
  "What can you do with a broken pencil? Nothing, it's pointless",
  "Applying percussive maintenance",
  "Searching for the correct USB orientation",
  "Ensuring the magic smoke stays inside the wires",
  "Rewriting in Rust for no particular reason",
  "Trying to exit Vim",
  "Spinning up the hamster wheel",
  "That's not a bug, it's an undocumented feature",
  "Engage.",
  "I'll be back\u2026 with an answer.",
  "My other process is a TARDIS",
  "Communing with the machine spirit",
  "Letting the thoughts marinate",
  "Just remembered where I put my keys",
  "Pondering the orb",
  "I've seen things you people wouldn't believe\u2026 like a user who reads loading messages.",
  "Initiating thoughtful gaze",
  "What's a computer's favorite snack? Microchips.",
  "Why do Java developers wear glasses? Because they don't C#.",
  "Charging the laser\u2026 pew pew!",
  "Dividing by zero\u2026 just kidding!",
  "Looking for an adult superviso\u2026 I mean, processing.",
  "Making it go beep boop.",
  "Buffering\u2026 because even AIs need a moment.",
  "Entangling quantum particles for a faster response",
  "Polishing the chrome\u2026 on the algorithms.",
  "Are you not entertained? (Working on it!)",
  "Summoning the code gremlins\u2026 to help, of course.",
  "Just waiting for the dial-up tone to finish",
  "Recalibrating the humor-o-meter.",
  "My other loading screen is even funnier.",
  "Pretty sure there's a cat walking on the keyboard somewhere",
  "Enhancing\u2026 Enhancing\u2026 Still loading.",
  "It's not a bug, it's a feature\u2026 of this loading screen.",
  "Have you tried turning it off and on again? (The loading screen, not me.)",
  "Constructing additional pylons",
  "New line? That\u2019s Ctrl+J.",
  "Releasing the HypnoDrones"
];

// packages/cli/src/ui/hooks/usePhraseCycler.ts
var PHRASE_CHANGE_INTERVAL_MS = 1e4;
var WITTY_PHRASE_CHANGE_INTERVAL_MS = 5e3;
var INTERACTIVE_SHELL_WAITING_PHRASE = "! Shell awaiting input (Tab to focus)";
var usePhraseCycler = (isActive, isWaiting, shouldShowFocusHint, showTips = true, showWit = true, customPhrases, maxLength) => {
  const [currentTipState, setCurrentTipState] = (0, import_react86.useState)(
    void 0
  );
  const [currentWittyPhraseState, setCurrentWittyPhraseState] = (0, import_react86.useState)(void 0);
  const tipIntervalRef = (0, import_react86.useRef)(null);
  const wittyIntervalRef = (0, import_react86.useRef)(null);
  const lastTipChangeTimeRef = (0, import_react86.useRef)(0);
  const lastWittyChangeTimeRef = (0, import_react86.useRef)(0);
  const lastSelectedTipRef = (0, import_react86.useRef)(void 0);
  const lastSelectedWittyPhraseRef = (0, import_react86.useRef)(void 0);
  const MIN_TIP_DISPLAY_TIME_MS = 1e4;
  const MIN_WIT_DISPLAY_TIME_MS = 5e3;
  (0, import_react86.useEffect)(() => {
    const clearTimers = () => {
      if (tipIntervalRef.current) {
        clearInterval(tipIntervalRef.current);
        tipIntervalRef.current = null;
      }
      if (wittyIntervalRef.current) {
        clearInterval(wittyIntervalRef.current);
        wittyIntervalRef.current = null;
      }
    };
    clearTimers();
    if (shouldShowFocusHint || isWaiting) {
      return clearTimers;
    }
    if (!isActive || !showTips && !showWit) {
      return clearTimers;
    }
    const wittyPhrasesList = customPhrases && customPhrases.length > 0 ? customPhrases : WITTY_LOADING_PHRASES;
    const setRandomTip = (force = false) => {
      if (!showTips) {
        setCurrentTipState(void 0);
        lastSelectedTipRef.current = void 0;
        return;
      }
      const now = Date.now();
      if (!force && now - lastTipChangeTimeRef.current < MIN_TIP_DISPLAY_TIME_MS && lastSelectedTipRef.current) {
        setCurrentTipState(lastSelectedTipRef.current);
        return;
      }
      const filteredTips = maxLength !== void 0 ? INFORMATIVE_TIPS.filter((p) => p.length <= maxLength) : INFORMATIVE_TIPS;
      if (filteredTips.length > 0) {
        const selected = filteredTips[Math.floor(Math.random() * filteredTips.length)];
        setCurrentTipState(selected);
        lastSelectedTipRef.current = selected;
        lastTipChangeTimeRef.current = now;
      }
    };
    const setRandomWitty = (force = false) => {
      if (!showWit) {
        setCurrentWittyPhraseState(void 0);
        lastSelectedWittyPhraseRef.current = void 0;
        return;
      }
      const now = Date.now();
      if (!force && now - lastWittyChangeTimeRef.current < MIN_WIT_DISPLAY_TIME_MS && lastSelectedWittyPhraseRef.current) {
        setCurrentWittyPhraseState(lastSelectedWittyPhraseRef.current);
        return;
      }
      const filteredWitty = maxLength !== void 0 ? wittyPhrasesList.filter((p) => p.length <= maxLength) : wittyPhrasesList;
      if (filteredWitty.length > 0) {
        const selected = filteredWitty[Math.floor(Math.random() * filteredWitty.length)];
        setCurrentWittyPhraseState(selected);
        lastSelectedWittyPhraseRef.current = selected;
        lastWittyChangeTimeRef.current = now;
      }
    };
    setRandomTip(false);
    setRandomWitty(false);
    if (showTips) {
      tipIntervalRef.current = setInterval(() => {
        setRandomTip(true);
      }, PHRASE_CHANGE_INTERVAL_MS);
    }
    if (showWit) {
      wittyIntervalRef.current = setInterval(() => {
        setRandomWitty(true);
      }, WITTY_PHRASE_CHANGE_INTERVAL_MS);
    }
    return clearTimers;
  }, [
    isActive,
    isWaiting,
    shouldShowFocusHint,
    showTips,
    showWit,
    customPhrases,
    maxLength
  ]);
  let currentTip = void 0;
  let currentWittyPhrase = void 0;
  if (shouldShowFocusHint) {
    currentTip = INTERACTIVE_SHELL_WAITING_PHRASE;
  } else if (isWaiting) {
    currentTip = "Waiting for user confirmation...";
  } else if (isActive) {
    currentTip = currentTipState;
    currentWittyPhrase = currentWittyPhraseState;
  }
  return { currentTip, currentWittyPhrase };
};

// packages/cli/src/ui/components/GeminiSpinner.tsx
var import_react87 = __toESM(require_react(), 1);
var import_tinygradient = __toESM(require_tinygradient(), 1);
var import_jsx_runtime115 = __toESM(require_jsx_runtime(), 1);
var COLOR_CYCLE_DURATION_MS = 4e3;
var GeminiSpinner = ({
  spinnerType = "dots",
  altText
}) => {
  const isScreenReaderEnabled = use_is_screen_reader_enabled_default();
  const [time, setTime] = (0, import_react87.useState)(0);
  const googleGradient = (0, import_react87.useMemo)(() => {
    const brandColors = [
      Colors.AccentPurple,
      Colors.AccentBlue,
      Colors.AccentCyan,
      Colors.AccentGreen,
      Colors.AccentYellow,
      Colors.AccentRed
    ];
    return (0, import_tinygradient.default)([...brandColors, brandColors[0]]);
  }, []);
  (0, import_react87.useEffect)(() => {
    if (isScreenReaderEnabled) {
      return;
    }
    const interval = setInterval(() => {
      setTime((prevTime) => prevTime + 30);
    }, 30);
    return () => clearInterval(interval);
  }, [isScreenReaderEnabled]);
  const progress = time % COLOR_CYCLE_DURATION_MS / COLOR_CYCLE_DURATION_MS;
  const currentColor = googleGradient.rgbAt(progress).toHexString();
  return isScreenReaderEnabled ? /* @__PURE__ */ (0, import_jsx_runtime115.jsx)(Text, { children: altText }) : /* @__PURE__ */ (0, import_jsx_runtime115.jsx)(Text, { color: currentColor, children: /* @__PURE__ */ (0, import_jsx_runtime115.jsx)(CliSpinner, { type: spinnerType }) });
};

// packages/cli/src/ui/components/GeminiRespondingSpinner.tsx
var import_jsx_runtime116 = __toESM(require_jsx_runtime(), 1);
var GeminiRespondingSpinner = ({
  nonRespondingDisplay,
  spinnerType = "dots",
  isHookActive = false,
  color
}) => {
  const streamingState = useStreamingContext();
  const isScreenReaderEnabled = use_is_screen_reader_enabled_default();
  if (streamingState === "responding" /* Responding */ && !isHookActive) {
    return /* @__PURE__ */ (0, import_jsx_runtime116.jsx)(
      GeminiSpinner,
      {
        spinnerType,
        altText: SCREEN_READER_RESPONDING
      }
    );
  }
  if (nonRespondingDisplay) {
    return isScreenReaderEnabled ? /* @__PURE__ */ (0, import_jsx_runtime116.jsx)(Text, { children: SCREEN_READER_LOADING }) : /* @__PURE__ */ (0, import_jsx_runtime116.jsx)(Text, { color: color ?? theme.text.primary, children: nonRespondingDisplay });
  }
  return null;
};

// packages/cli/src/ui/components/LoadingIndicator.tsx
var import_jsx_runtime117 = __toESM(require_jsx_runtime(), 1);
var LoadingIndicator = ({
  currentLoadingPhrase,
  wittyPhrase,
  showWit = false,
  elapsedTime,
  inline = false,
  rightContent,
  thought,
  thoughtLabel,
  showCancelAndTimer = true,
  forceRealStatusOnly = false,
  spinnerIcon,
  isHookActive = false
}) => {
  const streamingState = useStreamingContext();
  const { columns: terminalWidth } = useTerminalSize();
  const isNarrow = isNarrowWidth(terminalWidth);
  if (streamingState === "idle" /* Idle */ && !currentLoadingPhrase && !thought) {
    return null;
  }
  const primaryText = currentLoadingPhrase === INTERACTIVE_SHELL_WAITING_PHRASE ? currentLoadingPhrase : thought?.subject ? thoughtLabel ?? thought.subject : currentLoadingPhrase || (streamingState === "responding" /* Responding */ ? "Thinking..." : void 0);
  const cancelAndTimerContent = showCancelAndTimer && streamingState === "responding" /* Responding */ ? `(esc to cancel, ${elapsedTime < 60 ? `${elapsedTime}s` : formatDuration(elapsedTime * 1e3)})` : null;
  const wittyPhraseNode = !forceRealStatusOnly && showWit && wittyPhrase && primaryText === "Thinking..." ? /* @__PURE__ */ (0, import_jsx_runtime117.jsx)(Box_default, { marginLeft: 1, children: /* @__PURE__ */ (0, import_jsx_runtime117.jsx)(Text, { color: theme.text.secondary, dimColor: true, italic: true, children: wittyPhrase }) }) : null;
  if (inline) {
    return /* @__PURE__ */ (0, import_jsx_runtime117.jsxs)(Box_default, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime117.jsx)(Box_default, { marginRight: 1, children: /* @__PURE__ */ (0, import_jsx_runtime117.jsx)(
        GeminiRespondingSpinner,
        {
          nonRespondingDisplay: spinnerIcon ?? (streamingState === "waiting_for_confirmation" /* WaitingForConfirmation */ ? "\u280F" : ""),
          isHookActive
        }
      ) }),
      primaryText && /* @__PURE__ */ (0, import_jsx_runtime117.jsxs)(Box_default, { flexShrink: 1, children: [
        /* @__PURE__ */ (0, import_jsx_runtime117.jsx)(Text, { color: theme.text.primary, italic: true, wrap: "truncate-end", children: primaryText }),
        primaryText === INTERACTIVE_SHELL_WAITING_PHRASE && /* @__PURE__ */ (0, import_jsx_runtime117.jsxs)(Text, { color: theme.ui.active, italic: true, children: [
          " ",
          "(press tab to focus)"
        ] })
      ] }),
      cancelAndTimerContent && /* @__PURE__ */ (0, import_jsx_runtime117.jsxs)(import_jsx_runtime117.Fragment, { children: [
        /* @__PURE__ */ (0, import_jsx_runtime117.jsx)(Box_default, { flexShrink: 0, width: 1 }),
        /* @__PURE__ */ (0, import_jsx_runtime117.jsx)(Text, { color: theme.text.secondary, children: cancelAndTimerContent })
      ] }),
      wittyPhraseNode
    ] });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime117.jsxs)(Box_default, { paddingLeft: 0, flexDirection: "column", children: [
    /* @__PURE__ */ (0, import_jsx_runtime117.jsxs)(
      Box_default,
      {
        width: "100%",
        flexDirection: isNarrow ? "column" : "row",
        alignItems: isNarrow ? "flex-start" : "center",
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime117.jsxs)(Box_default, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime117.jsx)(Box_default, { marginRight: 1, children: /* @__PURE__ */ (0, import_jsx_runtime117.jsx)(
              GeminiRespondingSpinner,
              {
                nonRespondingDisplay: spinnerIcon ?? (streamingState === "waiting_for_confirmation" /* WaitingForConfirmation */ ? "\u280F" : ""),
                isHookActive
              }
            ) }),
            primaryText && /* @__PURE__ */ (0, import_jsx_runtime117.jsxs)(Box_default, { flexShrink: 1, children: [
              /* @__PURE__ */ (0, import_jsx_runtime117.jsx)(Text, { color: theme.text.primary, italic: true, wrap: "truncate-end", children: primaryText }),
              primaryText === INTERACTIVE_SHELL_WAITING_PHRASE && /* @__PURE__ */ (0, import_jsx_runtime117.jsxs)(Text, { color: theme.ui.active, italic: true, children: [
                " ",
                "(press tab to focus)"
              ] })
            ] }),
            !isNarrow && cancelAndTimerContent && /* @__PURE__ */ (0, import_jsx_runtime117.jsxs)(import_jsx_runtime117.Fragment, { children: [
              /* @__PURE__ */ (0, import_jsx_runtime117.jsx)(Box_default, { flexShrink: 0, width: 1 }),
              /* @__PURE__ */ (0, import_jsx_runtime117.jsx)(Text, { color: theme.text.secondary, children: cancelAndTimerContent })
            ] }),
            !isNarrow && wittyPhraseNode
          ] }),
          !isNarrow && /* @__PURE__ */ (0, import_jsx_runtime117.jsx)(Box_default, { flexGrow: 1 }),
          !isNarrow && rightContent && /* @__PURE__ */ (0, import_jsx_runtime117.jsx)(Box_default, { children: rightContent })
        ]
      }
    ),
    isNarrow && cancelAndTimerContent && /* @__PURE__ */ (0, import_jsx_runtime117.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime117.jsx)(Text, { color: theme.text.secondary, children: cancelAndTimerContent }) }),
    isNarrow && wittyPhraseNode,
    isNarrow && rightContent && /* @__PURE__ */ (0, import_jsx_runtime117.jsx)(Box_default, { children: rightContent })
  ] });
};

// packages/cli/src/ui/components/ContextSummaryDisplay.tsx
var import_jsx_runtime118 = __toESM(require_jsx_runtime(), 1);
var ContextSummaryDisplay = ({
  geminiMdFileCount,
  contextFileNames,
  mcpServers,
  blockedMcpServers,
  ideContext,
  skillCount,
  backgroundProcessCount = 0
}) => {
  const mcpServerCount = Object.keys(mcpServers || {}).length;
  const blockedMcpServerCount = blockedMcpServers?.length || 0;
  const openFileCount = ideContext?.workspaceState?.openFiles?.length ?? 0;
  if (geminiMdFileCount === 0 && mcpServerCount === 0 && blockedMcpServerCount === 0 && openFileCount === 0 && skillCount === 0 && backgroundProcessCount === 0) {
    return null;
  }
  const openFilesText = (() => {
    if (openFileCount === 0) {
      return "";
    }
    return `${openFileCount} open file${openFileCount > 1 ? "s" : ""} (${formatCommand("app.showIdeContextDetail" /* SHOW_IDE_CONTEXT_DETAIL */)} to view)`;
  })();
  const geminiMdText = (() => {
    if (geminiMdFileCount === 0) {
      return "";
    }
    const allNamesTheSame = new Set(contextFileNames).size < 2;
    const name = allNamesTheSame ? contextFileNames[0] : "context";
    return `${geminiMdFileCount} ${name} file${geminiMdFileCount > 1 ? "s" : ""}`;
  })();
  const mcpText = (() => {
    if (mcpServerCount === 0 && blockedMcpServerCount === 0) {
      return "";
    }
    const parts = [];
    if (mcpServerCount > 0) {
      parts.push(
        `${mcpServerCount} MCP server${mcpServerCount > 1 ? "s" : ""}`
      );
    }
    if (blockedMcpServerCount > 0) {
      let blockedText = `${blockedMcpServerCount} Blocked`;
      if (mcpServerCount === 0) {
        blockedText += ` MCP server${blockedMcpServerCount > 1 ? "s" : ""}`;
      }
      parts.push(blockedText);
    }
    return parts.join(", ");
  })();
  const skillText = (() => {
    if (skillCount === 0) {
      return "";
    }
    return `${skillCount} skill${skillCount > 1 ? "s" : ""}`;
  })();
  const backgroundText = (() => {
    if (backgroundProcessCount === 0) {
      return "";
    }
    return `${backgroundProcessCount} Background process${backgroundProcessCount > 1 ? "es" : ""}`;
  })();
  const summaryParts = [
    openFilesText,
    geminiMdText,
    mcpText,
    skillText,
    backgroundText
  ].filter(Boolean);
  return /* @__PURE__ */ (0, import_jsx_runtime118.jsx)(Box_default, { paddingX: 1, flexDirection: "row", flexWrap: "wrap", children: summaryParts.map((part, index) => /* @__PURE__ */ (0, import_jsx_runtime118.jsxs)(Box_default, { flexDirection: "row", children: [
    index > 0 && /* @__PURE__ */ (0, import_jsx_runtime118.jsx)(Text, { color: theme.text.secondary, children: " \xB7 " }),
    /* @__PURE__ */ (0, import_jsx_runtime118.jsx)(Text, { color: theme.text.secondary, children: part })
  ] }, index)) });
};

// packages/cli/src/ui/components/StatusDisplay.tsx
var import_jsx_runtime119 = __toESM(require_jsx_runtime(), 1);
var StatusDisplay = ({
  hideContextSummary
}) => {
  const uiState = useUIState();
  const settings = useSettings();
  const config = useConfig();
  if (process.env["GEMINI_SYSTEM_MD"]) {
    return /* @__PURE__ */ (0, import_jsx_runtime119.jsx)(Text, { color: theme.status.error, children: "|\u2310\u25A0_\u25A0|" });
  }
  if (!settings.merged.ui.hideContextSummary && !hideContextSummary) {
    return /* @__PURE__ */ (0, import_jsx_runtime119.jsx)(
      ContextSummaryDisplay,
      {
        ideContext: uiState.ideContextState,
        geminiMdFileCount: uiState.geminiMdFileCount,
        contextFileNames: uiState.contextFileNames,
        mcpServers: config.getMcpClientManager()?.getMcpServers() ?? {},
        blockedMcpServers: config.getMcpClientManager()?.getBlockedMcpServers() ?? [],
        skillCount: config.getSkillManager().getDisplayableSkills().length,
        backgroundProcessCount: uiState.backgroundTaskCount
      }
    );
  }
  return null;
};

// packages/cli/src/ui/components/shared/HorizontalLine.tsx
var import_jsx_runtime120 = __toESM(require_jsx_runtime(), 1);
var HorizontalLine = ({
  color = theme.border.default,
  dim = false
}) => /* @__PURE__ */ (0, import_jsx_runtime120.jsx)(
  Box_default,
  {
    width: "100%",
    borderStyle: "single",
    borderTop: true,
    borderBottom: false,
    borderLeft: false,
    borderRight: false,
    borderColor: color,
    borderDimColor: dim
  }
);

// packages/cli/src/ui/components/ApprovalModeIndicator.tsx
var import_jsx_runtime121 = __toESM(require_jsx_runtime(), 1);
var ApprovalModeIndicator = ({
  approvalMode,
  allowPlanMode
}) => {
  let textColor = "";
  let textContent = "";
  let subText = "";
  const cycleHint = formatCommand("app.cycleApprovalMode" /* CYCLE_APPROVAL_MODE */);
  const yoloHint = formatCommand("app.toggleYolo" /* TOGGLE_YOLO */);
  switch (approvalMode) {
    case ApprovalMode.AUTO_EDIT:
      textColor = theme.status.warning;
      textContent = "auto-accept edits";
      subText = allowPlanMode ? `${cycleHint} to plan` : `${cycleHint} to manual`;
      break;
    case ApprovalMode.PLAN:
      textColor = theme.status.success;
      textContent = "plan";
      subText = `${cycleHint} to manual`;
      break;
    case ApprovalMode.YOLO:
      textColor = theme.status.error;
      textContent = "YOLO";
      subText = yoloHint;
      break;
    case ApprovalMode.DEFAULT:
    default:
      textColor = theme.text.accent;
      textContent = "";
      subText = `${cycleHint} to accept edits`;
      break;
  }
  return /* @__PURE__ */ (0, import_jsx_runtime121.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime121.jsxs)(Text, { color: textColor, children: [
    textContent ? textContent : null,
    subText ? /* @__PURE__ */ (0, import_jsx_runtime121.jsxs)(Text, { color: theme.text.secondary, children: [
      textContent ? " " : "",
      subText
    ] }) : null
  ] }) });
};

// packages/cli/src/ui/components/ShellModeIndicator.tsx
var import_jsx_runtime122 = __toESM(require_jsx_runtime(), 1);
var ShellModeIndicator = () => /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime122.jsxs)(Text, { color: theme.ui.symbol, children: [
  "shell mode enabled",
  /* @__PURE__ */ (0, import_jsx_runtime122.jsx)(Text, { color: theme.text.secondary, children: " (esc to disable)" })
] }) });

// packages/cli/src/ui/components/RawMarkdownIndicator.tsx
var import_jsx_runtime123 = __toESM(require_jsx_runtime(), 1);
var RawMarkdownIndicator = () => {
  const modKey = formatCommand("app.toggleMarkdown" /* TOGGLE_MARKDOWN */);
  return /* @__PURE__ */ (0, import_jsx_runtime123.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime123.jsxs)(Text, { children: [
    "raw markdown mode",
    /* @__PURE__ */ (0, import_jsx_runtime123.jsxs)(Text, { color: theme.text.secondary, children: [
      " (",
      modKey,
      " to toggle) "
    ] })
  ] }) });
};

// packages/cli/src/ui/hooks/useComposerStatus.ts
var import_react88 = __toESM(require_react(), 1);
var useComposerStatus = () => {
  const uiState = useUIState();
  const settings = useSettings();
  const hasPendingToolConfirmation = (0, import_react88.useMemo)(
    () => (uiState.pendingHistoryItems ?? []).filter(
      (item) => item.type === "tool_group"
    ).some(
      (item) => item.tools.some(
        (tool) => tool.status === CoreToolCallStatus.AwaitingApproval
      )
    ),
    [uiState.pendingHistoryItems]
  );
  const hasPendingActionRequired = hasPendingToolConfirmation || Boolean(uiState.commandConfirmationRequest) || Boolean(uiState.authConsentRequest) || (uiState.confirmUpdateExtensionRequests?.length ?? 0) > 0 || Boolean(uiState.loopDetectionConfirmationRequest) || Boolean(uiState.quota.proQuotaRequest) || Boolean(uiState.quota.validationRequest) || Boolean(uiState.customDialog);
  const isInteractiveShellWaiting = Boolean(
    uiState.currentLoadingPhrase?.includes(INTERACTIVE_SHELL_WAITING_PHRASE)
  );
  const showLoadingIndicator = (!uiState.embeddedShellFocused || uiState.isBackgroundTaskVisible) && uiState.streamingState === "responding" /* Responding */ && !hasPendingActionRequired;
  const showApprovalModeIndicator = uiState.showApprovalModeIndicator;
  const modeContentObj = (0, import_react88.useMemo)(() => {
    const hideMinimalModeHintWhileBusy = !uiState.cleanUiDetailsVisible && (showLoadingIndicator || uiState.activeHooks.length > 0);
    if (hideMinimalModeHintWhileBusy) return null;
    switch (showApprovalModeIndicator) {
      case ApprovalMode.YOLO:
        return { text: "YOLO", color: theme.status.error };
      case ApprovalMode.PLAN:
        return { text: "plan", color: theme.status.success };
      case ApprovalMode.AUTO_EDIT:
        return { text: "auto edit", color: theme.status.warning };
      case ApprovalMode.DEFAULT:
      default:
        return null;
    }
  }, [
    uiState.cleanUiDetailsVisible,
    showLoadingIndicator,
    uiState.activeHooks.length,
    showApprovalModeIndicator
  ]);
  const showMinimalContext = isContextUsageHigh(
    uiState.sessionStats.lastPromptTokenCount,
    uiState.currentModel,
    settings.merged.model?.compressionThreshold
  );
  const loadingPhrases = settings.merged.ui.loadingPhrases;
  const showTips = loadingPhrases === "tips" || loadingPhrases === "all";
  const showWit = loadingPhrases === "witty" || loadingPhrases === "all";
  const shouldCollapseDuringApproval = settings.merged.ui.collapseDrawerDuringApproval !== false;
  return {
    hasPendingActionRequired,
    shouldCollapseDuringApproval,
    isInteractiveShellWaiting,
    showLoadingIndicator,
    showTips,
    showWit,
    modeContentObj,
    showMinimalContext
  };
};

// packages/cli/src/ui/components/StatusRow.tsx
var import_jsx_runtime124 = __toESM(require_jsx_runtime(), 1);
var LAYOUT = {
  STATUS_MIN_HEIGHT: 1,
  TIP_LEFT_MARGIN: 2,
  TIP_RIGHT_MARGIN_NARROW: 0,
  TIP_RIGHT_MARGIN_WIDE: 1,
  INDICATOR_LEFT_MARGIN: 1,
  CONTEXT_DISPLAY_TOP_MARGIN_NARROW: 1,
  CONTEXT_DISPLAY_LEFT_MARGIN_NARROW: 1,
  CONTEXT_DISPLAY_LEFT_MARGIN_WIDE: 0,
  COLLISION_GAP: 10
};
var StatusNode = ({
  showTips,
  showWit,
  thought,
  elapsedTime,
  currentWittyPhrase,
  activeHooks,
  showLoadingIndicator,
  errorVerbosity,
  onResize
}) => {
  const observerRef = (0, import_react89.useRef)(null);
  (0, import_react89.useEffect)(
    () => () => {
      observerRef.current?.disconnect();
    },
    []
  );
  const onRefChange = (0, import_react89.useCallback)(
    (node) => {
      if (observerRef.current) {
        observerRef.current.disconnect();
        observerRef.current = null;
      }
      if (node && onResize) {
        const observer = new ResizeObserver((entries) => {
          const entry = entries[0];
          if (entry) {
            onResize(Math.round(entry.contentRect.width));
          }
        });
        observer.observe(node);
        observerRef.current = observer;
      }
    },
    [onResize]
  );
  if (activeHooks.length === 0 && !showLoadingIndicator) return null;
  let currentLoadingPhrase = void 0;
  let currentThought = null;
  if (activeHooks.length > 0) {
    const userVisibleHooks = activeHooks.filter(
      (h) => isUserVisibleHook(h.source)
    );
    if (userVisibleHooks.length > 0) {
      const label = userVisibleHooks.length > 1 ? "Executing Hooks" : "Executing Hook";
      const displayNames = userVisibleHooks.map((h) => {
        let name = stripAnsi(h.name);
        if (h.index && h.total && h.total > 1) {
          name += ` (${h.index}/${h.total})`;
        }
        return name;
      });
      currentLoadingPhrase = `${label}: ${displayNames.join(", ")}`;
    } else {
      currentLoadingPhrase = GENERIC_WORKING_LABEL;
    }
  } else {
    currentThought = thought ? { ...thought, subject: stripAnsi(thought.subject) } : null;
  }
  return /* @__PURE__ */ (0, import_jsx_runtime124.jsx)(Box_default, { ref: onRefChange, children: /* @__PURE__ */ (0, import_jsx_runtime124.jsx)(
    LoadingIndicator,
    {
      inline: true,
      showTips,
      showWit,
      errorVerbosity,
      thought: currentThought,
      currentLoadingPhrase,
      elapsedTime,
      forceRealStatusOnly: false,
      wittyPhrase: currentWittyPhrase
    }
  ) });
};
var StatusRow = ({
  showUiDetails,
  isNarrow,
  terminalWidth,
  hideContextSummary,
  hideUiDetailsForSuggestions,
  hasPendingActionRequired
}) => {
  const uiState = useUIState();
  const inputState = useInputState();
  const settings = useSettings();
  const {
    isInteractiveShellWaiting,
    showLoadingIndicator,
    showTips,
    showWit,
    modeContentObj,
    showMinimalContext
  } = useComposerStatus();
  const [statusWidth, setStatusWidth] = (0, import_react89.useState)(0);
  const [tipWidth, setTipWidth] = (0, import_react89.useState)(0);
  const tipObserverRef = (0, import_react89.useRef)(null);
  (0, import_react89.useEffect)(
    () => () => {
      tipObserverRef.current?.disconnect();
    },
    []
  );
  const onTipRefChange = (0, import_react89.useCallback)((node) => {
    if (tipObserverRef.current) {
      tipObserverRef.current.disconnect();
      tipObserverRef.current = null;
    }
    if (node) {
      const observer = new ResizeObserver((entries) => {
        const entry = entries[0];
        if (entry) {
          const width = Math.round(entry.contentRect.width);
          if (width > 0) {
            setTipWidth(width);
          }
        }
      });
      observer.observe(node);
      tipObserverRef.current = observer;
    }
  }, []);
  const tipContentStr = (() => {
    if (showTips && uiState.currentTip && !(isInteractiveShellWaiting && uiState.currentTip === INTERACTIVE_SHELL_WAITING_PHRASE)) {
      return uiState.currentTip;
    }
    if (settings.merged.ui.showShortcutsHint && !hideUiDetailsForSuggestions && !hasPendingActionRequired && inputState.buffer.text.length === 0) {
      return showUiDetails ? "? for shortcuts" : "press tab twice for more";
    }
    return void 0;
  })();
  const willCollideTip = statusWidth + tipWidth + LAYOUT.COLLISION_GAP > terminalWidth;
  const showTipLine = Boolean(
    !hasPendingActionRequired && tipContentStr && !willCollideTip && !isNarrow
  );
  const showRow1Minimal = showLoadingIndicator || uiState.activeHooks.length > 0 || showTipLine;
  const showRow2Minimal = Boolean(modeContentObj) && !hideUiDetailsForSuggestions || showMinimalContext;
  const showRow1 = showUiDetails || showRow1Minimal;
  const showRow2 = showUiDetails || showRow2Minimal;
  const onStatusResize = (0, import_react89.useCallback)((width) => {
    if (width > 0) setStatusWidth(width);
  }, []);
  const statusNode = /* @__PURE__ */ (0, import_jsx_runtime124.jsx)(
    StatusNode,
    {
      showTips,
      showWit,
      thought: uiState.thought,
      elapsedTime: uiState.elapsedTime,
      currentWittyPhrase: uiState.currentWittyPhrase,
      activeHooks: uiState.activeHooks,
      showLoadingIndicator,
      errorVerbosity: settings.merged.ui.errorVerbosity,
      onResize: onStatusResize
    }
  );
  const renderTipNode = () => {
    if (!tipContentStr) return null;
    const isShortcutHint = tipContentStr === "? for shortcuts" || tipContentStr === "press tab twice for more";
    const color = isShortcutHint && uiState.shortcutsHelpVisible ? theme.text.accent : theme.text.secondary;
    return /* @__PURE__ */ (0, import_jsx_runtime124.jsx)(Box_default, { flexDirection: "row", justifyContent: "flex-end", ref: onTipRefChange, children: /* @__PURE__ */ (0, import_jsx_runtime124.jsx)(
      Text,
      {
        color,
        wrap: "truncate-end",
        italic: !isShortcutHint && tipContentStr === uiState.currentWittyPhrase,
        children: tipContentStr === uiState.currentTip ? `Tip: ${tipContentStr}` : tipContentStr
      }
    ) });
  };
  if (!showUiDetails && !showRow1Minimal && !showRow2Minimal) {
    return /* @__PURE__ */ (0, import_jsx_runtime124.jsx)(Box_default, { height: LAYOUT.STATUS_MIN_HEIGHT });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime124.jsxs)(Box_default, { flexDirection: "column", width: "100%", children: [
    showRow1 && /* @__PURE__ */ (0, import_jsx_runtime124.jsxs)(
      Box_default,
      {
        width: "100%",
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "space-between",
        minHeight: LAYOUT.STATUS_MIN_HEIGHT,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime124.jsx)(Box_default, { flexDirection: "row", flexGrow: 1, flexShrink: 1, children: !showUiDetails && showRow1Minimal ? /* @__PURE__ */ (0, import_jsx_runtime124.jsxs)(Box_default, { flexDirection: "row", columnGap: 1, children: [
            statusNode,
            !showUiDetails && showRow2Minimal && modeContentObj && /* @__PURE__ */ (0, import_jsx_runtime124.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime124.jsxs)(Text, { color: modeContentObj.color, children: [
              "\u25CF ",
              modeContentObj.text
            ] }) })
          ] }) : isInteractiveShellWaiting ? /* @__PURE__ */ (0, import_jsx_runtime124.jsx)(Box_default, { width: "100%", marginLeft: LAYOUT.INDICATOR_LEFT_MARGIN, children: /* @__PURE__ */ (0, import_jsx_runtime124.jsx)(Text, { color: theme.status.warning, children: INTERACTIVE_SHELL_WAITING_PHRASE }) }) : /* @__PURE__ */ (0, import_jsx_runtime124.jsx)(
            Box_default,
            {
              flexDirection: "row",
              alignItems: isNarrow ? "flex-start" : "center",
              flexGrow: 1,
              flexShrink: 0,
              marginLeft: LAYOUT.INDICATOR_LEFT_MARGIN,
              children: statusNode
            }
          ) }),
          /* @__PURE__ */ (0, import_jsx_runtime124.jsx)(
            Box_default,
            {
              flexShrink: 0,
              marginLeft: showTipLine ? LAYOUT.TIP_LEFT_MARGIN : 0,
              marginRight: showTipLine ? isNarrow ? LAYOUT.TIP_RIGHT_MARGIN_NARROW : LAYOUT.TIP_RIGHT_MARGIN_WIDE : 0,
              position: showTipLine ? "relative" : "absolute",
              ...showTipLine ? {} : { top: -100, left: -100 },
              children: !isNarrow && tipContentStr && renderTipNode()
            }
          )
        ]
      }
    ),
    showRow1 && showRow2 && (showUiDetails || showRow1Minimal && showRow2Minimal) && /* @__PURE__ */ (0, import_jsx_runtime124.jsx)(Box_default, { width: "100%", children: /* @__PURE__ */ (0, import_jsx_runtime124.jsx)(HorizontalLine, { dim: true }) }),
    showRow2 && /* @__PURE__ */ (0, import_jsx_runtime124.jsxs)(
      Box_default,
      {
        width: "100%",
        flexDirection: isNarrow ? "column" : "row",
        alignItems: isNarrow ? "flex-start" : "center",
        justifyContent: "space-between",
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime124.jsx)(
            Box_default,
            {
              flexDirection: "row",
              alignItems: "center",
              marginLeft: LAYOUT.INDICATOR_LEFT_MARGIN,
              children: showUiDetails ? /* @__PURE__ */ (0, import_jsx_runtime124.jsxs)(import_jsx_runtime124.Fragment, { children: [
                !hideUiDetailsForSuggestions && !inputState.shellModeActive && /* @__PURE__ */ (0, import_jsx_runtime124.jsx)(
                  ApprovalModeIndicator,
                  {
                    approvalMode: uiState.showApprovalModeIndicator,
                    allowPlanMode: uiState.allowPlanMode
                  }
                ),
                inputState.shellModeActive && /* @__PURE__ */ (0, import_jsx_runtime124.jsx)(Box_default, { marginLeft: LAYOUT.INDICATOR_LEFT_MARGIN, children: /* @__PURE__ */ (0, import_jsx_runtime124.jsx)(ShellModeIndicator, {}) }),
                !uiState.renderMarkdown && /* @__PURE__ */ (0, import_jsx_runtime124.jsx)(Box_default, { marginLeft: LAYOUT.INDICATOR_LEFT_MARGIN, children: /* @__PURE__ */ (0, import_jsx_runtime124.jsx)(RawMarkdownIndicator, {}) })
              ] }) : showRow2Minimal && modeContentObj && /* @__PURE__ */ (0, import_jsx_runtime124.jsxs)(Text, { color: modeContentObj.color, children: [
                "\u25CF ",
                modeContentObj.text
              ] })
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime124.jsxs)(
            Box_default,
            {
              marginTop: isNarrow ? LAYOUT.CONTEXT_DISPLAY_TOP_MARGIN_NARROW : 0,
              flexDirection: "row",
              alignItems: "center",
              marginLeft: isNarrow ? LAYOUT.CONTEXT_DISPLAY_LEFT_MARGIN_NARROW : LAYOUT.CONTEXT_DISPLAY_LEFT_MARGIN_WIDE,
              children: [
                (showUiDetails || showMinimalContext) && /* @__PURE__ */ (0, import_jsx_runtime124.jsx)(StatusDisplay, { hideContextSummary }),
                showMinimalContext && !showUiDetails && /* @__PURE__ */ (0, import_jsx_runtime124.jsx)(Box_default, { marginLeft: LAYOUT.INDICATOR_LEFT_MARGIN, children: /* @__PURE__ */ (0, import_jsx_runtime124.jsx)(
                  ContextUsageDisplay,
                  {
                    promptTokenCount: uiState.sessionStats.lastPromptTokenCount,
                    model: typeof uiState.currentModel === "string" ? uiState.currentModel : void 0,
                    terminalWidth
                  }
                ) })
              ]
            }
          )
        ]
      }
    )
  ] });
};

// packages/cli/src/ui/components/QueuedMessageDisplay.tsx
var import_jsx_runtime125 = __toESM(require_jsx_runtime(), 1);
var MAX_DISPLAYED_QUEUED_MESSAGES = 3;
var QueuedMessageDisplay = ({
  messageQueue: messageQueue2
}) => {
  if (messageQueue2.length === 0) {
    return null;
  }
  return /* @__PURE__ */ (0, import_jsx_runtime125.jsxs)(Box_default, { flexDirection: "column", marginTop: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime125.jsx)(Box_default, { paddingLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime125.jsx)(Text, { dimColor: true, children: "Queued (press \u2191 to edit):" }) }),
    messageQueue2.slice(0, MAX_DISPLAYED_QUEUED_MESSAGES).map((message, index) => {
      const preview = message.replace(/\s+/g, " ");
      return /* @__PURE__ */ (0, import_jsx_runtime125.jsx)(Box_default, { paddingLeft: 4, width: "100%", children: /* @__PURE__ */ (0, import_jsx_runtime125.jsx)(Text, { dimColor: true, wrap: "truncate", children: preview }) }, index);
    }),
    messageQueue2.length > MAX_DISPLAYED_QUEUED_MESSAGES && /* @__PURE__ */ (0, import_jsx_runtime125.jsx)(Box_default, { paddingLeft: 4, children: /* @__PURE__ */ (0, import_jsx_runtime125.jsxs)(Text, { dimColor: true, children: [
      "... (+",
      messageQueue2.length - MAX_DISPLAYED_QUEUED_MESSAGES,
      " more)"
    ] }) })
  ] });
};

// packages/cli/src/ui/components/ConfigInitDisplay.tsx
var import_react90 = __toESM(require_react(), 1);
var import_jsx_runtime126 = __toESM(require_jsx_runtime(), 1);
var ConfigInitDisplay = ({
  message: initialMessage = "Working..."
}) => {
  const [message, setMessage] = (0, import_react90.useState)(initialMessage);
  (0, import_react90.useEffect)(() => {
    const onChange = (clients) => {
      if (!clients || clients.size === 0) {
        setMessage(initialMessage);
        return;
      }
      let connected = 0;
      const connecting = [];
      for (const [name, client] of clients.entries()) {
        if (client.getStatus() === MCPServerStatus.CONNECTED) {
          connected++;
        } else {
          connecting.push(name);
        }
      }
      if (connecting.length > 0) {
        const maxDisplay = 3;
        const displayedServers = connecting.slice(0, maxDisplay).join(", ");
        const remaining = connecting.length - maxDisplay;
        const suffix = remaining > 0 ? `, +${remaining} more` : "";
        const mcpMessage = `Connecting to MCP servers... (${connected}/${clients.size}) - Waiting for: ${displayedServers}${suffix}`;
        setMessage(
          initialMessage && initialMessage !== "Working..." ? `${initialMessage} (${mcpMessage})` : mcpMessage
        );
      } else {
        const mcpMessage = `Connecting to MCP servers... (${connected}/${clients.size})`;
        setMessage(
          initialMessage && initialMessage !== "Working..." ? `${initialMessage} (${mcpMessage})` : mcpMessage
        );
      }
    };
    coreEvents.on(CoreEvent.McpClientUpdate, onChange);
    return () => {
      coreEvents.off(CoreEvent.McpClientUpdate, onChange);
    };
  }, [initialMessage]);
  return /* @__PURE__ */ (0, import_jsx_runtime126.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime126.jsxs)(Text, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime126.jsx)(GeminiSpinner, {}),
    " ",
    /* @__PURE__ */ (0, import_jsx_runtime126.jsx)(Text, { color: theme.text.primary, children: message })
  ] }) });
};

// packages/cli/src/ui/components/messages/Todo.tsx
var import_react92 = __toESM(require_react(), 1);

// packages/cli/src/ui/components/Checklist.tsx
var import_react91 = __toESM(require_react(), 1);

// packages/cli/src/ui/components/ChecklistItem.tsx
var import_jsx_runtime127 = __toESM(require_jsx_runtime(), 1);
var ChecklistStatusDisplay = ({
  status
}) => {
  switch (status) {
    case "completed":
      return /* @__PURE__ */ (0, import_jsx_runtime127.jsx)(Text, { color: theme.status.success, "aria-label": "Completed", children: "\u2713" });
    case "in_progress":
      return /* @__PURE__ */ (0, import_jsx_runtime127.jsx)(Text, { color: theme.text.accent, "aria-label": "In Progress", children: "\xBB" });
    case "pending":
      return /* @__PURE__ */ (0, import_jsx_runtime127.jsx)(Text, { color: theme.text.secondary, "aria-label": "Pending", children: "\u2610" });
    case "cancelled":
      return /* @__PURE__ */ (0, import_jsx_runtime127.jsx)(Text, { color: theme.status.error, "aria-label": "Cancelled", children: "\u2717" });
    case "blocked":
      return /* @__PURE__ */ (0, import_jsx_runtime127.jsx)(Text, { color: theme.status.warning, "aria-label": "Blocked", children: "\u26D4" });
    default:
      checkExhaustive(status);
  }
};
var ChecklistItem = ({
  item,
  wrap,
  role: ariaRole
}) => {
  const textColor = (() => {
    switch (item.status) {
      case "in_progress":
        return theme.text.accent;
      case "completed":
      case "cancelled":
      case "blocked":
        return theme.text.secondary;
      case "pending":
        return theme.text.primary;
      default:
        checkExhaustive(item.status);
    }
  })();
  const strikethrough = item.status === "cancelled";
  return /* @__PURE__ */ (0, import_jsx_runtime127.jsxs)(Box_default, { flexDirection: "row", columnGap: 1, "aria-role": ariaRole, children: [
    /* @__PURE__ */ (0, import_jsx_runtime127.jsx)(ChecklistStatusDisplay, { status: item.status }),
    /* @__PURE__ */ (0, import_jsx_runtime127.jsx)(Box_default, { flexShrink: 1, children: /* @__PURE__ */ (0, import_jsx_runtime127.jsx)(Text, { color: textColor, wrap, strikethrough, children: item.label }) })
  ] });
};

// packages/cli/src/ui/components/Checklist.tsx
var import_jsx_runtime128 = __toESM(require_jsx_runtime(), 1);
var ChecklistTitleDisplay = ({ title, items, toggleHint }) => {
  const score = (0, import_react91.useMemo)(() => {
    let total = 0;
    let completed = 0;
    for (const item of items) {
      if (item.status !== "cancelled") {
        total += 1;
        if (item.status === "completed") {
          completed += 1;
        }
      }
    }
    return `${completed}/${total} completed`;
  }, [items]);
  return /* @__PURE__ */ (0, import_jsx_runtime128.jsxs)(Box_default, { flexDirection: "row", columnGap: 2, height: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime128.jsx)(Text, { color: theme.text.primary, bold: true, "aria-label": `${title} list`, children: title }),
    /* @__PURE__ */ (0, import_jsx_runtime128.jsxs)(Text, { color: theme.text.secondary, children: [
      score,
      toggleHint ? ` (${toggleHint})` : ""
    ] })
  ] });
};
var ChecklistListDisplay = ({
  items
}) => /* @__PURE__ */ (0, import_jsx_runtime128.jsx)(Box_default, { flexDirection: "column", "aria-role": "list", children: items.map((item, index) => /* @__PURE__ */ (0, import_jsx_runtime128.jsx)(
  ChecklistItem,
  {
    item,
    role: "listitem"
  },
  `${index}-${item.label}`
)) });
var Checklist = ({
  title,
  items,
  isExpanded,
  toggleHint
}) => {
  const inProgress = (0, import_react91.useMemo)(
    () => items.find((item) => item.status === "in_progress") || null,
    [items]
  );
  const hasActiveItems = (0, import_react91.useMemo)(
    () => items.some(
      (item) => item.status === "pending" || item.status === "in_progress"
    ),
    [items]
  );
  if (items.length === 0 || !isExpanded && !hasActiveItems) {
    return null;
  }
  return /* @__PURE__ */ (0, import_jsx_runtime128.jsx)(
    Box_default,
    {
      borderStyle: "single",
      borderBottom: false,
      borderRight: false,
      borderLeft: false,
      borderColor: theme.border.default,
      paddingLeft: 1,
      paddingRight: 1,
      children: isExpanded ? /* @__PURE__ */ (0, import_jsx_runtime128.jsxs)(Box_default, { flexDirection: "column", rowGap: 1, children: [
        /* @__PURE__ */ (0, import_jsx_runtime128.jsx)(
          ChecklistTitleDisplay,
          {
            title,
            items,
            toggleHint
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime128.jsx)(ChecklistListDisplay, { items })
      ] }) : /* @__PURE__ */ (0, import_jsx_runtime128.jsxs)(Box_default, { flexDirection: "row", columnGap: 1, height: 1, children: [
        /* @__PURE__ */ (0, import_jsx_runtime128.jsx)(Box_default, { flexShrink: 0, flexGrow: 0, children: /* @__PURE__ */ (0, import_jsx_runtime128.jsx)(
          ChecklistTitleDisplay,
          {
            title,
            items,
            toggleHint
          }
        ) }),
        inProgress && /* @__PURE__ */ (0, import_jsx_runtime128.jsx)(Box_default, { flexShrink: 1, flexGrow: 1, children: /* @__PURE__ */ (0, import_jsx_runtime128.jsx)(ChecklistItem, { item: inProgress, wrap: "truncate" }) })
      ] })
    }
  );
};

// packages/cli/src/ui/components/messages/Todo.tsx
var import_jsx_runtime129 = __toESM(require_jsx_runtime(), 1);
var TodoTray = () => {
  const uiState = useUIState();
  const todos = (0, import_react92.useMemo)(() => {
    for (let i = uiState.history.length - 1; i >= 0; i--) {
      const entry = uiState.history[i];
      if (entry.type !== "tool_group") {
        continue;
      }
      const toolGroup = entry;
      for (const tool of toolGroup.tools) {
        if (typeof tool.resultDisplay !== "object" || !("todos" in tool.resultDisplay)) {
          continue;
        }
        return tool.resultDisplay;
      }
    }
    return null;
  }, [uiState.history]);
  const checklistItems = (0, import_react92.useMemo)(() => {
    if (!todos || !todos.todos) {
      return [];
    }
    return todos.todos.map((todo) => ({
      status: todo.status,
      label: todo.description
    }));
  }, [todos]);
  if (!todos || !todos.todos) {
    return null;
  }
  return /* @__PURE__ */ (0, import_jsx_runtime129.jsx)(
    Checklist,
    {
      title: "Todo",
      items: checklistItems,
      isExpanded: uiState.showFullTodos,
      toggleHint: `${formatCommand("app.showFullTodos" /* SHOW_FULL_TODOS */)} to toggle`
    }
  );
};

// packages/cli/src/ui/components/Composer.tsx
var import_jsx_runtime130 = __toESM(require_jsx_runtime(), 1);
var Composer = ({ isFocused = true }) => {
  const uiState = useUIState();
  const inputState = useInputState();
  const uiActions = useUIActions();
  const settings = useSettings();
  const config = useConfig();
  const { vimEnabled, vimMode } = useVimMode();
  const isScreenReaderEnabled = use_is_screen_reader_enabled_default();
  const { columns: terminalWidth } = useTerminalSize();
  const isNarrow = isNarrowWidth(terminalWidth);
  const debugConsoleMaxHeight = Math.floor(Math.max(terminalWidth * 0.2, 5));
  const [suggestionsVisible, setSuggestionsVisible] = (0, import_react93.useState)(false);
  const isAlternateBuffer = useAlternateBuffer();
  const showUiDetails = uiState.cleanUiDetailsVisible;
  const suggestionsPosition = isAlternateBuffer ? "above" : "below";
  const hideContextSummary = suggestionsVisible && suggestionsPosition === "above";
  const { hasPendingActionRequired, shouldCollapseDuringApproval } = useComposerStatus();
  const isPassiveShortcutsHelpState = uiState.isInputActive && uiState.streamingState === "idle" && !hasPendingActionRequired;
  const { setShortcutsHelpVisible } = uiActions;
  (0, import_react93.useEffect)(() => {
    if (hasPendingActionRequired) {
      appEvents.emit("scroll-to-bottom" /* ScrollToBottom */);
    }
  }, [hasPendingActionRequired]);
  (0, import_react93.useEffect)(() => {
    if (uiState.shortcutsHelpVisible && !isPassiveShortcutsHelpState) {
      setShortcutsHelpVisible(false);
    }
  }, [
    uiState.shortcutsHelpVisible,
    isPassiveShortcutsHelpState,
    setShortcutsHelpVisible
  ]);
  const showShortcutsHelp = uiState.shortcutsHelpVisible && uiState.streamingState === "idle" && !hasPendingActionRequired;
  if (hasPendingActionRequired && shouldCollapseDuringApproval) {
    return null;
  }
  const showToast = shouldShowToast(uiState, inputState);
  const hideUiDetailsForSuggestions = suggestionsVisible && suggestionsPosition === "above";
  const showMinimalToast = showToast;
  return /* @__PURE__ */ (0, import_jsx_runtime130.jsxs)(
    Box_default,
    {
      flexDirection: "column",
      width: uiState.terminalWidth,
      flexGrow: 0,
      flexShrink: 0,
      children: [
        uiState.isResuming && /* @__PURE__ */ (0, import_jsx_runtime130.jsx)(ConfigInitDisplay, { message: "Resuming session..." }),
        showUiDetails && /* @__PURE__ */ (0, import_jsx_runtime130.jsx)(QueuedMessageDisplay, { messageQueue: uiState.messageQueue }),
        showUiDetails && /* @__PURE__ */ (0, import_jsx_runtime130.jsx)(TodoTray, {}),
        showShortcutsHelp && /* @__PURE__ */ (0, import_jsx_runtime130.jsx)(ShortcutsHelp, {}),
        (showUiDetails || showMinimalToast) && /* @__PURE__ */ (0, import_jsx_runtime130.jsx)(Box_default, { minHeight: 1, marginLeft: isNarrow ? 0 : 1, children: /* @__PURE__ */ (0, import_jsx_runtime130.jsx)(ToastDisplay, {}) }),
        /* @__PURE__ */ (0, import_jsx_runtime130.jsx)(Box_default, { width: "100%", flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime130.jsx)(
          StatusRow,
          {
            showUiDetails,
            isNarrow,
            terminalWidth,
            hideContextSummary,
            hideUiDetailsForSuggestions,
            hasPendingActionRequired
          }
        ) }),
        showUiDetails && uiState.showErrorDetails && /* @__PURE__ */ (0, import_jsx_runtime130.jsx)(OverflowProvider, { children: /* @__PURE__ */ (0, import_jsx_runtime130.jsxs)(Box_default, { flexDirection: "column", children: [
          /* @__PURE__ */ (0, import_jsx_runtime130.jsx)(
            DetailedMessagesDisplay,
            {
              maxHeight: uiState.constrainHeight ? debugConsoleMaxHeight : void 0,
              width: uiState.terminalWidth,
              hasFocus: uiState.showErrorDetails
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime130.jsx)(ShowMoreLines, { constrainHeight: uiState.constrainHeight })
        ] }) }),
        uiState.isInputActive && /* @__PURE__ */ (0, import_jsx_runtime130.jsx)(
          InputPrompt,
          {
            onSubmit: uiActions.handleFinalSubmit,
            setBannerVisible: uiActions.setBannerVisible,
            onClearScreen: uiActions.handleClearScreen,
            config,
            slashCommands: uiState.slashCommands || [],
            commandContext: uiState.commandContext,
            setShellModeActive: uiActions.setShellModeActive,
            approvalMode: uiState.showApprovalModeIndicator,
            onEscapePromptChange: uiActions.onEscapePromptChange,
            focus: isFocused,
            vimHandleInput: uiActions.vimHandleInput,
            isEmbeddedShellFocused: uiState.embeddedShellFocused,
            popAllMessages: uiActions.popAllMessages,
            onQueueMessage: uiActions.addMessage,
            placeholder: vimEnabled ? vimMode === "INSERT" ? "  Press 'Esc' for NORMAL mode." : "  Press 'i' for INSERT mode." : inputState.shellModeActive ? "  Type your shell command" : "  Type your message or @path/to/file",
            setQueueErrorMessage: uiActions.setQueueErrorMessage,
            streamingState: uiState.streamingState,
            suggestionsPosition,
            onSuggestionsVisibilityChange: setSuggestionsVisible
          }
        ),
        showUiDetails && !settings.merged.ui.hideFooter && !isScreenReaderEnabled && /* @__PURE__ */ (0, import_jsx_runtime130.jsx)(Footer, {})
      ]
    }
  );
};

// packages/cli/src/ui/components/ExitWarning.tsx
var import_jsx_runtime131 = __toESM(require_jsx_runtime(), 1);
var ExitWarning = () => {
  const uiState = useUIState();
  return /* @__PURE__ */ (0, import_jsx_runtime131.jsxs)(import_jsx_runtime131.Fragment, { children: [
    uiState.dialogsVisible && uiState.ctrlCPressedOnce && /* @__PURE__ */ (0, import_jsx_runtime131.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime131.jsx)(Text, { color: theme.status.warning, children: "Press Ctrl+C again to exit." }) }),
    uiState.dialogsVisible && uiState.ctrlDPressedOnce && /* @__PURE__ */ (0, import_jsx_runtime131.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime131.jsx)(Text, { color: theme.status.warning, children: "Press Ctrl+D again to exit." }) })
  ] });
};

// packages/cli/src/ui/hooks/useFlickerDetector.ts
var import_react94 = __toESM(require_react(), 1);
function useFlickerDetector(rootUiRef, terminalHeight) {
  const config = useConfig();
  const { constrainHeight } = useUIState();
  (0, import_react94.useEffect)(() => {
    if (rootUiRef.current) {
      const measurement = measure_element_default(rootUiRef.current);
      if (measurement.height > terminalHeight) {
        if (!constrainHeight) {
          return;
        }
        recordFlickerFrame(config);
        appEvents.emit("flicker" /* Flicker */);
      }
    }
  });
}

// packages/cli/src/ui/layouts/ScreenReaderAppLayout.tsx
var import_jsx_runtime132 = __toESM(require_jsx_runtime(), 1);
var ScreenReaderAppLayout = () => {
  const uiState = useUIState();
  const { rootUiRef, terminalHeight } = uiState;
  useFlickerDetector(rootUiRef, terminalHeight);
  return /* @__PURE__ */ (0, import_jsx_runtime132.jsxs)(
    Box_default,
    {
      flexDirection: "column",
      width: "90%",
      height: "100%",
      ref: uiState.rootUiRef,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime132.jsx)(Notifications, {}),
        /* @__PURE__ */ (0, import_jsx_runtime132.jsx)(Footer, {}),
        /* @__PURE__ */ (0, import_jsx_runtime132.jsx)(Box_default, { flexGrow: 1, overflow: "hidden", children: /* @__PURE__ */ (0, import_jsx_runtime132.jsx)(MainContent, {}) }),
        uiState.dialogsVisible ? /* @__PURE__ */ (0, import_jsx_runtime132.jsx)(
          DialogManager,
          {
            terminalWidth: uiState.terminalWidth,
            addItem: uiState.historyManager.addItem
          }
        ) : /* @__PURE__ */ (0, import_jsx_runtime132.jsx)(Composer, {}),
        /* @__PURE__ */ (0, import_jsx_runtime132.jsx)(ExitWarning, {})
      ]
    }
  );
};

// packages/cli/src/ui/components/CopyModeWarning.tsx
var import_jsx_runtime133 = __toESM(require_jsx_runtime(), 1);
var CopyModeWarning = () => {
  const { copyModeEnabled } = useInputState();
  return /* @__PURE__ */ (0, import_jsx_runtime133.jsx)(Box_default, { height: 1, children: copyModeEnabled && /* @__PURE__ */ (0, import_jsx_runtime133.jsx)(Text, { color: theme.status.warning, children: "In Copy Mode. Use Page Up/Down to scroll. Press Ctrl+S or any other key to exit." }) });
};

// packages/cli/src/ui/components/BackgroundTaskDisplay.tsx
var import_react96 = __toESM(require_react(), 1);

// packages/cli/src/ui/hooks/useExecutionLifecycle.ts
var import_react95 = __toESM(require_react(), 1);
import crypto2 from "node:crypto";
import path12 from "node:path";
import os2 from "node:os";
import fs5 from "node:fs";

// packages/cli/src/ui/hooks/shellReducer.ts
var initialState4 = {
  activeShellPtyId: null,
  lastShellOutputTime: 0,
  backgroundTasks: /* @__PURE__ */ new Map(),
  isBackgroundTaskVisible: false
};
function shellReducer(state, action) {
  switch (action.type) {
    case "SET_ACTIVE_PTY":
      return { ...state, activeShellPtyId: action.pid };
    case "SET_OUTPUT_TIME":
      return { ...state, lastShellOutputTime: action.time };
    case "SET_VISIBILITY":
      return { ...state, isBackgroundTaskVisible: action.visible };
    case "TOGGLE_VISIBILITY":
      return {
        ...state,
        isBackgroundTaskVisible: !state.isBackgroundTaskVisible
      };
    case "REGISTER_TASK": {
      if (state.backgroundTasks.has(action.pid)) return state;
      const nextTasks = new Map(state.backgroundTasks);
      nextTasks.set(action.pid, {
        pid: action.pid,
        command: action.command,
        output: action.initialOutput,
        isBinary: false,
        binaryBytesReceived: 0,
        status: "running",
        completionBehavior: action.completionBehavior
      });
      return { ...state, backgroundTasks: nextTasks };
    }
    case "UPDATE_TASK": {
      const task = state.backgroundTasks.get(action.pid);
      if (!task) return state;
      const nextTasks = new Map(state.backgroundTasks);
      const updatedTask = { ...task, ...action.update };
      if (action.update.status === "exited") {
        nextTasks.delete(action.pid);
      }
      nextTasks.set(action.pid, updatedTask);
      return { ...state, backgroundTasks: nextTasks };
    }
    case "APPEND_TASK_OUTPUT": {
      const task = state.backgroundTasks.get(action.pid);
      if (!task) return state;
      let newOutput = task.output;
      if (typeof action.chunk === "string") {
        const currentOutput = typeof task.output === "string" ? task.output : "";
        const combinedLength = currentOutput.length + action.chunk.length;
        if (combinedLength > MAX_SHELL_OUTPUT_SIZE + SHELL_OUTPUT_TRUNCATION_BUFFER) {
          if (action.chunk.length >= MAX_SHELL_OUTPUT_SIZE) {
            newOutput = action.chunk.slice(-MAX_SHELL_OUTPUT_SIZE);
          } else {
            const keepFromCurrent = MAX_SHELL_OUTPUT_SIZE - action.chunk.length;
            newOutput = currentOutput.slice(-keepFromCurrent) + action.chunk;
          }
          if (newOutput.length > 0) {
            const firstCharCode = newOutput.charCodeAt(0);
            if (firstCharCode >= 56320 && firstCharCode <= 57343) {
              newOutput = newOutput.slice(1);
            }
          }
        } else {
          newOutput = currentOutput + action.chunk;
        }
      } else if (action.chunk) {
        newOutput = action.chunk;
      }
      task.output = newOutput;
      const nextState = { ...state, lastShellOutputTime: Date.now() };
      if (state.isBackgroundTaskVisible) {
        return {
          ...nextState,
          backgroundTasks: new Map(state.backgroundTasks)
        };
      }
      return nextState;
    }
    case "SYNC_BACKGROUND_TASKS": {
      return { ...state, backgroundTasks: new Map(state.backgroundTasks) };
    }
    case "DISMISS_TASK": {
      const nextTasks = new Map(state.backgroundTasks);
      nextTasks.delete(action.pid);
      return {
        ...state,
        backgroundTasks: nextTasks,
        isBackgroundTaskVisible: nextTasks.size === 0 ? false : state.isBackgroundTaskVisible
      };
    }
    default:
      return state;
  }
}

// packages/cli/src/ui/hooks/useExecutionLifecycle.ts
var RESTORE_VISIBILITY_DELAY_MS = 300;
var MAX_OUTPUT_LENGTH = 1e4;
function addShellCommandToGeminiHistory(geminiClient, rawQuery, resultText) {
  const modelContent = resultText.length > MAX_OUTPUT_LENGTH ? resultText.substring(0, MAX_OUTPUT_LENGTH) + "\n... (truncated)" : resultText;
  const safeQuery = rawQuery.replace(/\\/g, "\\\\").replace(/\x60/g, "\\`");
  const safeModelContent = modelContent.replace(/\\/g, "\\\\").replace(/\x60/g, "\\`");
  geminiClient.addHistory({
    role: "user",
    parts: [
      {
        text: `I ran the following shell command:
\`\`\`sh
${safeQuery}
\`\`\`

This produced the following result:
\`\`\`
${safeModelContent}
\`\`\``
      }
    ]
  });
}
var useExecutionLifecycle = (addItemToHistory, setPendingHistoryItem, onExec, onDebugMessage, config, geminiClient, setShellInputFocused, terminalWidth, terminalHeight, activeBackgroundExecutionId, isWaitingForConfirmation) => {
  const [state, dispatch] = (0, import_react95.useReducer)(shellReducer, initialState4);
  const manager = (0, import_react95.useRef)(null);
  if (!manager.current) {
    manager.current = {
      wasVisibleBeforeForeground: false,
      restoreTimeout: null,
      backgroundedPids: /* @__PURE__ */ new Set(),
      subscriptions: /* @__PURE__ */ new Map()
    };
  }
  const m = manager.current;
  const activePtyId = state.activeShellPtyId ?? activeBackgroundExecutionId ?? void 0;
  (0, import_react95.useEffect)(() => {
    const isForegroundActive = !!activePtyId || !!isWaitingForConfirmation;
    if (isForegroundActive) {
      if (m.restoreTimeout) {
        clearTimeout(m.restoreTimeout);
        m.restoreTimeout = null;
      }
      if (state.isBackgroundTaskVisible && !m.wasVisibleBeforeForeground) {
        m.wasVisibleBeforeForeground = true;
        dispatch({ type: "SET_VISIBILITY", visible: false });
      }
    } else if (m.wasVisibleBeforeForeground && !m.restoreTimeout) {
      m.restoreTimeout = setTimeout(() => {
        dispatch({ type: "SET_VISIBILITY", visible: true });
        m.wasVisibleBeforeForeground = false;
        m.restoreTimeout = null;
      }, RESTORE_VISIBILITY_DELAY_MS);
    }
    return () => {
      if (m.restoreTimeout) {
        clearTimeout(m.restoreTimeout);
      }
    };
  }, [
    activePtyId,
    isWaitingForConfirmation,
    state.isBackgroundTaskVisible,
    m,
    dispatch
  ]);
  (0, import_react95.useEffect)(
    () => () => {
      for (const unsubscribe of m.subscriptions.values()) {
        unsubscribe();
      }
      m.subscriptions.clear();
    },
    [m]
  );
  const toggleBackgroundTasks = (0, import_react95.useCallback)(() => {
    if (state.backgroundTasks.size > 0) {
      const willBeVisible = !state.isBackgroundTaskVisible;
      dispatch({ type: "TOGGLE_VISIBILITY" });
      const isForegroundActive = !!activePtyId || !!isWaitingForConfirmation;
      if (willBeVisible && isForegroundActive) {
        m.wasVisibleBeforeForeground = true;
      } else {
        m.wasVisibleBeforeForeground = false;
      }
      if (willBeVisible) {
        dispatch({ type: "SYNC_BACKGROUND_TASKS" });
      }
    } else {
      dispatch({ type: "SET_VISIBILITY", visible: false });
      addItemToHistory(
        {
          type: "info",
          text: "No background tasks are currently active."
        },
        Date.now()
      );
    }
  }, [
    addItemToHistory,
    state.backgroundTasks.size,
    state.isBackgroundTaskVisible,
    activePtyId,
    isWaitingForConfirmation,
    m,
    dispatch
  ]);
  const backgroundCurrentExecution = (0, import_react95.useCallback)(() => {
    const pidToBackground = state.activeShellPtyId ?? activeBackgroundExecutionId;
    if (pidToBackground) {
      m.backgroundedPids.add(pidToBackground);
      if (state.activeShellPtyId) {
        ShellExecutionService.background(pidToBackground);
      } else {
        ExecutionLifecycleService.background(pidToBackground);
      }
      m.wasVisibleBeforeForeground = false;
      if (m.restoreTimeout) {
        clearTimeout(m.restoreTimeout);
        m.restoreTimeout = null;
      }
    }
  }, [state.activeShellPtyId, activeBackgroundExecutionId, m]);
  const dismissBackgroundTask = (0, import_react95.useCallback)(
    async (pid) => {
      const shell2 = state.backgroundTasks.get(pid);
      if (shell2) {
        if (shell2.status === "running") {
          ExecutionLifecycleService.kill(pid);
        }
        dispatch({ type: "DISMISS_TASK", pid });
        m.backgroundedPids.delete(pid);
        const unsubscribe = m.subscriptions.get(pid);
        if (unsubscribe) {
          unsubscribe();
          m.subscriptions.delete(pid);
        }
      }
    },
    [state.backgroundTasks, dispatch, m]
  );
  const registerBackgroundTask = (0, import_react95.useCallback)(
    (pid, command, initialOutput, completionBehavior) => {
      m.backgroundedPids.add(pid);
      dispatch({
        type: "REGISTER_TASK",
        pid,
        command,
        initialOutput,
        completionBehavior
      });
      const exitUnsubscribe = ExecutionLifecycleService.onExit(pid, (code) => {
        dispatch({
          type: "UPDATE_TASK",
          pid,
          update: { status: "exited", exitCode: code }
        });
        if (completionBehavior !== "silent") {
          dispatch({ type: "DISMISS_TASK", pid });
        }
        const unsub = m.subscriptions.get(pid);
        if (unsub) {
          unsub();
          m.subscriptions.delete(pid);
        }
        m.backgroundedPids.delete(pid);
      });
      const dataUnsubscribe = ExecutionLifecycleService.subscribe(
        pid,
        (event) => {
          if (event.type === "data") {
            dispatch({
              type: "APPEND_TASK_OUTPUT",
              pid,
              chunk: event.chunk
            });
          } else if (event.type === "binary_detected") {
            dispatch({
              type: "UPDATE_TASK",
              pid,
              update: { isBinary: true }
            });
          } else if (event.type === "binary_progress") {
            dispatch({
              type: "UPDATE_TASK",
              pid,
              update: {
                isBinary: true,
                binaryBytesReceived: event.bytesReceived
              }
            });
          }
        }
      );
      m.subscriptions.set(pid, () => {
        exitUnsubscribe();
        dataUnsubscribe();
      });
    },
    [dispatch, m]
  );
  (0, import_react95.useEffect)(() => {
    const listener = (info) => {
      if (m.backgroundedPids.has(info.executionId)) {
        return;
      }
      registerBackgroundTask(
        info.executionId,
        info.label,
        info.output,
        info.completionBehavior
      );
    };
    ExecutionLifecycleService.onBackground(listener);
    return () => {
      ExecutionLifecycleService.offBackground(listener);
    };
  }, [registerBackgroundTask, m]);
  const handleShellCommand = (0, import_react95.useCallback)(
    (rawQuery, abortSignal) => {
      if (typeof rawQuery !== "string" || rawQuery.trim() === "") {
        return false;
      }
      const userMessageTimestamp = Date.now();
      const callId = `shell-${userMessageTimestamp}`;
      addItemToHistory(
        { type: "user_shell", text: rawQuery },
        userMessageTimestamp
      );
      const isWindows2 = os2.platform() === "win32";
      const targetDir = config.getTargetDir();
      let commandToExecute = rawQuery;
      let pwdFilePath;
      if (!isWindows2) {
        let command = rawQuery.trim();
        const pwdFileName = `shell_pwd_${crypto2.randomBytes(6).toString("hex")}.tmp`;
        pwdFilePath = path12.join(os2.tmpdir(), pwdFileName);
        if (!command.endsWith(";") && !command.endsWith("&")) {
          command += ";";
        }
        commandToExecute = `{ ${command} }; __code=$?; pwd > "${pwdFilePath}"; exit $__code`;
      }
      const executeCommand = async () => {
        let cumulativeStdout = "";
        let isBinaryStream = false;
        let binaryBytesReceived = 0;
        const initialToolDisplay = {
          callId,
          name: SHELL_COMMAND_NAME,
          description: rawQuery,
          status: CoreToolCallStatus.Executing,
          isClientInitiated: true,
          resultDisplay: "",
          confirmationDetails: void 0
        };
        setPendingHistoryItem({
          type: "tool_group",
          tools: [initialToolDisplay]
        });
        let executionPid;
        const abortHandler = () => {
          onDebugMessage(
            `Aborting shell command (PID: ${executionPid ?? "unknown"})`
          );
        };
        abortSignal.addEventListener("abort", abortHandler, { once: true });
        onDebugMessage(`Executing in ${targetDir}: ${commandToExecute}`);
        try {
          const activeTheme = themeManager.getActiveTheme();
          const shellExecutionConfig = {
            ...config.getShellExecutionConfig(),
            terminalWidth,
            terminalHeight,
            defaultFg: activeTheme.colors.Foreground,
            defaultBg: activeTheme.colors.Background
          };
          const { pid, result: resultPromise } = await ShellExecutionService.execute(
            commandToExecute,
            targetDir,
            (event) => {
              let shouldUpdate = false;
              switch (event.type) {
                case "data":
                  if (isBinaryStream) break;
                  if (typeof event.chunk === "string") {
                    if (typeof cumulativeStdout === "string") {
                      cumulativeStdout += event.chunk;
                    } else {
                      cumulativeStdout = event.chunk;
                    }
                  } else {
                    cumulativeStdout = event.chunk;
                  }
                  shouldUpdate = true;
                  break;
                case "binary_detected":
                  isBinaryStream = true;
                  shouldUpdate = true;
                  break;
                case "binary_progress":
                  isBinaryStream = true;
                  binaryBytesReceived = event.bytesReceived;
                  shouldUpdate = true;
                  break;
                case "exit":
                  break;
                default:
                  throw new Error("An unhandled ShellOutputEvent was found.");
              }
              if (executionPid && m.backgroundedPids.has(executionPid)) {
                dispatch({
                  type: "APPEND_TASK_OUTPUT",
                  pid: executionPid,
                  chunk: event.type === "data" ? event.chunk : cumulativeStdout
                });
                return;
              }
              let currentDisplayOutput;
              if (isBinaryStream) {
                currentDisplayOutput = binaryBytesReceived > 0 ? `[Receiving binary output... ${formatBytes(binaryBytesReceived)} received]` : "[Binary output detected. Halting stream...]";
              } else {
                currentDisplayOutput = cumulativeStdout;
              }
              if (shouldUpdate) {
                dispatch({ type: "SET_OUTPUT_TIME", time: Date.now() });
                setPendingHistoryItem((prevItem) => {
                  if (prevItem?.type === "tool_group") {
                    return {
                      ...prevItem,
                      tools: prevItem.tools.map(
                        (tool) => tool.callId === callId ? { ...tool, resultDisplay: currentDisplayOutput } : tool
                      )
                    };
                  }
                  return prevItem;
                });
              }
            },
            abortSignal,
            config.getEnableInteractiveShell(),
            shellExecutionConfig
          );
          executionPid = pid;
          if (pid) {
            dispatch({ type: "SET_ACTIVE_PTY", pid });
            setPendingHistoryItem((prevItem) => {
              if (prevItem?.type === "tool_group") {
                return {
                  ...prevItem,
                  tools: prevItem.tools.map(
                    (tool) => tool.callId === callId ? { ...tool, ptyId: pid } : tool
                  )
                };
              }
              return prevItem;
            });
          }
          const result = await resultPromise;
          setPendingHistoryItem(null);
          if (result.backgrounded && result.pid) {
            registerBackgroundTask(
              result.pid,
              rawQuery,
              cumulativeStdout,
              "notify"
            );
            dispatch({ type: "SET_ACTIVE_PTY", pid: null });
          }
          let mainContent;
          if (isBinaryStream || isBinary(result.rawOutput)) {
            mainContent = "[Command produced binary output, which is not shown.]";
          } else {
            mainContent = result.output.trim() || "(Command produced no output)";
          }
          let finalOutput = result.ansiOutput && result.ansiOutput.length > 0 ? result.ansiOutput : mainContent;
          let finalStatus = CoreToolCallStatus.Success;
          const prependToAnsiOutput = (output, text) => {
            const newLines = text.split("\n").map((line) => [
              {
                text: line,
                fg: "",
                bg: "",
                dim: false,
                bold: false,
                italic: false,
                underline: false,
                inverse: false,
                isUninitialized: false
              }
            ]);
            return [...newLines, [], ...output];
          };
          let prefix = "";
          if (result.error) {
            finalStatus = CoreToolCallStatus.Error;
            prefix = result.error.message;
          } else if (result.aborted) {
            finalStatus = CoreToolCallStatus.Cancelled;
            prefix = "Command was cancelled.";
          } else if (result.backgrounded) {
            finalStatus = CoreToolCallStatus.Success;
            finalOutput = `Command moved to background (PID: ${result.pid}). Output hidden. Press Ctrl+B to view.`;
            mainContent = finalOutput;
          } else if (result.signal) {
            finalStatus = CoreToolCallStatus.Error;
            prefix = `Command terminated by signal: ${result.signal}.`;
          } else if (result.exitCode !== 0) {
            finalStatus = CoreToolCallStatus.Error;
            prefix = `Command exited with code ${result.exitCode}.`;
          }
          if (prefix) {
            finalOutput = typeof finalOutput === "string" ? `${prefix}
${finalOutput}` : prependToAnsiOutput(finalOutput, prefix);
            mainContent = `${prefix}
${mainContent}`;
          }
          if (pwdFilePath && fs5.existsSync(pwdFilePath)) {
            const finalPwd = fs5.readFileSync(pwdFilePath, "utf8").trim();
            if (finalPwd && finalPwd !== targetDir) {
              const warning = `WARNING: shell mode is stateless; the directory change to '${finalPwd}' will not persist.`;
              finalOutput = typeof finalOutput === "string" ? `${warning}

${finalOutput}` : prependToAnsiOutput(finalOutput, warning);
              mainContent = `${warning}

${mainContent}`;
            }
          }
          const finalToolDisplay = {
            ...initialToolDisplay,
            status: finalStatus,
            resultDisplay: finalOutput
          };
          if (finalStatus !== CoreToolCallStatus.Cancelled) {
            addItemToHistory(
              {
                type: "tool_group",
                tools: [finalToolDisplay]
              },
              userMessageTimestamp
            );
          }
          addShellCommandToGeminiHistory(geminiClient, rawQuery, mainContent);
        } catch (err) {
          setPendingHistoryItem(null);
          const errorMessage = err instanceof Error ? err.message : String(err);
          addItemToHistory(
            {
              type: "error",
              text: `An unexpected error occurred: ${errorMessage}`
            },
            userMessageTimestamp
          );
        } finally {
          abortSignal.removeEventListener("abort", abortHandler);
          if (pwdFilePath && fs5.existsSync(pwdFilePath)) {
            fs5.unlinkSync(pwdFilePath);
          }
          dispatch({ type: "SET_ACTIVE_PTY", pid: null });
          setShellInputFocused(false);
        }
      };
      onExec(executeCommand());
      return true;
    },
    [
      config,
      onDebugMessage,
      addItemToHistory,
      setPendingHistoryItem,
      onExec,
      geminiClient,
      setShellInputFocused,
      terminalHeight,
      terminalWidth,
      registerBackgroundTask,
      m,
      dispatch
    ]
  );
  const backgroundTaskCount = Array.from(state.backgroundTasks.values()).filter(
    (s) => s.status === "running"
  ).length;
  return {
    handleShellCommand,
    activeShellPtyId: state.activeShellPtyId,
    lastShellOutputTime: state.lastShellOutputTime,
    backgroundTaskCount,
    isBackgroundTaskVisible: state.isBackgroundTaskVisible,
    toggleBackgroundTasks,
    backgroundCurrentExecution,
    registerBackgroundTask,
    dismissBackgroundTask,
    backgroundTasks: state.backgroundTasks
  };
};

// packages/cli/src/ui/components/BackgroundTaskDisplay.tsx
var import_jsx_runtime134 = __toESM(require_jsx_runtime(), 1);
var CONTENT_PADDING_X = 1;
var BORDER_WIDTH = 2;
var MAIN_BORDER_HEIGHT = 2;
var HEADER_HEIGHT = 1;
var FOOTER_HEIGHT = 1;
var TOTAL_OVERHEAD_HEIGHT = MAIN_BORDER_HEIGHT + HEADER_HEIGHT + FOOTER_HEIGHT;
var PROCESS_LIST_HEADER_HEIGHT = 3;
var TAB_DISPLAY_HORIZONTAL_PADDING = 4;
var LOG_PATH_OVERHEAD = 7;
var formatShellCommandForDisplay = (command, maxWidth) => {
  const commandFirstLine = command.split("\n")[0];
  return cpLen(commandFirstLine) > maxWidth ? `${cpSlice(commandFirstLine, 0, maxWidth - 3)}...` : commandFirstLine;
};
var BackgroundTaskDisplay = ({
  shells,
  activePid,
  width,
  height,
  isFocused,
  isListOpenProp
}) => {
  const keyMatchers = useKeyMatchers();
  const {
    dismissBackgroundTask,
    setActiveBackgroundTaskPid,
    setIsBackgroundTaskListOpen
  } = useUIActions();
  const activeShell = shells.get(activePid);
  const [output, setOutput] = (0, import_react96.useState)(
    activeShell?.output || ""
  );
  const [highlightedPid, setHighlightedPid] = (0, import_react96.useState)(
    activePid
  );
  const outputRef = (0, import_react96.useRef)(null);
  const subscribedRef = (0, import_react96.useRef)(false);
  (0, import_react96.useEffect)(() => {
    if (!activePid) return;
    const ptyWidth = Math.max(1, width - BORDER_WIDTH - CONTENT_PADDING_X * 2);
    const ptyHeight = Math.max(1, height - TOTAL_OVERHEAD_HEIGHT);
    ShellExecutionService.resizePty(activePid, ptyWidth, ptyHeight);
  }, [activePid, width, height]);
  (0, import_react96.useEffect)(() => {
    if (!activePid) {
      setOutput("");
      return;
    }
    const shell2 = shells.get(activePid);
    if (shell2) {
      setOutput(shell2.output);
    }
    subscribedRef.current = false;
    const unsubscribe = ShellExecutionService.subscribe(activePid, (event) => {
      if (event.type === "data") {
        if (typeof event.chunk === "string") {
          if (!subscribedRef.current) {
            setOutput(event.chunk);
          } else {
            setOutput(
              (prev) => typeof prev === "string" ? prev + event.chunk : event.chunk
            );
          }
        } else {
          setOutput(event.chunk);
        }
      }
    });
    subscribedRef.current = true;
    return () => {
      unsubscribe();
      subscribedRef.current = false;
    };
  }, [activePid, shells]);
  (0, import_react96.useEffect)(() => {
    if (isListOpenProp) {
      setHighlightedPid(activePid);
    }
  }, [isListOpenProp, activePid]);
  useKeypress(
    (key) => {
      if (!activeShell) return;
      if (isListOpenProp) {
        if (keyMatchers["background.escape" /* BACKGROUND_SHELL_ESCAPE */](key)) {
          setIsBackgroundTaskListOpen(false);
          return true;
        }
        if (keyMatchers["background.kill" /* KILL_BACKGROUND_SHELL */](key)) {
          if (highlightedPid) {
            void dismissBackgroundTask(highlightedPid);
          }
          return true;
        }
        if (keyMatchers["background.toggleList" /* TOGGLE_BACKGROUND_SHELL_LIST */](key)) {
          if (highlightedPid) {
            setActiveBackgroundTaskPid(highlightedPid);
          }
          setIsBackgroundTaskListOpen(false);
          return true;
        }
        return false;
      }
      if (keyMatchers["background.toggle" /* TOGGLE_BACKGROUND_SHELL */](key)) {
        return false;
      }
      if (keyMatchers["background.kill" /* KILL_BACKGROUND_SHELL */](key)) {
        void dismissBackgroundTask(activeShell.pid);
        return true;
      }
      if (keyMatchers["background.toggleList" /* TOGGLE_BACKGROUND_SHELL_LIST */](key)) {
        setIsBackgroundTaskListOpen(true);
        return true;
      }
      if (keyMatchers["background.select" /* BACKGROUND_SHELL_SELECT */](key)) {
        ShellExecutionService.writeToPty(activeShell.pid, "\r");
        return true;
      } else if (keyMatchers["edit.deleteLeft" /* DELETE_CHAR_LEFT */](key)) {
        ShellExecutionService.writeToPty(activeShell.pid, "\b");
        return true;
      } else if (key.sequence) {
        ShellExecutionService.writeToPty(activeShell.pid, key.sequence);
        return true;
      }
      return false;
    },
    { isActive: isFocused && !!activeShell }
  );
  const helpTextParts = [
    { label: "Close", command: "background.toggle" /* TOGGLE_BACKGROUND_SHELL */ },
    { label: "Kill", command: "background.kill" /* KILL_BACKGROUND_SHELL */ },
    { label: "List", command: "background.toggleList" /* TOGGLE_BACKGROUND_SHELL_LIST */ }
  ];
  const helpTextStr = helpTextParts.map((p) => `${p.label} (${formatCommand(p.command)})`).join(" | ");
  const renderHelpText = () => /* @__PURE__ */ (0, import_jsx_runtime134.jsx)(Text, { children: helpTextParts.map((p, i) => /* @__PURE__ */ (0, import_jsx_runtime134.jsxs)(Text, { children: [
    i > 0 ? " | " : "",
    p.label,
    " (",
    /* @__PURE__ */ (0, import_jsx_runtime134.jsx)(Text, { color: theme.text.accent, children: formatCommand(p.command) }),
    ")"
  ] }, p.label)) });
  const renderTabs = () => {
    const shellList = Array.from(shells.values()).filter(
      (s) => s.status === "running"
    );
    const pidInfoWidth = getCachedStringWidth(
      ` (PID: ${activePid}) ${isFocused ? "(Focused)" : ""}`
    );
    const availableWidth = width - TAB_DISPLAY_HORIZONTAL_PADDING - getCachedStringWidth(helpTextStr) - pidInfoWidth;
    let currentWidth = 0;
    const tabs = [];
    for (let i = 0; i < shellList.length; i++) {
      const shell2 = shellList[i];
      const labelOverhead = 4 + (i + 1).toString().length;
      const maxTabLabelLength = Math.max(
        1,
        Math.floor(availableWidth / shellList.length) - labelOverhead
      );
      const truncatedCommand = formatShellCommandForDisplay(
        shell2.command,
        maxTabLabelLength
      );
      const label = ` ${i + 1}: ${truncatedCommand} `;
      const labelWidth = getCachedStringWidth(label);
      if (i > 0 && currentWidth + labelWidth > availableWidth) {
        break;
      }
      const isActive = shell2.pid === activePid;
      tabs.push(
        /* @__PURE__ */ (0, import_jsx_runtime134.jsx)(
          Text,
          {
            color: isActive ? theme.text.primary : theme.text.secondary,
            bold: isActive,
            children: label
          },
          shell2.pid
        )
      );
      currentWidth += labelWidth;
    }
    if (shellList.length > tabs.length && !isListOpenProp) {
      const overflowLabel = ` ... (${formatCommand("background.toggleList" /* TOGGLE_BACKGROUND_SHELL_LIST */)}) `;
      const overflowWidth = getCachedStringWidth(overflowLabel);
      const shouldShowOverflow = tabs.length > 1 || availableWidth - currentWidth >= overflowWidth;
      if (shouldShowOverflow) {
        tabs.push(
          /* @__PURE__ */ (0, import_jsx_runtime134.jsx)(Text, { color: theme.status.warning, bold: true, children: overflowLabel }, "overflow")
        );
      }
    }
    return tabs;
  };
  const renderProcessList = () => {
    const maxCommandLength = Math.max(
      0,
      width - BORDER_WIDTH - CONTENT_PADDING_X * 2 - 10
    );
    const items = Array.from(
      shells.values()
    ).map((shell2, index) => {
      const truncatedCommand = formatShellCommandForDisplay(
        shell2.command,
        maxCommandLength
      );
      let label = `${index + 1}: ${truncatedCommand} (PID: ${shell2.pid})`;
      if (shell2.status === "exited") {
        label += ` (Exit Code: ${shell2.exitCode})`;
      }
      return {
        key: shell2.pid.toString(),
        value: shell2.pid,
        label
      };
    });
    const initialIndex = items.findIndex((item) => item.value === activePid);
    return /* @__PURE__ */ (0, import_jsx_runtime134.jsxs)(Box_default, { flexDirection: "column", height: "100%", width: "100%", children: [
      /* @__PURE__ */ (0, import_jsx_runtime134.jsx)(Box_default, { flexShrink: 0, marginBottom: 1, paddingTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime134.jsx)(Text, { bold: true, children: `Select Process (${formatCommand("background.select" /* BACKGROUND_SHELL_SELECT */)} to select, ${formatCommand("background.kill" /* KILL_BACKGROUND_SHELL */)} to kill, ${formatCommand("background.escape" /* BACKGROUND_SHELL_ESCAPE */)} to cancel):` }) }),
      /* @__PURE__ */ (0, import_jsx_runtime134.jsx)(Box_default, { flexGrow: 1, width: "100%", children: /* @__PURE__ */ (0, import_jsx_runtime134.jsx)(
        RadioButtonSelect,
        {
          items,
          initialIndex: initialIndex >= 0 ? initialIndex : 0,
          onSelect: (pid) => {
            setActiveBackgroundTaskPid(pid);
            setIsBackgroundTaskListOpen(false);
          },
          onHighlight: (pid) => setHighlightedPid(pid),
          isFocused,
          maxItemsToShow: Math.max(
            1,
            height - TOTAL_OVERHEAD_HEIGHT - PROCESS_LIST_HEADER_HEIGHT
          ),
          renderItem: (item, { isSelected: _isSelected, titleColor: _titleColor }) => {
            const shell2 = shells.get(item.value);
            if (!shell2) return /* @__PURE__ */ (0, import_jsx_runtime134.jsx)(Text, { children: item.label });
            const truncatedCommand = formatShellCommandForDisplay(
              shell2.command,
              maxCommandLength
            );
            return /* @__PURE__ */ (0, import_jsx_runtime134.jsxs)(Text, { children: [
              truncatedCommand,
              " (PID: ",
              shell2.pid,
              ")",
              shell2.status === "exited" ? /* @__PURE__ */ (0, import_jsx_runtime134.jsxs)(
                Text,
                {
                  color: shell2.exitCode === 0 ? theme.status.success : theme.status.error,
                  children: [
                    " ",
                    "(Exit Code: ",
                    shell2.exitCode,
                    ")"
                  ]
                }
              ) : null
            ] });
          }
        }
      ) })
    ] });
  };
  const renderFooter = () => {
    const pidToDisplay = isListOpenProp ? highlightedPid ?? activePid : activePid;
    if (!pidToDisplay) return null;
    const logPath = ShellExecutionService.getLogFilePath(pidToDisplay);
    const displayPath = shortenPath(
      tildeifyPath(logPath),
      width - LOG_PATH_OVERHEAD
    );
    return /* @__PURE__ */ (0, import_jsx_runtime134.jsx)(Box_default, { paddingX: 1, children: /* @__PURE__ */ (0, import_jsx_runtime134.jsxs)(Text, { color: theme.text.secondary, children: [
      "Log: ",
      displayPath
    ] }) });
  };
  const renderOutput = () => {
    const lines = typeof output === "string" ? output.split("\n") : output;
    return /* @__PURE__ */ (0, import_jsx_runtime134.jsx)(
      ScrollableListWithForwardRef,
      {
        ref: outputRef,
        data: lines,
        renderItem: ({ item: line, index }) => {
          if (typeof line === "string") {
            return /* @__PURE__ */ (0, import_jsx_runtime134.jsx)(Text, { children: line }, index);
          }
          return /* @__PURE__ */ (0, import_jsx_runtime134.jsx)(Text, { wrap: "truncate", children: line.length > 0 ? line.map((token, tokenIndex) => /* @__PURE__ */ (0, import_jsx_runtime134.jsx)(
            Text,
            {
              color: token.fg,
              backgroundColor: token.bg,
              inverse: token.inverse,
              dimColor: token.dim,
              bold: token.bold,
              italic: token.italic,
              underline: token.underline,
              children: token.text
            },
            tokenIndex
          )) : null }, index);
        },
        estimatedItemHeight: () => 1,
        keyExtractor: (_, index) => index.toString(),
        hasFocus: isFocused,
        initialScrollIndex: SCROLL_TO_ITEM_END
      }
    );
  };
  return /* @__PURE__ */ (0, import_jsx_runtime134.jsxs)(
    Box_default,
    {
      flexDirection: "column",
      height: "100%",
      width: "100%",
      borderStyle: "single",
      borderColor: isFocused ? theme.ui.focus : void 0,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime134.jsxs)(
          Box_default,
          {
            flexDirection: "row",
            justifyContent: "space-between",
            borderStyle: "single",
            borderBottom: false,
            borderLeft: false,
            borderRight: false,
            borderTop: false,
            paddingX: 1,
            borderColor: isFocused ? theme.ui.focus : void 0,
            children: [
              /* @__PURE__ */ (0, import_jsx_runtime134.jsxs)(Box_default, { flexDirection: "row", children: [
                renderTabs(),
                /* @__PURE__ */ (0, import_jsx_runtime134.jsxs)(Text, { bold: true, children: [
                  " ",
                  "(PID: ",
                  activeShell?.pid,
                  ") ",
                  isFocused ? "(Focused)" : ""
                ] })
              ] }),
              renderHelpText()
            ]
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime134.jsx)(Box_default, { flexGrow: 1, overflow: "hidden", paddingX: CONTENT_PADDING_X, children: isListOpenProp ? renderProcessList() : renderOutput() }),
        renderFooter()
      ]
    }
  );
};

// packages/cli/src/ui/layouts/DefaultAppLayout.tsx
var import_jsx_runtime135 = __toESM(require_jsx_runtime(), 1);
var DefaultAppLayout = () => {
  const uiState = useUIState();
  const { copyModeEnabled } = useInputState();
  const isAlternateBuffer = useAlternateBuffer();
  const { rootUiRef, terminalHeight } = uiState;
  useFlickerDetector(rootUiRef, terminalHeight);
  return /* @__PURE__ */ (0, import_jsx_runtime135.jsxs)(
    Box_default,
    {
      flexDirection: "column",
      width: uiState.terminalWidth,
      height: isAlternateBuffer ? terminalHeight : void 0,
      paddingBottom: isAlternateBuffer ? 1 : void 0,
      flexShrink: 0,
      flexGrow: 0,
      ref: uiState.rootUiRef,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime135.jsx)(MainContent, {}),
        uiState.isBackgroundTaskVisible && uiState.backgroundTasks.size > 0 && uiState.activeBackgroundTaskPid && uiState.backgroundTaskHeight > 0 && uiState.streamingState !== "waiting_for_confirmation" /* WaitingForConfirmation */ && /* @__PURE__ */ (0, import_jsx_runtime135.jsx)(Box_default, { height: uiState.backgroundTaskHeight, flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime135.jsx)(
          BackgroundTaskDisplay,
          {
            shells: uiState.backgroundTasks,
            activePid: uiState.activeBackgroundTaskPid,
            width: uiState.terminalWidth,
            height: uiState.backgroundTaskHeight,
            isFocused: uiState.embeddedShellFocused && !uiState.dialogsVisible,
            isListOpenProp: uiState.isBackgroundTaskListOpen
          }
        ) }),
        /* @__PURE__ */ (0, import_jsx_runtime135.jsxs)(
          Box_default,
          {
            flexDirection: "column",
            ref: uiState.mainControlsRef,
            flexShrink: 0,
            flexGrow: 0,
            width: uiState.terminalWidth,
            height: copyModeEnabled ? uiState.stableControlsHeight : void 0,
            children: [
              /* @__PURE__ */ (0, import_jsx_runtime135.jsx)(Notifications, {}),
              /* @__PURE__ */ (0, import_jsx_runtime135.jsx)(CopyModeWarning, {}),
              uiState.customDialog ? uiState.customDialog : uiState.dialogsVisible ? /* @__PURE__ */ (0, import_jsx_runtime135.jsx)(
                DialogManager,
                {
                  terminalWidth: uiState.terminalWidth,
                  addItem: uiState.historyManager.addItem
                }
              ) : /* @__PURE__ */ (0, import_jsx_runtime135.jsx)(Composer, { isFocused: true }),
              /* @__PURE__ */ (0, import_jsx_runtime135.jsx)(ExitWarning, {})
            ]
          }
        )
      ]
    }
  );
};

// packages/cli/src/ui/components/AlternateBufferQuittingDisplay.tsx
var import_jsx_runtime136 = __toESM(require_jsx_runtime(), 1);
var AlternateBufferQuittingDisplay = () => {
  const { version } = useAppContext();
  const uiState = useUIState();
  const confirmingTool = useConfirmingTool();
  const showPromptedTool = confirmingTool !== null;
  return /* @__PURE__ */ (0, import_jsx_runtime136.jsxs)(
    Box_default,
    {
      flexDirection: "column",
      flexShrink: 0,
      flexGrow: 0,
      width: uiState.terminalWidth,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime136.jsx)(AppHeader, { version }, "app-header"),
        uiState.history.map((h) => /* @__PURE__ */ (0, import_jsx_runtime136.jsx)(
          HistoryItemDisplay,
          {
            terminalWidth: uiState.mainAreaWidth,
            availableTerminalHeight: void 0,
            availableTerminalHeightGemini: MAX_GEMINI_MESSAGE_LINES,
            item: h,
            isPending: false,
            commands: uiState.slashCommands
          },
          h.id
        )),
        uiState.pendingHistoryItems.map((item, i) => /* @__PURE__ */ (0, import_jsx_runtime136.jsx)(
          HistoryItemDisplay,
          {
            availableTerminalHeight: void 0,
            terminalWidth: uiState.mainAreaWidth,
            item: { ...item, id: 0 },
            isPending: true
          },
          i
        )),
        showPromptedTool && /* @__PURE__ */ (0, import_jsx_runtime136.jsxs)(Box_default, { flexDirection: "column", marginTop: 1, marginBottom: 1, children: [
          /* @__PURE__ */ (0, import_jsx_runtime136.jsx)(Text, { color: theme.status.warning, bold: true, children: "Action Required (was prompted):" }),
          /* @__PURE__ */ (0, import_jsx_runtime136.jsxs)(Box_default, { marginTop: 1, children: [
            /* @__PURE__ */ (0, import_jsx_runtime136.jsx)(
              ToolStatusIndicator,
              {
                status: confirmingTool.tool.status,
                name: confirmingTool.tool.name
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime136.jsx)(
              ToolInfo,
              {
                name: confirmingTool.tool.name,
                status: confirmingTool.tool.status,
                description: confirmingTool.tool.description,
                emphasis: "high"
              }
            )
          ] })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime136.jsx)(QuittingDisplay, {})
      ]
    }
  );
};

// packages/cli/src/ui/App.tsx
var import_jsx_runtime137 = __toESM(require_jsx_runtime(), 1);
var App = () => {
  const uiState = useUIState();
  const isAlternateBuffer = useAlternateBuffer();
  const isScreenReaderEnabled = use_is_screen_reader_enabled_default();
  if (uiState.quittingMessages) {
    if (isAlternateBuffer) {
      return /* @__PURE__ */ (0, import_jsx_runtime137.jsx)(StreamingContext.Provider, { value: uiState.streamingState, children: /* @__PURE__ */ (0, import_jsx_runtime137.jsx)(AlternateBufferQuittingDisplay, {}) });
    } else {
      return /* @__PURE__ */ (0, import_jsx_runtime137.jsx)(QuittingDisplay, {});
    }
  }
  return /* @__PURE__ */ (0, import_jsx_runtime137.jsx)(StreamingContext.Provider, { value: uiState.streamingState, children: isScreenReaderEnabled ? /* @__PURE__ */ (0, import_jsx_runtime137.jsx)(ScreenReaderAppLayout, {}) : /* @__PURE__ */ (0, import_jsx_runtime137.jsx)(DefaultAppLayout, {}) });
};

// packages/cli/src/ui/AppContainer.tsx
import process14 from "node:process";

// packages/cli/src/ui/hooks/useMemoryMonitor.ts
var import_react97 = __toESM(require_react(), 1);
import process8 from "node:process";
var MEMORY_WARNING_THRESHOLD = 7 * 1024 * 1024 * 1024;
var MEMORY_CHECK_INTERVAL = 60 * 1e3;
var useMemoryMonitor = ({ addItem }) => {
  (0, import_react97.useEffect)(() => {
    const intervalId = setInterval(() => {
      const usage = process8.memoryUsage().rss;
      if (usage > MEMORY_WARNING_THRESHOLD) {
        addItem(
          {
            type: "warning" /* WARNING */,
            text: `High memory usage detected: ${(usage / (1024 * 1024 * 1024)).toFixed(2)} GB. If you experience a crash, please file a bug report by running \`/bug\``
          },
          Date.now()
        );
        clearInterval(intervalId);
      }
    }, MEMORY_CHECK_INTERVAL);
    return () => clearInterval(intervalId);
  }, [addItem]);
};

// packages/cli/src/ui/hooks/useThemeCommand.ts
var import_react99 = __toESM(require_react(), 1);
import process9 from "node:process";

// packages/cli/src/ui/contexts/TerminalContext.tsx
var import_react98 = __toESM(require_react(), 1);
var import_jsx_runtime138 = __toESM(require_jsx_runtime(), 1);
var TerminalContext = (0, import_react98.createContext)(
  void 0
);
function useTerminalContext() {
  const context = (0, import_react98.useContext)(TerminalContext);
  if (!context) {
    throw new Error(
      "useTerminalContext must be used within a TerminalProvider"
    );
  }
  return context;
}
function TerminalProvider({ children }) {
  const { stdin } = use_stdin_default();
  const { stdout } = use_stdout_default();
  const subscribers = (0, import_react98.useRef)(/* @__PURE__ */ new Set()).current;
  const bufferRef = (0, import_react98.useRef)("");
  const subscribe2 = (0, import_react98.useCallback)(
    (handler) => {
      subscribers.add(handler);
    },
    [subscribers]
  );
  const unsubscribe = (0, import_react98.useCallback)(
    (handler) => {
      subscribers.delete(handler);
    },
    [subscribers]
  );
  const queryTerminalBackground = (0, import_react98.useCallback)(
    async () => new Promise((resolve3) => {
      const handler = () => {
        unsubscribe(handler);
        resolve3();
      };
      subscribe2(handler);
      TerminalCapabilityManager.queryBackgroundColor(stdout);
      setTimeout(() => {
        unsubscribe(handler);
        resolve3();
      }, 100);
    }),
    [stdout, subscribe2, unsubscribe]
  );
  (0, import_react98.useEffect)(() => {
    const handleData = (data) => {
      bufferRef.current += typeof data === "string" ? data : data.toString("utf-8");
      const match = bufferRef.current.match(
        TerminalCapabilityManager.OSC_11_REGEX
      );
      if (match) {
        const colorStr = `rgb:${match[1]}/${match[2]}/${match[3]}`;
        for (const handler of subscribers) {
          handler(colorStr);
        }
        if (match.index !== void 0) {
          bufferRef.current = bufferRef.current.slice(
            match.index + match[0].length
          );
        }
      } else if (bufferRef.current.length > 4096) {
        bufferRef.current = bufferRef.current.slice(-1024);
      }
    };
    stdin.on("data", handleData);
    return () => {
      stdin.removeListener("data", handleData);
    };
  }, [stdin, subscribers]);
  return /* @__PURE__ */ (0, import_jsx_runtime138.jsx)(
    TerminalContext.Provider,
    {
      value: { subscribe: subscribe2, unsubscribe, queryTerminalBackground },
      children
    }
  );
}

// packages/cli/src/ui/hooks/useThemeCommand.ts
var useThemeCommand = (loadedSettings, setThemeError, addItem, initialThemeError, refreshStatic) => {
  const [isThemeDialogOpen, setIsThemeDialogOpen] = (0, import_react99.useState)(!!initialThemeError);
  const { queryTerminalBackground } = useTerminalContext();
  const openThemeDialog = (0, import_react99.useCallback)(async () => {
    if (process9.env["NO_COLOR"]) {
      addItem(
        {
          type: "info" /* INFO */,
          text: "Theme configuration unavailable due to NO_COLOR env variable."
        },
        Date.now()
      );
      return;
    }
    await queryTerminalBackground();
    setIsThemeDialogOpen(true);
  }, [addItem, queryTerminalBackground]);
  const applyTheme = (0, import_react99.useCallback)(
    (themeName) => {
      if (!themeManager.setActiveTheme(themeName)) {
        setIsThemeDialogOpen(true);
        setThemeError(`Theme "${themeName}" not found.`);
      } else {
        setThemeError(null);
      }
    },
    [setThemeError]
  );
  const handleThemeHighlight = (0, import_react99.useCallback)(
    (themeName) => {
      applyTheme(themeName);
    },
    [applyTheme]
  );
  const closeThemeDialog = (0, import_react99.useCallback)(() => {
    applyTheme(loadedSettings.merged.ui.theme);
    setIsThemeDialogOpen(false);
  }, [applyTheme, loadedSettings]);
  const handleThemeSelect = (0, import_react99.useCallback)(
    async (themeName, scope) => {
      try {
        const mergedCustomThemes = {
          ...loadedSettings.user.settings.ui?.customThemes || {},
          ...loadedSettings.workspace.settings.ui?.customThemes || {}
        };
        const isBuiltIn = themeManager.findThemeByName(themeName);
        const isCustom = themeName && mergedCustomThemes[themeName];
        if (!isBuiltIn && !isCustom) {
          setThemeError(`Theme "${themeName}" not found in selected scope.`);
          setIsThemeDialogOpen(true);
          return;
        }
        loadedSettings.setValue(scope, "ui.theme", themeName);
        if (loadedSettings.merged.ui.customThemes) {
          themeManager.loadCustomThemes(loadedSettings.merged.ui.customThemes);
        }
        applyTheme(loadedSettings.merged.ui.theme);
        refreshStatic();
        setThemeError(null);
      } finally {
        setIsThemeDialogOpen(false);
      }
    },
    [applyTheme, loadedSettings, refreshStatic, setThemeError]
  );
  return {
    isThemeDialogOpen,
    openThemeDialog,
    closeThemeDialog,
    handleThemeSelect,
    handleThemeHighlight
  };
};

// packages/cli/src/ui/hooks/useQuotaAndFallback.ts
var import_react100 = __toESM(require_react(), 1);

// packages/cli/src/ui/hooks/creditsFlowHandler.ts
async function handleCreditsFlow(args) {
  const creditBalance = getG1CreditBalance(args.paidTier);
  if (creditBalance == null) {
    return null;
  }
  const { overageStrategy } = args;
  if (shouldAutoUseCredits(overageStrategy, creditBalance)) {
    return null;
  }
  if (shouldShowOverageMenu(overageStrategy, creditBalance)) {
    return handleOverageMenu(args, creditBalance);
  }
  if (shouldShowEmptyWalletMenu(overageStrategy, creditBalance)) {
    return handleEmptyWalletMenu(args);
  }
  return null;
}
async function handleOverageMenu(args, creditBalance) {
  const {
    config,
    fallbackModel,
    usageLimitReachedModel,
    overageStrategy,
    resetTime,
    isDialogPending,
    setOverageMenuRequest,
    setModelSwitchedFromQuotaError
  } = args;
  logBillingEvent(
    config,
    new OverageMenuShownEvent(
      usageLimitReachedModel,
      creditBalance,
      overageStrategy
    )
  );
  if (isDialogPending.current) {
    return "stop";
  }
  isDialogPending.current = true;
  setModelSwitchedFromQuotaError(true);
  config.setQuotaErrorOccurred(true);
  const overageIntent = await new Promise((resolve3) => {
    setOverageMenuRequest({
      failedModel: usageLimitReachedModel,
      fallbackModel,
      resetTime,
      creditBalance,
      resolve: resolve3
    });
  });
  setOverageMenuRequest(null);
  isDialogPending.current = false;
  logOverageOptionSelected(
    config,
    usageLimitReachedModel,
    overageIntent,
    creditBalance
  );
  switch (overageIntent) {
    case "use_credits":
      setModelSwitchedFromQuotaError(false);
      config.setQuotaErrorOccurred(false);
      config.setOverageStrategy("always");
      return "retry_with_credits";
    case "use_fallback":
      return "retry_always";
    case "manage": {
      logCreditPurchaseClick(config, "manage", usageLimitReachedModel);
      const manageUrl = await openG1Url(
        "activity",
        G1_UTM_CAMPAIGNS.MANAGE_ACTIVITY
      );
      if (manageUrl) {
        args.historyManager.addItem(
          {
            type: "info" /* INFO */,
            text: `Please open this URL in a browser: ${manageUrl}`
          },
          Date.now()
        );
      }
      return "stop";
    }
    case "stop":
    default:
      return "stop";
  }
}
async function handleEmptyWalletMenu(args) {
  const {
    config,
    fallbackModel,
    usageLimitReachedModel,
    resetTime,
    isDialogPending,
    setEmptyWalletRequest,
    setModelSwitchedFromQuotaError
  } = args;
  logBillingEvent(
    config,
    new EmptyWalletMenuShownEvent(usageLimitReachedModel)
  );
  if (isDialogPending.current) {
    return "stop";
  }
  isDialogPending.current = true;
  setModelSwitchedFromQuotaError(true);
  config.setQuotaErrorOccurred(true);
  const emptyWalletIntent = await new Promise((resolve3) => {
    setEmptyWalletRequest({
      failedModel: usageLimitReachedModel,
      fallbackModel,
      resetTime,
      onGetCredits: async () => {
        logCreditPurchaseClick(
          config,
          "empty_wallet_menu",
          usageLimitReachedModel
        );
        const creditsUrl = await openG1Url(
          "credits",
          G1_UTM_CAMPAIGNS.EMPTY_WALLET_ADD_CREDITS
        );
        if (creditsUrl) {
          args.historyManager.addItem(
            {
              type: "info" /* INFO */,
              text: `Please open this URL in a browser: ${creditsUrl}`
            },
            Date.now()
          );
        }
      },
      resolve: resolve3
    });
  });
  setEmptyWalletRequest(null);
  isDialogPending.current = false;
  switch (emptyWalletIntent) {
    case "get_credits":
      args.historyManager.addItem(
        {
          type: "info" /* INFO */,
          text: "Newly purchased AI credits may take a few minutes to update. Run /stats to check your balance."
        },
        Date.now()
      );
      return "stop";
    case "use_fallback":
      return "retry_always";
    case "stop":
    default:
      return "stop";
  }
}
function logOverageOptionSelected(config, model, option, creditBalance) {
  logBillingEvent(
    config,
    new OverageOptionSelectedEvent(model, option, creditBalance)
  );
  recordOverageOptionSelected(config, {
    selected_option: option,
    model
  });
}
function logCreditPurchaseClick(config, source2, model) {
  logBillingEvent(config, new CreditPurchaseClickEvent(source2, model));
  recordCreditPurchaseClick(config, { source: source2, model });
}
async function openG1Url(path16, campaign) {
  try {
    const userEmail = new UserAccountManager().getCachedGoogleAccount() ?? "";
    const url2 = buildG1Url(path16, userEmail, campaign);
    if (!shouldLaunchBrowser()) {
      return url2;
    }
    await openBrowserSecurely(url2);
  } catch {
  }
  return void 0;
}

// packages/cli/src/ui/hooks/useQuotaAndFallback.ts
function useQuotaAndFallback({
  config,
  historyManager,
  userTier,
  paidTier,
  settings,
  setModelSwitchedFromQuotaError,
  onShowAuthSelection,
  errorVerbosity = "full"
}) {
  const [proQuotaRequest, setProQuotaRequest] = (0, import_react100.useState)(null);
  const [validationRequest, setValidationRequest] = (0, import_react100.useState)(null);
  const [overageMenuRequest, setOverageMenuRequest] = (0, import_react100.useState)(null);
  const [emptyWalletRequest, setEmptyWalletRequest] = (0, import_react100.useState)(null);
  const isDialogPending = (0, import_react100.useRef)(false);
  const isValidationPending = (0, import_react100.useRef)(false);
  (0, import_react100.useEffect)(() => {
    const fallbackHandler = async (failedModel, fallbackModel, error) => {
      const contentGeneratorConfig = config.getContentGeneratorConfig();
      let message;
      let isTerminalQuotaError = false;
      let isModelNotFoundError = false;
      const usageLimitReachedModel = isProModel(failedModel) ? "all Pro models" : failedModel;
      if (error instanceof TerminalQuotaError) {
        isTerminalQuotaError = true;
        const isInsufficientCredits = error.isInsufficientCredits;
        if (!isInsufficientCredits && paidTier?.availableCredits && isOverageEligibleModel(failedModel)) {
          const resetTime = error.retryDelayMs ? getResetTimeMessage(error.retryDelayMs) : void 0;
          const overageStrategy = config.getBillingSettings().overageStrategy;
          const creditsResult = await handleCreditsFlow({
            config,
            paidTier,
            overageStrategy,
            failedModel,
            fallbackModel,
            usageLimitReachedModel,
            resetTime,
            historyManager,
            setModelSwitchedFromQuotaError,
            isDialogPending,
            setOverageMenuRequest,
            setEmptyWalletRequest
          });
          if (creditsResult) return creditsResult;
        }
        const messageLines = [
          `Usage limit reached for ${usageLimitReachedModel}.`,
          error.retryDelayMs ? `Access resets at ${getResetTimeMessage(error.retryDelayMs)}.` : null,
          `/stats model for usage details`,
          `/model to switch models.`,
          contentGeneratorConfig?.authType === AuthType.LOGIN_WITH_GOOGLE ? `/auth to switch to API key.` : null
        ].filter(Boolean);
        message = messageLines.join("\n");
      } else if (error instanceof ModelNotFoundError) {
        isModelNotFoundError = true;
        if (VALID_GEMINI_MODELS.has(failedModel)) {
          const messageLines = [
            `It seems like you don't have access to ${getDisplayString(failedModel)}.`,
            `Your admin might have disabled the access. Contact them to enable the Preview Release Channel.`
          ];
          message = messageLines.join("\n");
        } else {
          const messageLines = [
            `Model "${failedModel}" was not found or is invalid.`,
            `/model to switch models.`
          ];
          message = messageLines.join("\n");
        }
      } else {
        const messageLines = [
          `We are currently experiencing high demand.`,
          "We apologize and appreciate your patience.",
          "/model to switch models."
        ];
        message = messageLines.join("\n");
      }
      if (errorVerbosity === "low" && !isTerminalQuotaError && !isModelNotFoundError) {
        return "retry_once";
      }
      setModelSwitchedFromQuotaError(true);
      config.setQuotaErrorOccurred(true);
      if (isDialogPending.current) {
        return "stop";
      }
      isDialogPending.current = true;
      const intent = await new Promise(
        (resolve3) => {
          setProQuotaRequest({
            failedModel,
            fallbackModel,
            resolve: resolve3,
            message,
            isTerminalQuotaError,
            isModelNotFoundError,
            authType: contentGeneratorConfig?.authType
          });
        }
      );
      return intent;
    };
    config.setFallbackModelHandler(fallbackHandler);
  }, [
    config,
    historyManager,
    userTier,
    paidTier,
    settings,
    setModelSwitchedFromQuotaError,
    onShowAuthSelection,
    errorVerbosity
  ]);
  (0, import_react100.useEffect)(() => {
    const validationHandler = async (validationLink, validationDescription, learnMoreUrl) => {
      if (isValidationPending.current) {
        return "cancel";
      }
      isValidationPending.current = true;
      const intent = await new Promise(
        (resolve3) => {
          setValidationRequest({
            validationLink,
            validationDescription,
            learnMoreUrl,
            resolve: resolve3
          });
        }
      );
      return intent;
    };
    config.setValidationHandler(validationHandler);
  }, [config]);
  const handleProQuotaChoice = (0, import_react100.useCallback)(
    (choice) => {
      if (!proQuotaRequest) return;
      const intent = choice;
      proQuotaRequest.resolve(intent);
      setProQuotaRequest(null);
      isDialogPending.current = false;
      if (choice === "retry_always" || choice === "retry_once") {
        setModelSwitchedFromQuotaError(false);
        config.setQuotaErrorOccurred(false);
        if (choice === "retry_always") {
          historyManager.addItem(
            {
              type: "info" /* INFO */,
              text: `Switched to fallback model ${proQuotaRequest.fallbackModel}`
            },
            Date.now()
          );
        }
      }
    },
    [proQuotaRequest, historyManager, config, setModelSwitchedFromQuotaError]
  );
  const handleValidationChoice = (0, import_react100.useCallback)(
    (choice) => {
      if (!isValidationPending.current || !validationRequest) return;
      isValidationPending.current = false;
      validationRequest.resolve(choice);
      setValidationRequest(null);
      if (choice === "change_auth" || choice === "cancel") {
        onShowAuthSelection();
      }
    },
    [validationRequest, onShowAuthSelection]
  );
  const handleOverageMenuChoice = (0, import_react100.useCallback)(
    (choice) => {
      if (!overageMenuRequest) return;
      overageMenuRequest.resolve(choice);
    },
    [overageMenuRequest]
  );
  const handleEmptyWalletChoice = (0, import_react100.useCallback)(
    (choice) => {
      if (!emptyWalletRequest) return;
      emptyWalletRequest.resolve(choice);
    },
    [emptyWalletRequest]
  );
  return {
    proQuotaRequest,
    handleProQuotaChoice,
    validationRequest,
    handleValidationChoice,
    // G1 AI Credits
    overageMenuRequest,
    handleOverageMenuChoice,
    emptyWalletRequest,
    handleEmptyWalletChoice
  };
}
function getResetTimeMessage(delayMs) {
  const resetDate = new Date(Date.now() + delayMs);
  const timeFormatter = new Intl.DateTimeFormat("en-US", {
    hour: "numeric",
    minute: "2-digit",
    timeZoneName: "short"
  });
  return timeFormatter.format(resetDate);
}

// packages/cli/src/ui/hooks/useEditorSettings.ts
var import_react101 = __toESM(require_react(), 1);

// packages/cli/src/config/settingPaths.ts
var SettingPaths = {
  General: {
    PreferredEditor: "general.preferredEditor"
  }
};

// packages/cli/src/ui/hooks/useEditorSettings.ts
var useEditorSettings = (loadedSettings, setEditorError, addItem) => {
  const [isEditorDialogOpen, setIsEditorDialogOpen] = (0, import_react101.useState)(false);
  const openEditorDialog = (0, import_react101.useCallback)(() => {
    setIsEditorDialogOpen(true);
  }, []);
  const handleEditorSelect = (0, import_react101.useCallback)(
    (editorType, scope) => {
      if (editorType && (!hasValidEditorCommand(editorType) || !allowEditorTypeInSandbox(editorType))) {
        return;
      }
      try {
        loadedSettings.setValue(
          scope,
          SettingPaths.General.PreferredEditor,
          editorType
        );
        addItem(
          {
            type: "info" /* INFO */,
            text: `Editor preference ${editorType ? `set to "${getEditorDisplayName(editorType)}"` : "cleared"} in ${scope} settings.`
          },
          Date.now()
        );
        setEditorError(null);
        setIsEditorDialogOpen(false);
        coreEvents.emit(CoreEvent.EditorSelected, { editor: editorType });
      } catch (error) {
        setEditorError(`Failed to set editor preference: ${error}`);
      }
    },
    [loadedSettings, setEditorError, addItem]
  );
  const exitEditorDialog = (0, import_react101.useCallback)(() => {
    setIsEditorDialogOpen(false);
    coreEvents.emit(CoreEvent.EditorSelected, { editor: void 0 });
  }, []);
  return {
    isEditorDialogOpen,
    openEditorDialog,
    handleEditorSelect,
    exitEditorDialog
  };
};

// packages/cli/src/ui/hooks/useSettingsCommand.ts
var import_react102 = __toESM(require_react(), 1);
function useSettingsCommand() {
  const [isSettingsDialogOpen, setIsSettingsDialogOpen] = (0, import_react102.useState)(false);
  const openSettingsDialog = (0, import_react102.useCallback)(() => {
    setIsSettingsDialogOpen(true);
  }, []);
  const closeSettingsDialog = (0, import_react102.useCallback)(() => {
    setIsSettingsDialogOpen(false);
  }, []);
  return {
    isSettingsDialogOpen,
    openSettingsDialog,
    closeSettingsDialog
  };
}

// packages/cli/src/ui/hooks/useModelCommand.ts
var import_react103 = __toESM(require_react(), 1);
var useModelCommand = () => {
  const [isModelDialogOpen, setIsModelDialogOpen] = (0, import_react103.useState)(false);
  const openModelDialog = (0, import_react103.useCallback)(() => {
    setIsModelDialogOpen(true);
  }, []);
  const closeModelDialog = (0, import_react103.useCallback)(() => {
    setIsModelDialogOpen(false);
  }, []);
  return {
    isModelDialogOpen,
    openModelDialog,
    closeModelDialog
  };
};

// packages/cli/src/ui/hooks/slashCommandProcessor.ts
var import_react104 = __toESM(require_react(), 1);
import process10 from "node:process";

// packages/cli/src/services/SkillCommandLoader.ts
var SkillCommandLoader = class {
  constructor(config) {
    this.config = config;
  }
  /**
   * Discovers all available skills from the SkillManager and converts
   * them into executable slash commands.
   *
   * @param _signal An AbortSignal (unused for this synchronous loader).
   * @returns A promise that resolves to an array of `SlashCommand` objects.
   */
  async loadCommands(_signal) {
    if (!this.config || !this.config.isSkillsSupportEnabled()) {
      return [];
    }
    const skillManager = this.config.getSkillManager();
    if (!skillManager || !skillManager.isAdminEnabled()) {
      return [];
    }
    const skills = skillManager.getDisplayableSkills();
    return skills.map((skill) => {
      const commandName = skill.name.trim().replace(/\s+/g, "-");
      return {
        name: commandName,
        description: skill.description || `Activate the ${skill.name} skill`,
        kind: "skill" /* SKILL */,
        autoExecute: true,
        extensionName: skill.extensionName,
        action: async (_context, args) => ({
          type: "tool",
          toolName: ACTIVATE_SKILL_TOOL_NAME,
          toolArgs: { name: skill.name },
          postSubmitPrompt: args.trim().length > 0 ? args.trim() : void 0
        })
      };
    });
  }
};

// packages/cli/src/ui/components/LogoutConfirmationDialog.tsx
var import_jsx_runtime139 = __toESM(require_jsx_runtime(), 1);
var LogoutConfirmationDialog = ({ onSelect }) => {
  useKeypress(
    (key) => {
      if (key.name === "escape") {
        onSelect("exit" /* EXIT */);
        return true;
      }
      return false;
    },
    { isActive: true }
  );
  const options = [
    {
      label: "Sign in",
      value: "login" /* LOGIN */,
      key: "login"
    },
    {
      label: "Exit",
      value: "exit" /* EXIT */,
      key: "exit"
    }
  ];
  return /* @__PURE__ */ (0, import_jsx_runtime139.jsx)(Box_default, { flexDirection: "row", width: "100%", children: /* @__PURE__ */ (0, import_jsx_runtime139.jsxs)(
    Box_default,
    {
      flexDirection: "column",
      borderStyle: "round",
      borderColor: theme.ui.focus,
      padding: 1,
      flexGrow: 1,
      marginLeft: 1,
      marginRight: 1,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime139.jsxs)(Box_default, { flexDirection: "column", marginBottom: 1, children: [
          /* @__PURE__ */ (0, import_jsx_runtime139.jsx)(Text, { bold: true, color: theme.text.primary, children: "You are now signed out" }),
          /* @__PURE__ */ (0, import_jsx_runtime139.jsx)(Text, { color: theme.text.secondary, children: "Sign in again to continue using Gemini CLI, or exit the application." })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime139.jsx)(RadioButtonSelect, { items: options, onSelect, isFocused: true }),
        /* @__PURE__ */ (0, import_jsx_runtime139.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime139.jsx)(Text, { color: theme.text.secondary, children: "(Use Enter to select, Esc to close)" }) })
      ]
    }
  ) });
};

// packages/cli/src/ui/hooks/slashCommandProcessor.ts
var useSlashCommandProcessor = (config, settings, addItem, clearItems, loadHistory, refreshStatic, toggleVimEnabled, setIsProcessing, actions, extensionsUpdateState, isConfigInitialized, setBannerVisible, setCustomDialog) => {
  const session = useSessionStats();
  const [commands, setCommands] = (0, import_react104.useState)(
    void 0
  );
  const [reloadTrigger, setReloadTrigger] = (0, import_react104.useState)(0);
  const reloadCommands = (0, import_react104.useCallback)(() => {
    setReloadTrigger((v) => v + 1);
  }, []);
  const [confirmationRequest, setConfirmationRequest] = (0, import_react104.useState)(null);
  const [sessionShellAllowlist, setSessionShellAllowlist] = (0, import_react104.useState)(
    /* @__PURE__ */ new Set()
  );
  const gitService = (0, import_react104.useMemo)(() => {
    if (!config?.getProjectRoot()) {
      return;
    }
    return new GitService(config.getProjectRoot(), config.storage);
  }, [config]);
  const logger = (0, import_react104.useMemo)(() => {
    const l = new Logger(
      config?.getSessionId() || "",
      config?.storage ?? new Storage(process10.cwd())
    );
    return l;
  }, [config]);
  const [pendingItem, setPendingItem] = (0, import_react104.useState)(
    null
  );
  const pendingHistoryItems = (0, import_react104.useMemo)(() => {
    const items = [];
    if (pendingItem != null) {
      items.push(pendingItem);
    }
    return items;
  }, [pendingItem]);
  const addMessage = (0, import_react104.useCallback)(
    (message) => {
      let historyItemContent;
      if (message.type === "about" /* ABOUT */) {
        historyItemContent = {
          type: "about",
          cliVersion: message.cliVersion,
          osVersion: message.osVersion,
          sandboxEnv: message.sandboxEnv,
          modelVersion: message.modelVersion,
          selectedAuthType: message.selectedAuthType,
          gcpProject: message.gcpProject,
          ideClient: message.ideClient
        };
      } else if (message.type === "help" /* HELP */) {
        historyItemContent = {
          type: "help",
          timestamp: message.timestamp
        };
      } else if (message.type === "stats" /* STATS */) {
        historyItemContent = {
          type: "stats",
          duration: message.duration
        };
      } else if (message.type === "model_stats" /* MODEL_STATS */) {
        historyItemContent = {
          type: "model_stats"
        };
      } else if (message.type === "tool_stats" /* TOOL_STATS */) {
        historyItemContent = {
          type: "tool_stats"
        };
      } else if (message.type === "quit" /* QUIT */) {
        historyItemContent = {
          type: "quit",
          duration: message.duration
        };
      } else if (message.type === "compression" /* COMPRESSION */) {
        historyItemContent = {
          type: "compression",
          compression: message.compression
        };
      } else {
        historyItemContent = {
          type: message.type,
          text: message.content
        };
      }
      addItem(historyItemContent, message.timestamp.getTime());
    },
    [addItem]
  );
  const commandContext = (0, import_react104.useMemo)(
    () => ({
      services: {
        agentContext: config,
        settings,
        git: gitService,
        logger
      },
      ui: {
        addItem,
        clear: () => {
          clearItems();
          refreshStatic();
          setBannerVisible(false);
        },
        loadHistory: (history, postLoadInput) => {
          loadHistory(history);
          refreshStatic();
          if (postLoadInput !== void 0) {
            actions.setText(postLoadInput);
          }
        },
        setDebugMessage: actions.setDebugMessage,
        pendingItem,
        setPendingItem,
        toggleCorgiMode: actions.toggleCorgiMode,
        toggleDebugProfiler: actions.toggleDebugProfiler,
        toggleVimEnabled,
        reloadCommands,
        openAgentConfigDialog: actions.openAgentConfigDialog,
        extensionsUpdateState,
        dispatchExtensionStateUpdate: actions.dispatchExtensionStateUpdate,
        addConfirmUpdateExtensionRequest: actions.addConfirmUpdateExtensionRequest,
        setConfirmationRequest,
        removeComponent: () => setCustomDialog(null),
        toggleBackgroundTasks: actions.toggleBackgroundTasks,
        toggleShortcutsHelp: actions.toggleShortcutsHelp
      },
      session: {
        stats: session.stats,
        sessionShellAllowlist
      }
    }),
    [
      config,
      settings,
      gitService,
      logger,
      loadHistory,
      addItem,
      clearItems,
      refreshStatic,
      session.stats,
      actions,
      pendingItem,
      setPendingItem,
      setConfirmationRequest,
      toggleVimEnabled,
      sessionShellAllowlist,
      reloadCommands,
      extensionsUpdateState,
      setBannerVisible,
      setCustomDialog
    ]
  );
  (0, import_react104.useEffect)(() => {
    if (!config) {
      return;
    }
    const listener = () => {
      reloadCommands();
    };
    (async () => {
      const ideClient = await IdeClient.getInstance();
      ideClient.addStatusChangeListener(listener);
    })();
    addMCPStatusChangeListener(listener);
    const extensionEventListener = (_event) => {
      reloadCommands();
    };
    coreEvents.on("extensionsStarting", extensionEventListener);
    coreEvents.on("extensionsStopping", extensionEventListener);
    return () => {
      (async () => {
        const ideClient = await IdeClient.getInstance();
        ideClient.removeStatusChangeListener(listener);
      })();
      removeMCPStatusChangeListener(listener);
      coreEvents.off("extensionsStarting", extensionEventListener);
      coreEvents.off("extensionsStopping", extensionEventListener);
    };
  }, [config, reloadCommands]);
  (0, import_react104.useEffect)(() => {
    const controller = new AbortController();
    (async () => {
      const commandService = await CommandService.create(
        [
          new BuiltinCommandLoader(config),
          new SkillCommandLoader(config),
          new McpPromptLoader(config),
          new FileCommandLoader(config)
        ],
        controller.signal
      );
      if (controller.signal.aborted) {
        return;
      }
      setCommands(commandService.getCommands());
    })();
    return () => {
      controller.abort();
    };
  }, [config, reloadTrigger, isConfigInitialized]);
  const handleSlashCommand = (0, import_react104.useCallback)(
    async (rawQuery, oneTimeShellAllowlist, overwriteConfirmed, addToHistory = true) => {
      if (!commands) {
        return false;
      }
      if (typeof rawQuery !== "string") {
        return false;
      }
      const trimmed = rawQuery.trim();
      if (!trimmed.startsWith("/") && !trimmed.startsWith("?")) {
        return false;
      }
      const {
        commandToExecute,
        args,
        canonicalPath: resolvedCommandPath
      } = parseSlashCommand(trimmed, commands);
      if (!commandToExecute) {
        const isMcpLoading = config?.getMcpClientManager()?.getDiscoveryState() === MCPDiscoveryState.IN_PROGRESS;
        if (isMcpLoading) {
          setIsProcessing(true);
          if (addToHistory) {
            addItem({ type: "user" /* USER */, text: trimmed }, Date.now());
          }
          addMessage({
            type: "error" /* ERROR */,
            content: `Unknown command: ${trimmed}. Command might have been from an MCP server but MCP servers are not done loading.`,
            timestamp: /* @__PURE__ */ new Date()
          });
          setIsProcessing(false);
          return { type: "handled" };
        }
        return false;
      }
      setIsProcessing(true);
      if (addToHistory) {
        const userMessageTimestamp = Date.now();
        addItem(
          { type: "user" /* USER */, text: trimmed },
          userMessageTimestamp
        );
      }
      let hasError = false;
      const subcommand = resolvedCommandPath.length > 1 ? resolvedCommandPath.slice(1).join(" ") : void 0;
      try {
        if (commandToExecute) {
          if (commandToExecute.action) {
            const fullCommandContext = {
              ...commandContext,
              invocation: {
                raw: trimmed,
                name: commandToExecute.name,
                args
              },
              overwriteConfirmed
            };
            if (oneTimeShellAllowlist && oneTimeShellAllowlist.size > 0) {
              fullCommandContext.session = {
                ...fullCommandContext.session,
                sessionShellAllowlist: /* @__PURE__ */ new Set([
                  ...fullCommandContext.session.sessionShellAllowlist,
                  ...oneTimeShellAllowlist
                ])
              };
            }
            const result = await commandToExecute.action(
              fullCommandContext,
              args
            );
            if (result) {
              switch (result.type) {
                case "tool":
                  return {
                    type: "schedule_tool",
                    toolName: result.toolName,
                    toolArgs: result.toolArgs,
                    postSubmitPrompt: result.postSubmitPrompt
                  };
                case "message":
                  addItem(
                    {
                      type: result.messageType === "error" ? "error" /* ERROR */ : "info" /* INFO */,
                      text: result.content
                    },
                    Date.now()
                  );
                  return { type: "handled" };
                case "logout":
                  setCustomDialog(
                    (0, import_react104.createElement)(LogoutConfirmationDialog, {
                      onSelect: async (choice) => {
                        setCustomDialog(null);
                        if (choice === "login" /* LOGIN */) {
                          actions.openAuthDialog();
                        } else {
                          await runExitCleanup();
                          process10.exit(0);
                        }
                      }
                    })
                  );
                  return { type: "handled" };
                case "dialog":
                  switch (result.dialog) {
                    case "auth":
                      actions.openAuthDialog();
                      return { type: "handled" };
                    case "theme":
                      actions.openThemeDialog();
                      return { type: "handled" };
                    case "editor":
                      actions.openEditorDialog();
                      return { type: "handled" };
                    case "privacy":
                      actions.openPrivacyNotice();
                      return { type: "handled" };
                    case "sessionBrowser":
                      actions.openSessionBrowser();
                      return { type: "handled" };
                    case "settings":
                      actions.openSettingsDialog();
                      return { type: "handled" };
                    case "model":
                      actions.openModelDialog();
                      return { type: "handled" };
                    case "agentConfig": {
                      const props = result.props;
                      if (!props || // eslint-disable-next-line no-restricted-syntax
                      typeof props["name"] !== "string" || // eslint-disable-next-line no-restricted-syntax
                      typeof props["displayName"] !== "string" || !props["definition"]) {
                        throw new Error(
                          "Received invalid properties for agentConfig dialog action."
                        );
                      }
                      actions.openAgentConfigDialog(
                        props["name"],
                        props["displayName"],
                        // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
                        props["definition"]
                      );
                      return { type: "handled" };
                    }
                    case "permissions":
                      actions.openPermissionsDialog(
                        // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
                        result.props
                      );
                      return { type: "handled" };
                    case "help":
                      return { type: "handled" };
                    default: {
                      const unhandled = result.dialog;
                      throw new Error(
                        `Unhandled slash command result: ${unhandled}`
                      );
                    }
                  }
                case "load_history": {
                  config?.getGeminiClient()?.setHistory(result.clientHistory);
                  fullCommandContext.ui.clear();
                  result.history.forEach((item, index) => {
                    fullCommandContext.ui.addItem(item, index);
                  });
                  return { type: "handled" };
                }
                case "quit":
                  actions.quit(result.messages);
                  return { type: "handled" };
                case "submit_prompt":
                  return {
                    type: "submit_prompt",
                    content: result.content
                  };
                case "confirm_shell_commands": {
                  const callId = `expansion-${Date.now()}`;
                  const { outcome, approvedCommands } = await new Promise((resolve3) => {
                    const confirmationDetails = {
                      type: "exec",
                      title: `Confirm Shell Expansion`,
                      command: result.commandsToConfirm[0] || "",
                      rootCommand: result.commandsToConfirm[0] || "",
                      rootCommands: result.commandsToConfirm,
                      commands: result.commandsToConfirm,
                      onConfirm: async (resolvedOutcome) => {
                        resolve3({
                          outcome: resolvedOutcome,
                          approvedCommands: resolvedOutcome === ToolConfirmationOutcome.Cancel ? [] : result.commandsToConfirm
                        });
                      }
                    };
                    const toolDisplay = {
                      callId,
                      name: "Expansion",
                      description: "Command expansion needs shell access",
                      status: CoreToolCallStatus.AwaitingApproval,
                      isClientInitiated: true,
                      resultDisplay: void 0,
                      confirmationDetails
                    };
                    setPendingItem({
                      type: "tool_group",
                      tools: [toolDisplay]
                    });
                  });
                  setPendingItem(null);
                  if (outcome === ToolConfirmationOutcome.Cancel || !approvedCommands || approvedCommands.length === 0) {
                    addItem(
                      {
                        type: "info" /* INFO */,
                        text: "Slash command shell execution declined."
                      },
                      Date.now()
                    );
                    return { type: "handled" };
                  }
                  if (outcome === ToolConfirmationOutcome.ProceedAlways) {
                    setSessionShellAllowlist(
                      (prev) => /* @__PURE__ */ new Set([...prev, ...approvedCommands])
                    );
                  }
                  return await handleSlashCommand(
                    result.originalInvocation.raw,
                    // Pass the approved commands as a one-time grant for this execution.
                    new Set(approvedCommands),
                    void 0,
                    false
                    // Do not add to history again
                  );
                }
                case "confirm_action": {
                  const { confirmed } = await new Promise((resolve3) => {
                    setConfirmationRequest({
                      prompt: result.prompt,
                      onConfirm: (resolvedConfirmed) => {
                        setConfirmationRequest(null);
                        resolve3({ confirmed: resolvedConfirmed });
                      }
                    });
                  });
                  if (!confirmed) {
                    addItem(
                      {
                        type: "info" /* INFO */,
                        text: "Operation cancelled."
                      },
                      Date.now()
                    );
                    return { type: "handled" };
                  }
                  return await handleSlashCommand(
                    result.originalInvocation.raw,
                    void 0,
                    true
                  );
                }
                case "custom_dialog": {
                  setCustomDialog(result.component);
                  return { type: "handled" };
                }
                default: {
                  const unhandled = result;
                  throw new Error(
                    `Unhandled slash command result: ${unhandled}`
                  );
                }
              }
            }
            return { type: "handled" };
          } else if (commandToExecute.subCommands) {
            const helpText = `Command '/${commandToExecute.name}' requires a subcommand. Available:
${commandToExecute.subCommands.map((sc) => `  - ${sc.name}: ${sc.description || ""}`).join("\n")}`;
            addMessage({
              type: "info" /* INFO */,
              content: helpText,
              timestamp: /* @__PURE__ */ new Date()
            });
            return { type: "handled" };
          }
        }
        return { type: "handled" };
      } catch (e) {
        hasError = true;
        if (config) {
          const event = makeSlashCommandEvent({
            command: resolvedCommandPath[0],
            subcommand,
            status: SlashCommandStatus.ERROR,
            extension_id: commandToExecute?.extensionId
          });
          logSlashCommand(config, event);
        }
        addItem(
          {
            type: "error" /* ERROR */,
            text: e instanceof Error ? e.message : String(e)
          },
          Date.now()
        );
        return { type: "handled" };
      } finally {
        if (config && resolvedCommandPath[0] && !hasError) {
          const event = makeSlashCommandEvent({
            command: resolvedCommandPath[0],
            subcommand,
            status: SlashCommandStatus.SUCCESS,
            extension_id: commandToExecute?.extensionId
          });
          logSlashCommand(config, event);
        }
        setIsProcessing(false);
      }
    },
    [
      config,
      addItem,
      actions,
      commands,
      commandContext,
      addMessage,
      setSessionShellAllowlist,
      setIsProcessing,
      setConfirmationRequest,
      setCustomDialog
    ]
  );
  return {
    handleSlashCommand,
    slashCommands: commands,
    pendingHistoryItems,
    commandContext,
    confirmationRequest
  };
};

// packages/cli/src/ui/utils/ui-sizing.ts
var calculateMainAreaWidth = (terminalWidth, config) => {
  if (isAlternateBufferEnabled(config)) {
    return terminalWidth - 1;
  }
  return terminalWidth;
};

// packages/cli/node_modules/ansi-escapes/base.js
var base_exports = {};
__export(base_exports, {
  ConEmu: () => ConEmu,
  beep: () => beep,
  beginSynchronizedOutput: () => beginSynchronizedOutput,
  clearScreen: () => clearScreen,
  clearTerminal: () => clearTerminal,
  clearViewport: () => clearViewport,
  cursorBackward: () => cursorBackward,
  cursorDown: () => cursorDown,
  cursorForward: () => cursorForward,
  cursorGetPosition: () => cursorGetPosition,
  cursorHide: () => cursorHide,
  cursorLeft: () => cursorLeft,
  cursorMove: () => cursorMove,
  cursorNextLine: () => cursorNextLine,
  cursorPrevLine: () => cursorPrevLine,
  cursorRestorePosition: () => cursorRestorePosition,
  cursorSavePosition: () => cursorSavePosition,
  cursorShow: () => cursorShow,
  cursorTo: () => cursorTo,
  cursorUp: () => cursorUp,
  endSynchronizedOutput: () => endSynchronizedOutput,
  enterAlternativeScreen: () => enterAlternativeScreen,
  eraseDown: () => eraseDown,
  eraseEndLine: () => eraseEndLine,
  eraseLine: () => eraseLine,
  eraseLines: () => eraseLines,
  eraseScreen: () => eraseScreen,
  eraseStartLine: () => eraseStartLine,
  eraseUp: () => eraseUp,
  exitAlternativeScreen: () => exitAlternativeScreen,
  iTerm: () => iTerm,
  image: () => image,
  link: () => link,
  scrollDown: () => scrollDown,
  scrollUp: () => scrollUp,
  setCwd: () => setCwd,
  synchronizedOutput: () => synchronizedOutput
});
import process11 from "node:process";
import os3 from "node:os";
var ESC2 = "\x1B[";
var OSC = "\x1B]";
var BEL = "\x07";
var SEP = ";";
var isTerminalApp = !isBrowser && process11.env.TERM_PROGRAM === "Apple_Terminal";
var isWindows = !isBrowser && process11.platform === "win32";
var isTmux = !isBrowser && (process11.env.TERM?.startsWith("screen") || process11.env.TERM?.startsWith("tmux") || process11.env.TMUX !== void 0);
var cwdFunction = isBrowser ? () => {
  throw new Error("`process.cwd()` only works in Node.js, not the browser.");
} : process11.cwd;
var wrapOsc = (sequence) => {
  if (isTmux) {
    return "\x1BPtmux;" + sequence.replaceAll("\x1B", "\x1B\x1B") + "\x1B\\";
  }
  return sequence;
};
var cursorTo = (x, y) => {
  if (typeof x !== "number") {
    throw new TypeError("The `x` argument is required");
  }
  if (typeof y !== "number") {
    return ESC2 + (x + 1) + "G";
  }
  return ESC2 + (y + 1) + SEP + (x + 1) + "H";
};
var cursorMove = (x, y) => {
  if (typeof x !== "number") {
    throw new TypeError("The `x` argument is required");
  }
  let returnValue = "";
  if (x < 0) {
    returnValue += ESC2 + -x + "D";
  } else if (x > 0) {
    returnValue += ESC2 + x + "C";
  }
  if (y < 0) {
    returnValue += ESC2 + -y + "A";
  } else if (y > 0) {
    returnValue += ESC2 + y + "B";
  }
  return returnValue;
};
var cursorUp = (count = 1) => ESC2 + count + "A";
var cursorDown = (count = 1) => ESC2 + count + "B";
var cursorForward = (count = 1) => ESC2 + count + "C";
var cursorBackward = (count = 1) => ESC2 + count + "D";
var cursorLeft = ESC2 + "G";
var cursorSavePosition = isTerminalApp ? "\x1B7" : ESC2 + "s";
var cursorRestorePosition = isTerminalApp ? "\x1B8" : ESC2 + "u";
var cursorGetPosition = ESC2 + "6n";
var cursorNextLine = ESC2 + "E";
var cursorPrevLine = ESC2 + "F";
var cursorHide = ESC2 + "?25l";
var cursorShow = ESC2 + "?25h";
var eraseLines = (count) => {
  let clear = "";
  for (let i = 0; i < count; i++) {
    clear += eraseLine + (i < count - 1 ? cursorUp() : "");
  }
  if (count) {
    clear += cursorLeft;
  }
  return clear;
};
var eraseEndLine = ESC2 + "K";
var eraseStartLine = ESC2 + "1K";
var eraseLine = ESC2 + "2K";
var eraseDown = ESC2 + "J";
var eraseUp = ESC2 + "1J";
var eraseScreen = ESC2 + "2J";
var scrollUp = ESC2 + "S";
var scrollDown = ESC2 + "T";
var clearScreen = "\x1Bc";
var clearViewport = `${eraseScreen}${ESC2}H`;
var isOldWindows = () => {
  if (isBrowser || !isWindows) {
    return false;
  }
  const parts = os3.release().split(".");
  const major = Number(parts[0]);
  const build = Number(parts[2] ?? 0);
  if (major < 10) {
    return true;
  }
  if (major === 10 && build < 10586) {
    return true;
  }
  return false;
};
var clearTerminal = isOldWindows() ? `${eraseScreen}${ESC2}0f` : `${eraseScreen}${ESC2}3J${ESC2}H`;
var enterAlternativeScreen = ESC2 + "?1049h";
var exitAlternativeScreen = ESC2 + "?1049l";
var beginSynchronizedOutput = ESC2 + "?2026h";
var endSynchronizedOutput = ESC2 + "?2026l";
var synchronizedOutput = (text) => beginSynchronizedOutput + text + endSynchronizedOutput;
var beep = BEL;
var link = (text, url2) => {
  const openLink = wrapOsc(`${OSC}8${SEP}${SEP}${url2}${BEL}`);
  const closeLink = wrapOsc(`${OSC}8${SEP}${SEP}${BEL}`);
  return openLink + text + closeLink;
};
var image = (data, options = {}) => {
  let returnValue = `${OSC}1337;File=inline=1`;
  if (options.width) {
    returnValue += `;width=${options.width}`;
  }
  if (options.height) {
    returnValue += `;height=${options.height}`;
  }
  if (options.preserveAspectRatio === false) {
    returnValue += ";preserveAspectRatio=0";
  }
  const imageBuffer = Buffer.from(data);
  return wrapOsc(returnValue + `;size=${imageBuffer.byteLength}:` + imageBuffer.toString("base64") + BEL);
};
var iTerm = {
  setCwd: (cwd5 = cwdFunction()) => wrapOsc(`${OSC}50;CurrentDir=${cwd5}${BEL}`),
  annotation(message, options = {}) {
    let returnValue = `${OSC}1337;`;
    const hasX = options.x !== void 0;
    const hasY = options.y !== void 0;
    if ((hasX || hasY) && !(hasX && hasY && options.length !== void 0)) {
      throw new Error("`x`, `y` and `length` must be defined when `x` or `y` is defined");
    }
    message = message.replaceAll("|", "");
    returnValue += options.isHidden ? "AddHiddenAnnotation=" : "AddAnnotation=";
    if (options.length > 0) {
      returnValue += (hasX ? [message, options.length, options.x, options.y] : [options.length, message]).join("|");
    } else {
      returnValue += message;
    }
    return wrapOsc(returnValue + BEL);
  }
};
var ConEmu = {
  setCwd: (cwd5 = cwdFunction()) => wrapOsc(`${OSC}9;9;${cwd5}${BEL}`)
};
var setCwd = (cwd5 = cwdFunction()) => iTerm.setCwd(cwd5) + ConEmu.setCwd(cwd5);

// packages/cli/src/ui/AppContainer.tsx
import { basename as basename4 } from "node:path";

// packages/cli/src/utils/windowTitle.ts
function truncate(text, maxLen) {
  if (text.length <= maxLen) {
    return text;
  }
  return text.substring(0, maxLen - 1) + "\u2026";
}
function computeTerminalTitle({
  streamingState,
  thoughtSubject,
  isConfirming,
  isSilentWorking,
  folderName,
  showThoughts,
  useDynamicTitle
}) {
  const MAX_LEN = 80;
  let displayContext = process.env["CLI_TITLE"] || folderName;
  if (!useDynamicTitle) {
    const base = "Gemini CLI ";
    const maxContextLen = MAX_LEN - base.length - 2;
    displayContext = truncate(displayContext, maxContextLen);
    return `${base}(${displayContext})`.padEnd(MAX_LEN, " ");
  }
  const getSuffix = (context) => ` (${context})`;
  let title;
  if (isConfirming || streamingState === "waiting_for_confirmation" /* WaitingForConfirmation */) {
    const base = "\u270B  Action Required";
    const maxContextLen = MAX_LEN - base.length - 3;
    const context = truncate(displayContext, maxContextLen);
    title = `${base}${getSuffix(context)}`;
  } else if (isSilentWorking) {
    const base = "\u23F2  Working\u2026";
    const maxContextLen = MAX_LEN - base.length - 3;
    const context = truncate(displayContext, maxContextLen);
    title = `${base}${getSuffix(context)}`;
  } else if (streamingState === "idle" /* Idle */) {
    const base = "\u25C7  Ready";
    const maxContextLen = MAX_LEN - base.length - 3;
    const context = truncate(displayContext, maxContextLen);
    title = `${base}${getSuffix(context)}`;
  } else {
    const cleanSubject = showThoughts && thoughtSubject?.replace(/[\r\n]+/g, " ").trim();
    const suffix = getSuffix(displayContext);
    const suffixLen = suffix.length;
    const canFitThoughtWithSuffix = cleanSubject ? cleanSubject.length + suffixLen + 3 <= MAX_LEN : true;
    let activeSuffix = "";
    let maxStatusLen = MAX_LEN - 3;
    if (!cleanSubject || canFitThoughtWithSuffix) {
      activeSuffix = suffix;
      maxStatusLen -= activeSuffix.length;
    }
    const displayStatus = cleanSubject ? truncate(cleanSubject, maxStatusLen) : "Working\u2026";
    title = `\u2726  ${displayStatus}${activeSuffix}`;
  }
  const safeTitle = title.replace(/[\x00-\x1F\x7F]/g, "");
  return safeTitle.padEnd(MAX_LEN, " ").substring(0, MAX_LEN);
}

// packages/cli/src/ui/hooks/useLogger.ts
var import_react105 = __toESM(require_react(), 1);
var useLogger = (storage) => {
  const [logger, setLogger] = (0, import_react105.useState)(null);
  const config = (0, import_react105.useContext)(ConfigContext);
  (0, import_react105.useEffect)(() => {
    const activeSessionId = config?.getSessionId() ?? sessionId;
    const newLogger = new Logger(activeSessionId, storage);
    newLogger.initialize().then(() => {
      setLogger(newLogger);
    }).catch(() => {
    });
  }, [storage, config]);
  return logger;
};

// packages/cli/src/ui/hooks/useGeminiStream.ts
var import_react108 = __toESM(require_react(), 1);

// packages/cli/src/ui/utils/markdownUtilities.ts
var isIndexInsideCodeBlock = (content, indexToTest) => {
  let fenceCount = 0;
  let searchPos = 0;
  while (searchPos < content.length) {
    const nextFence = content.indexOf("```", searchPos);
    if (nextFence === -1 || nextFence >= indexToTest) {
      break;
    }
    fenceCount++;
    searchPos = nextFence + 3;
  }
  return fenceCount % 2 === 1;
};
var findEnclosingCodeBlockStart = (content, index) => {
  if (!isIndexInsideCodeBlock(content, index)) {
    return -1;
  }
  let currentSearchPos = 0;
  while (currentSearchPos < index) {
    const blockStartIndex = content.indexOf("```", currentSearchPos);
    if (blockStartIndex === -1 || blockStartIndex >= index) {
      break;
    }
    const blockEndIndex = content.indexOf("```", blockStartIndex + 3);
    if (blockStartIndex < index) {
      if (blockEndIndex === -1 || index < blockEndIndex + 3) {
        return blockStartIndex;
      }
    }
    if (blockEndIndex === -1) break;
    currentSearchPos = blockEndIndex + 3;
  }
  return -1;
};
var findLastSafeSplitPoint = (content) => {
  const enclosingBlockStart = findEnclosingCodeBlockStart(
    content,
    content.length
  );
  if (enclosingBlockStart !== -1) {
    return enclosingBlockStart;
  }
  let searchStartIndex = content.length;
  while (searchStartIndex >= 0) {
    const dnlIndex = content.lastIndexOf("\n\n", searchStartIndex);
    if (dnlIndex === -1) {
      break;
    }
    const potentialSplitPoint = dnlIndex + 2;
    if (!isIndexInsideCodeBlock(content, potentialSplitPoint)) {
      return potentialSplitPoint;
    }
    searchStartIndex = dnlIndex - 1;
  }
  return content.length;
};

// packages/cli/src/ui/hooks/useStateAndRef.ts
var import_react106 = __toESM(require_react(), 1);
var useStateAndRef = (initialValue) => {
  const [state, setState] = import_react106.default.useState(initialValue);
  const ref = import_react106.default.useRef(initialValue);
  const setStateInternal = import_react106.default.useCallback(
    (newStateOrCallback) => {
      let newValue;
      if (typeof newStateOrCallback === "function") {
        newValue = newStateOrCallback(ref.current);
      } else {
        newValue = newStateOrCallback;
      }
      setState(newValue);
      ref.current = newValue;
    },
    []
  );
  return [state, ref, setStateInternal];
};

// packages/cli/src/ui/hooks/toolMapping.ts
function hasSubagentHistory(call) {
  return "subagentHistory" in call && call.subagentHistory !== void 0;
}
function mapToDisplay(toolOrTools, options = {}) {
  const toolCalls = Array.isArray(toolOrTools) ? toolOrTools : [toolOrTools];
  const { borderTop, borderBottom, borderColor, borderDimColor } = options;
  const toolDisplays = toolCalls.map((call) => {
    let description;
    let renderOutputAsMarkdown = false;
    const displayName = call.tool?.displayName ?? call.request.name;
    if (call.status === CoreToolCallStatus.Error) {
      description = JSON.stringify(call.request.args);
    } else {
      description = call.invocation.getDescription();
      renderOutputAsMarkdown = call.tool.isOutputMarkdown;
    }
    const baseDisplayProperties = {
      callId: call.request.callId,
      parentCallId: call.request.parentCallId,
      name: displayName,
      args: call.request.args,
      description,
      renderOutputAsMarkdown
    };
    let resultDisplay = void 0;
    let confirmationDetails = void 0;
    let outputFile = void 0;
    let ptyId = void 0;
    let correlationId = void 0;
    let progressMessage = void 0;
    let progress = void 0;
    let progressTotal = void 0;
    switch (call.status) {
      case CoreToolCallStatus.Success:
        resultDisplay = call.response.resultDisplay;
        outputFile = call.response.outputFile;
        break;
      case CoreToolCallStatus.Error:
      case CoreToolCallStatus.Cancelled:
        resultDisplay = call.response.resultDisplay;
        break;
      case CoreToolCallStatus.AwaitingApproval:
        correlationId = call.correlationId;
        confirmationDetails = call.confirmationDetails;
        break;
      case CoreToolCallStatus.Executing:
        resultDisplay = call.liveOutput;
        ptyId = call.pid;
        progressMessage = call.progressMessage;
        progress = call.progress;
        progressTotal = call.progressTotal;
        break;
      case CoreToolCallStatus.Scheduled:
      case CoreToolCallStatus.Validating:
        break;
      default: {
        const exhaustiveCheck = call;
        debugLogger.warn(
          `Unhandled tool call status in mapper: ${exhaustiveCheck.status}`
        );
        break;
      }
    }
    return {
      ...baseDisplayProperties,
      status: call.status,
      isClientInitiated: !!call.request.isClientInitiated,
      kind: call.tool?.kind,
      resultDisplay,
      confirmationDetails,
      outputFile,
      ptyId,
      correlationId,
      progressMessage,
      progress,
      progressTotal,
      approvalMode: call.approvalMode,
      originalRequestName: call.request.originalRequestName,
      subagentHistory: hasSubagentHistory(call) ? call.subagentHistory : void 0
    };
  });
  return {
    type: "tool_group",
    tools: toolDisplays,
    borderTop,
    borderBottom,
    borderColor,
    borderDimColor
  };
}

// packages/cli/src/ui/hooks/useToolScheduler.ts
var import_react107 = __toESM(require_react(), 1);
function useToolScheduler(onComplete, config, getPreferredEditor) {
  const [toolCallsMap, setToolCallsMap] = (0, import_react107.useState)({});
  const [lastToolOutputTime, setLastToolOutputTime] = (0, import_react107.useState)(0);
  const [subagentHistoryMap, setSubagentHistoryMap] = (0, import_react107.useState)({});
  const messageBus = (0, import_react107.useMemo)(() => config.getMessageBus(), [config]);
  const onCompleteRef = (0, import_react107.useRef)(onComplete);
  (0, import_react107.useEffect)(() => {
    onCompleteRef.current = onComplete;
  }, [onComplete]);
  const getPreferredEditorRef = (0, import_react107.useRef)(getPreferredEditor);
  (0, import_react107.useEffect)(() => {
    getPreferredEditorRef.current = getPreferredEditor;
  }, [getPreferredEditor]);
  const scheduler = (0, import_react107.useMemo)(
    () => new Scheduler({
      context: config,
      messageBus,
      getPreferredEditor: () => getPreferredEditorRef.current(),
      schedulerId: ROOT_SCHEDULER_ID
    }),
    [config, messageBus]
  );
  (0, import_react107.useEffect)(() => () => scheduler.dispose(), [scheduler]);
  const internalAdaptToolCalls = (0, import_react107.useCallback)(
    (coreCalls, prevTracked) => adaptToolCalls(coreCalls, prevTracked),
    []
  );
  (0, import_react107.useEffect)(() => {
    const handler = (event) => {
      const isRoot = event.schedulerId === ROOT_SCHEDULER_ID;
      const hasExecuting = event.toolCalls.some(
        (tc) => tc.status === CoreToolCallStatus.Executing || (tc.status === CoreToolCallStatus.Success || tc.status === CoreToolCallStatus.Error) && "tailToolCallRequest" in tc && tc.tailToolCallRequest != null
      );
      if (hasExecuting) {
        setLastToolOutputTime(Date.now());
      }
      setToolCallsMap((prev) => {
        const prevCalls = prev[event.schedulerId] ?? [];
        const prevCallIds = new Set(prevCalls.map((tc) => tc.request.callId));
        const filteredToolCalls = isRoot ? event.toolCalls : event.toolCalls.filter(
          (tc) => tc.status === CoreToolCallStatus.AwaitingApproval || prevCallIds.has(tc.request.callId)
        );
        if (!isRoot && filteredToolCalls.length === 0 && prevCalls.length === 0) {
          return prev;
        }
        const adapted = internalAdaptToolCalls(filteredToolCalls, prevCalls);
        return {
          ...prev,
          [event.schedulerId]: adapted
        };
      });
    };
    messageBus.subscribe(MessageBusType.TOOL_CALLS_UPDATE, handler);
    return () => {
      messageBus.unsubscribe(MessageBusType.TOOL_CALLS_UPDATE, handler);
    };
  }, [messageBus, internalAdaptToolCalls]);
  (0, import_react107.useEffect)(() => {
    const handler = (event) => {
      setSubagentHistoryMap((prev) => {
        const history = prev[event.subagentName] ?? [];
        const index = history.findIndex(
          (item) => item.id === event.activity.id
        );
        const nextHistory = [...history];
        if (index >= 0) {
          nextHistory[index] = event.activity;
        } else {
          nextHistory.push(event.activity);
        }
        return {
          ...prev,
          [event.subagentName]: nextHistory
        };
      });
    };
    messageBus.subscribe(MessageBusType.SUBAGENT_ACTIVITY, handler);
    return () => {
      messageBus.unsubscribe(MessageBusType.SUBAGENT_ACTIVITY, handler);
    };
  }, [messageBus]);
  const schedule = (0, import_react107.useCallback)(
    async (request, signal) => {
      setToolCallsMap({});
      setSubagentHistoryMap({});
      const results = await scheduler.schedule(request, signal);
      await onCompleteRef.current(results);
      return results;
    },
    [scheduler]
  );
  const cancelAll = (0, import_react107.useCallback)(
    (_signal) => {
      scheduler.cancelAll();
    },
    [scheduler]
  );
  const markToolsAsSubmitted = (0, import_react107.useCallback)(
    (callIdsToMark) => {
      setToolCallsMap((prevMap) => {
        const nextMap = { ...prevMap };
        for (const [sid, calls] of Object.entries(nextMap)) {
          nextMap[sid] = calls.map(
            (tc) => callIdsToMark.includes(tc.request.callId) ? { ...tc, responseSubmittedToGemini: true } : tc
          );
        }
        return nextMap;
      });
    },
    []
  );
  const toolCalls = (0, import_react107.useMemo)(() => {
    const flattened = Object.values(toolCallsMap).flat();
    return flattened.map((tc) => {
      let subagentName = tc.request.name;
      if (tc.request.name === "invoke_subagent") {
        const argsObj = tc.request.args;
        let parsedArgs = argsObj;
        if (typeof argsObj === "string") {
          try {
            parsedArgs = JSON.parse(argsObj);
          } catch {
            parsedArgs = null;
          }
        }
        if (typeof parsedArgs === "object" && parsedArgs !== null) {
          for (const [key, value] of Object.entries(parsedArgs)) {
            if (key === "subagent_name" && typeof value === "string") {
              subagentName = value;
              break;
            }
          }
        }
      }
      return {
        ...tc,
        subagentHistory: subagentHistoryMap[subagentName] ?? tc.subagentHistory
      };
    });
  }, [toolCallsMap, subagentHistoryMap]);
  const setToolCallsForDisplay = (0, import_react107.useCallback)(
    (action) => {
      setToolCallsMap((prev) => {
        const currentFlattened = Object.values(prev).flat();
        const nextFlattened = typeof action === "function" ? action(currentFlattened) : action;
        if (nextFlattened.length === 0) {
          return {};
        }
        const nextMap = {};
        for (const call of nextFlattened) {
          const sid = call.schedulerId ?? ROOT_SCHEDULER_ID;
          if (!nextMap[sid]) {
            nextMap[sid] = [];
          }
          nextMap[sid].push(call);
        }
        return nextMap;
      });
    },
    []
  );
  return [
    toolCalls,
    schedule,
    markToolsAsSubmitted,
    setToolCallsForDisplay,
    cancelAll,
    lastToolOutputTime
  ];
}
function adaptToolCalls(coreCalls, prevTracked) {
  const prevMap = new Map(prevTracked.map((t) => [t.request.callId, t]));
  return coreCalls.map((coreCall) => {
    const prev = prevMap.get(coreCall.request.callId);
    const responseSubmittedToGemini = prev?.responseSubmittedToGemini ?? false;
    let status = coreCall.status;
    if ((status === CoreToolCallStatus.Success || status === CoreToolCallStatus.Error) && "tailToolCallRequest" in coreCall && coreCall.tailToolCallRequest != null) {
      status = CoreToolCallStatus.Executing;
    }
    return {
      ...coreCall,
      status,
      responseSubmittedToGemini
    };
  });
}

// packages/cli/src/ui/hooks/useGeminiStream.ts
import { promises as fs6 } from "node:fs";
import path13 from "node:path";
var isTopicTool2 = (name) => name === UPDATE_TOPIC_TOOL_NAME || name === UPDATE_TOPIC_DISPLAY_NAME;
var SUPPRESSED_TOOL_ERRORS_NOTE = 'Some internal tool attempts failed before this final error. Press F12 for diagnostics, or run /settings and change "Error Verbosity" to full for details.';
var LOW_VERBOSITY_FAILURE_NOTE = 'This request failed. Press F12 for diagnostics, or run /settings and change "Error Verbosity" to full for full details.';
function getBackgroundedToolInfo(toolCall) {
  const response = toolCall.response;
  const rawData = response?.data;
  if (!isBackgroundExecutionData(rawData)) {
    return void 0;
  }
  if (rawData.pid === void 0) {
    return void 0;
  }
  return {
    pid: rawData.pid,
    command: rawData.command ?? toolCall.request.name,
    initialOutput: rawData.initialOutput ?? ""
  };
}
function isBackgroundableExecutingToolCall(toolCall) {
  return toolCall.status === CoreToolCallStatus.Executing && typeof toolCall.pid === "number";
}
function showCitations(settings) {
  const enabled = settings.merged.ui.showCitations;
  if (enabled !== void 0) {
    return enabled;
  }
  return true;
}
function calculateStreamingState(isResponding, toolCalls) {
  if (toolCalls.some((tc) => tc.status === CoreToolCallStatus.AwaitingApproval)) {
    return "waiting_for_confirmation" /* WaitingForConfirmation */;
  }
  const isAnyToolActive = toolCalls.some((tc) => {
    if (tc.status === CoreToolCallStatus.Executing || tc.status === CoreToolCallStatus.Scheduled || tc.status === CoreToolCallStatus.Validating) {
      return true;
    }
    if (tc.status === CoreToolCallStatus.Success || tc.status === CoreToolCallStatus.Error || tc.status === CoreToolCallStatus.Cancelled) {
      return !tc.responseSubmittedToGemini;
    }
    return false;
  });
  if (isResponding || isAnyToolActive) {
    return "responding" /* Responding */;
  }
  return "idle" /* Idle */;
}
var useGeminiStream = (geminiClient, history, addItem, config, settings, onDebugMessage, handleSlashCommand, shellModeActive, getPreferredEditor, onAuthError, performMemoryRefresh, modelSwitchedFromQuotaError, setModelSwitchedFromQuotaError, onCancelSubmit, setShellInputFocused, terminalWidth, terminalHeight, isShellFocused, consumeUserHint) => {
  const [initError, setInitError] = (0, import_react108.useState)(null);
  const [retryStatus, setRetryStatus] = (0, import_react108.useState)(
    null
  );
  const isLowErrorVerbosity = settings.merged.ui?.errorVerbosity !== "full";
  const suppressedToolErrorCountRef = (0, import_react108.useRef)(0);
  const suppressedToolErrorNoteShownRef = (0, import_react108.useRef)(false);
  const lowVerbosityFailureNoteShownRef = (0, import_react108.useRef)(false);
  const abortControllerRef = (0, import_react108.useRef)(null);
  const turnCancelledRef = (0, import_react108.useRef)(false);
  const activeQueryIdRef = (0, import_react108.useRef)(null);
  const previousApprovalModeRef = (0, import_react108.useRef)(
    config.getApprovalMode()
  );
  const [isResponding, isRespondingRef, setIsResponding] = useStateAndRef(false);
  const [thought, thoughtRef, setThought] = useStateAndRef(null);
  const [pendingHistoryItem, pendingHistoryItemRef, setPendingHistoryItem] = useStateAndRef(null);
  const [lastGeminiActivityTime, setLastGeminiActivityTime] = (0, import_react108.useState)(0);
  const [pushedToolCallIds, pushedToolCallIdsRef, setPushedToolCallIds] = useStateAndRef(/* @__PURE__ */ new Set());
  const [_isFirstToolInGroup, isFirstToolInGroupRef, setIsFirstToolInGroup] = useStateAndRef(true);
  const processedMemoryToolsRef = (0, import_react108.useRef)(/* @__PURE__ */ new Set());
  const { startNewPrompt, getPromptCount } = useSessionStats();
  const storage = config.storage;
  const logger = useLogger(storage);
  const gitService = (0, import_react108.useMemo)(() => {
    if (!config.getProjectRoot()) {
      return;
    }
    return new GitService(config.getProjectRoot(), storage);
  }, [config, storage]);
  (0, import_react108.useEffect)(() => {
    const handleRetryAttempt = (payload) => {
      if (turnCancelledRef.current || !isRespondingRef.current) {
        return;
      }
      setRetryStatus(payload);
    };
    coreEvents.on(CoreEvent.RetryAttempt, handleRetryAttempt);
    return () => {
      coreEvents.off(CoreEvent.RetryAttempt, handleRetryAttempt);
    };
  }, [isRespondingRef]);
  const [
    toolCalls,
    scheduleToolCalls,
    markToolsAsSubmitted,
    setToolCallsForDisplay,
    cancelAllToolCalls,
    lastToolOutputTime
  ] = useToolScheduler(
    async (completedToolCallsFromScheduler) => {
      if (completedToolCallsFromScheduler.length > 0) {
        const toolsToPush = completedToolCallsFromScheduler.filter(
          (tc) => !pushedToolCallIdsRef.current.has(tc.request.callId)
        );
        if (toolsToPush.length > 0) {
          const isCompactModeEnabled = settings.merged.ui?.compactToolOutput === true;
          const firstToolToPush = toolsToPush[0];
          const tcIndex = toolCalls.indexOf(firstToolToPush);
          const prevTool = tcIndex > 0 ? toolCalls[tcIndex - 1] : null;
          let borderTop = isFirstToolInGroupRef.current;
          if (!borderTop && prevTool) {
            const currentIsCompact = isCompactTool(
              mapToDisplay(firstToolToPush).tools[0],
              isCompactModeEnabled
            );
            const prevWasCompact = isCompactTool(
              mapToDisplay(prevTool).tools[0],
              isCompactModeEnabled
            );
            if (!currentIsCompact && prevWasCompact) {
              borderTop = true;
            }
          }
          addItem(
            mapToDisplay(toolsToPush, {
              borderTop,
              borderBottom: true,
              borderColor: theme.border.default,
              borderDimColor: false
            })
          );
        }
        setToolCallsForDisplay([]);
        try {
          const currentModel = config.getGeminiClient().getCurrentSequenceModel() ?? config.getModel();
          config.getGeminiClient().getChat().recordCompletedToolCalls(
            currentModel,
            completedToolCallsFromScheduler
          );
          await recordToolCallInteractions(
            config,
            completedToolCallsFromScheduler
          );
        } catch (error) {
          debugLogger.warn(
            `Error recording completed tool call information: ${error}`
          );
        }
        await handleCompletedTools(completedToolCallsFromScheduler);
      }
    },
    config,
    getPreferredEditor
  );
  const activeBackgroundExecutionId = (0, import_react108.useMemo)(() => {
    const executingBackgroundableTool = toolCalls.find(
      isBackgroundableExecutingToolCall
    );
    return executingBackgroundableTool?.pid;
  }, [toolCalls]);
  const onExec = (0, import_react108.useCallback)(
    async (done) => {
      setIsResponding(true);
      await done;
      setIsResponding(false);
    },
    [setIsResponding]
  );
  const {
    handleShellCommand,
    activeShellPtyId,
    lastShellOutputTime,
    backgroundTaskCount,
    isBackgroundTaskVisible,
    toggleBackgroundTasks,
    backgroundCurrentExecution,
    registerBackgroundTask,
    dismissBackgroundTask,
    backgroundTasks
  } = useExecutionLifecycle(
    addItem,
    setPendingHistoryItem,
    onExec,
    onDebugMessage,
    config,
    geminiClient,
    setShellInputFocused,
    terminalWidth,
    terminalHeight,
    activeBackgroundExecutionId
  );
  const streamingState = (0, import_react108.useMemo)(
    () => calculateStreamingState(isResponding, toolCalls),
    [isResponding, toolCalls]
  );
  (0, import_react108.useEffect)(() => {
    if (toolCalls.length > 0) {
      const isNewBatch = !toolCalls.some(
        (tc) => pushedToolCallIdsRef.current.has(tc.request.callId)
      );
      if (isNewBatch) {
        setPushedToolCallIds(/* @__PURE__ */ new Set());
        setIsFirstToolInGroup(true);
      }
    } else if (streamingState === "idle" /* Idle */) {
      setPushedToolCallIds(/* @__PURE__ */ new Set());
      setIsFirstToolInGroup(true);
    }
  }, [
    toolCalls,
    pushedToolCallIdsRef,
    setPushedToolCallIds,
    setIsFirstToolInGroup,
    streamingState
  ]);
  (0, import_react108.useEffect)(() => {
    const toolsToPush = [];
    for (let i = 0; i < toolCalls.length; i++) {
      const tc = toolCalls[i];
      if (pushedToolCallIdsRef.current.has(tc.request.callId)) continue;
      if (tc.status === "success" || tc.status === "error" || tc.status === "cancelled") {
        const isAgent = tc.tool?.kind === Kind.Agent;
        if (isAgent) {
          let contigAgentsComplete = true;
          for (let j = i + 1; j < toolCalls.length; j++) {
            const nextTc = toolCalls[j];
            if (nextTc.tool?.kind === Kind.Agent) {
              if (nextTc.status !== "success" && nextTc.status !== "error" && nextTc.status !== "cancelled") {
                contigAgentsComplete = false;
                break;
              }
            } else {
              break;
            }
          }
          if (!contigAgentsComplete) {
            break;
          }
        }
        toolsToPush.push(tc);
      } else {
        break;
      }
    }
    if (toolsToPush.length > 0) {
      const newPushed = new Set(pushedToolCallIdsRef.current);
      const isFirstInThisPush = isFirstToolInGroupRef.current;
      const isCompactModeEnabled = settings.merged.ui?.compactToolOutput === true;
      const groups = [];
      let currentGroup = [];
      for (const tc of toolsToPush) {
        newPushed.add(tc.request.callId);
        if (tc.tool?.kind === Kind.Agent) {
          currentGroup.push(tc);
        } else {
          if (currentGroup.length > 0) {
            groups.push(currentGroup);
            currentGroup = [];
          }
          groups.push([tc]);
        }
      }
      if (currentGroup.length > 0) {
        groups.push(currentGroup);
      }
      for (let i = 0; i < groups.length; i++) {
        const group = groups[i];
        const isFirstInBatch = i === 0 && isFirstInThisPush;
        const lastTcInGroup = group[group.length - 1];
        const tcIndexInBatch = toolCalls.indexOf(lastTcInGroup);
        const isLastInBatch = tcIndexInBatch === toolCalls.length - 1;
        const nextTcInBatch = tcIndexInBatch < toolCalls.length - 1 ? toolCalls[tcIndexInBatch + 1] : null;
        const prevTcInBatch = toolCalls.indexOf(group[0]) > 0 ? toolCalls[toolCalls.indexOf(group[0]) - 1] : null;
        const historyItem = mapToDisplay(group, {
          ...getToolGroupBorderAppearance(
            { type: "tool_group", tools: toolCalls },
            activeShellPtyId,
            !!isShellFocused,
            [],
            backgroundTasks
          )
        });
        const currentIsCompact = historyItem.tools.length === 1 && isCompactTool(historyItem.tools[0], isCompactModeEnabled);
        let nextIsCompact = false;
        if (nextTcInBatch) {
          const nextHistoryItem = mapToDisplay(nextTcInBatch);
          nextIsCompact = nextHistoryItem.tools.length === 1 && isCompactTool(nextHistoryItem.tools[0], isCompactModeEnabled);
        }
        let prevWasCompact = false;
        if (prevTcInBatch) {
          const prevHistoryItem = mapToDisplay(prevTcInBatch);
          prevWasCompact = prevHistoryItem.tools.length === 1 && isCompactTool(prevHistoryItem.tools[0], isCompactModeEnabled);
        }
        historyItem.borderTop = isFirstInBatch || !currentIsCompact && prevWasCompact;
        historyItem.borderBottom = currentIsCompact ? isLastInBatch && !nextIsCompact : isLastInBatch || nextIsCompact;
        addItem(historyItem);
      }
      setPushedToolCallIds(newPushed);
      if (isFirstToolInGroupRef.current && toolsToPush.every((tc) => isTopicTool2(tc.request.name))) {
      } else {
        setIsFirstToolInGroup(false);
      }
    }
  }, [
    toolCalls,
    pushedToolCallIdsRef,
    isFirstToolInGroupRef,
    setPushedToolCallIds,
    setIsFirstToolInGroup,
    addItem,
    activeShellPtyId,
    isShellFocused,
    backgroundTasks,
    settings.merged.ui?.compactToolOutput
  ]);
  const pendingToolGroupItems = (0, import_react108.useMemo)(() => {
    const remainingTools = toolCalls.filter(
      (tc) => !pushedToolCallIds.has(tc.request.callId)
    );
    const items = [];
    const appearance = getToolGroupBorderAppearance(
      { type: "tool_group", tools: toolCalls },
      activeShellPtyId,
      !!isShellFocused,
      [],
      backgroundTasks
    );
    if (remainingTools.length > 0) {
      let needsTopBorder = pushedToolCallIds.size === 0;
      if (!needsTopBorder) {
        const allPushedWereTopics = toolCalls.filter((tc) => pushedToolCallIds.has(tc.request.callId)).every((tc) => isTopicTool2(tc.request.name));
        if (allPushedWereTopics) {
          needsTopBorder = true;
        }
      }
      items.push(
        mapToDisplay(remainingTools, {
          borderTop: needsTopBorder,
          borderBottom: false,
          // Stay open to connect with the slice below
          ...appearance
        })
      );
    }
    const allTerminal = toolCalls.length > 0 && toolCalls.every(
      (tc) => tc.status === "success" || tc.status === "error" || tc.status === "cancelled"
    );
    const allPushed = toolCalls.length > 0 && toolCalls.every((tc) => pushedToolCallIds.has(tc.request.callId));
    const isToolVisible = (tc) => {
      const displayName = tc.tool?.displayName ?? tc.request.name;
      let hasResultDisplay = false;
      if (tc.status === CoreToolCallStatus.Success || tc.status === CoreToolCallStatus.Error || tc.status === CoreToolCallStatus.Cancelled) {
        hasResultDisplay = !!tc.response?.resultDisplay;
      } else if (tc.status === CoreToolCallStatus.Executing) {
        hasResultDisplay = !!tc.liveOutput;
      }
      if (shouldHideToolCall({
        displayName,
        status: tc.status,
        approvalMode: tc.approvalMode,
        hasResultDisplay,
        parentCallId: tc.request.parentCallId
      })) {
        return false;
      }
      const displayStatus = mapCoreStatusToDisplayStatus(tc.status);
      if (displayStatus === "Confirming" /* Confirming */) {
        return false;
      }
      return true;
    };
    let lastVisibleIsCompact = false;
    const isCompactModeEnabled = settings.merged.ui?.compactToolOutput === true;
    for (let i = toolCalls.length - 1; i >= 0; i--) {
      if (isToolVisible(toolCalls[i])) {
        const mapped = mapToDisplay(toolCalls[i]);
        lastVisibleIsCompact = mapped.tools[0] ? isCompactTool(mapped.tools[0], isCompactModeEnabled) : false;
        break;
      }
    }
    if (toolCalls.length > 0 && !(allTerminal && allPushed) && toolCalls.some(isToolVisible) && !lastVisibleIsCompact) {
      items.push({
        type: "tool_group",
        tools: [],
        borderTop: false,
        borderBottom: true,
        ...appearance
      });
    }
    return items;
  }, [
    toolCalls,
    pushedToolCallIds,
    activeShellPtyId,
    isShellFocused,
    backgroundTasks,
    settings.merged.ui?.compactToolOutput
  ]);
  const lastQueryRef = (0, import_react108.useRef)(null);
  const lastPromptIdRef = (0, import_react108.useRef)(null);
  const loopDetectedRef = (0, import_react108.useRef)(false);
  const [
    loopDetectionConfirmationRequest,
    setLoopDetectionConfirmationRequest
  ] = (0, import_react108.useState)(null);
  const activePtyId = activeShellPtyId ?? activeBackgroundExecutionId ?? void 0;
  const prevActiveShellPtyIdRef = (0, import_react108.useRef)(null);
  (0, import_react108.useEffect)(() => {
    if (turnCancelledRef.current && prevActiveShellPtyIdRef.current !== null && activeShellPtyId === null) {
      addItem({ type: "info" /* INFO */, text: "Request cancelled." });
      setIsResponding(false);
    }
    prevActiveShellPtyIdRef.current = activeShellPtyId;
  }, [activeShellPtyId, addItem, setIsResponding]);
  (0, import_react108.useEffect)(() => {
    if (config.getApprovalMode() === ApprovalMode.YOLO && streamingState === "idle" /* Idle */) {
      const lastUserMessageIndex = history.findLastIndex(
        (item) => item.type === "user" /* USER */
      );
      const turnCount = lastUserMessageIndex === -1 ? 0 : history.length - lastUserMessageIndex;
      if (turnCount > 0) {
        logConversationFinishedEvent(
          config,
          new ConversationFinishedEvent(config.getApprovalMode(), turnCount)
        );
      }
    }
  }, [streamingState, config, history]);
  (0, import_react108.useEffect)(() => {
    if (!isResponding) {
      setRetryStatus(null);
    }
  }, [isResponding]);
  const maybeAddSuppressedToolErrorNote = (0, import_react108.useCallback)(
    (userMessageTimestamp) => {
      if (!isLowErrorVerbosity) {
        return;
      }
      if (suppressedToolErrorCountRef.current === 0) {
        return;
      }
      if (suppressedToolErrorNoteShownRef.current) {
        return;
      }
      addItem(
        {
          type: "info" /* INFO */,
          text: SUPPRESSED_TOOL_ERRORS_NOTE
        },
        userMessageTimestamp
      );
      suppressedToolErrorNoteShownRef.current = true;
    },
    [addItem, isLowErrorVerbosity]
  );
  const maybeAddLowVerbosityFailureNote = (0, import_react108.useCallback)(
    (userMessageTimestamp) => {
      if (!isLowErrorVerbosity || config.getDebugMode()) {
        return;
      }
      if (lowVerbosityFailureNoteShownRef.current || suppressedToolErrorNoteShownRef.current) {
        return;
      }
      addItem(
        {
          type: "info" /* INFO */,
          text: LOW_VERBOSITY_FAILURE_NOTE
        },
        userMessageTimestamp
      );
      lowVerbosityFailureNoteShownRef.current = true;
    },
    [addItem, config, isLowErrorVerbosity]
  );
  const cancelOngoingRequest = (0, import_react108.useCallback)(() => {
    if (streamingState !== "responding" /* Responding */ && streamingState !== "waiting_for_confirmation" /* WaitingForConfirmation */) {
      return;
    }
    if (turnCancelledRef.current) {
      return;
    }
    turnCancelledRef.current = true;
    setRetryStatus(null);
    const isFullCancellation = !toolCalls.some(
      (tc) => tc.status === "success" || tc.status === "error"
    );
    if (!abortControllerRef.current) {
      abortControllerRef.current = new AbortController();
    }
    abortControllerRef.current.abort();
    cancelAllToolCalls(abortControllerRef.current.signal);
    if (pendingHistoryItemRef.current) {
      const isShellCommand = pendingHistoryItemRef.current.type === "tool_group" && pendingHistoryItemRef.current.tools.some(
        (t) => t.name === SHELL_COMMAND_NAME
      );
      if (isShellCommand) {
        const toolGroup = pendingHistoryItemRef.current;
        const updatedTools = toolGroup.tools.map((tool) => {
          if (tool.name === SHELL_COMMAND_NAME) {
            return {
              ...tool,
              status: CoreToolCallStatus.Cancelled,
              resultDisplay: tool.resultDisplay
            };
          }
          return tool;
        });
        addItem({ ...toolGroup, tools: updatedTools });
      } else {
        addItem(pendingHistoryItemRef.current);
      }
    }
    setPendingHistoryItem(null);
    if (isFullCancellation) {
      if (!activeShellPtyId) {
        addItem({
          type: "info" /* INFO */,
          text: "Request cancelled."
        });
        setIsResponding(false);
      }
    }
    onCancelSubmit(false);
    setShellInputFocused(false);
  }, [
    streamingState,
    addItem,
    setPendingHistoryItem,
    onCancelSubmit,
    pendingHistoryItemRef,
    setShellInputFocused,
    cancelAllToolCalls,
    toolCalls,
    activeShellPtyId,
    setIsResponding
  ]);
  useKeypress(
    (key) => {
      if (key.name === "escape" && !isShellFocused) {
        cancelOngoingRequest();
      }
    },
    {
      isActive: streamingState === "responding" /* Responding */ || streamingState === "waiting_for_confirmation" /* WaitingForConfirmation */
    }
  );
  const prepareQueryForGemini = (0, import_react108.useCallback)(
    async (query, userMessageTimestamp, abortSignal, prompt_id) => {
      if (turnCancelledRef.current) {
        return { queryToSend: null, shouldProceed: false };
      }
      if (typeof query === "string" && query.trim().length === 0) {
        return { queryToSend: null, shouldProceed: false };
      }
      let localQueryToSendToGemini = null;
      if (typeof query === "string") {
        const trimmedQuery = query.trim();
        await logger?.logMessage(MessageSenderType.USER, trimmedQuery);
        if (!shellModeActive) {
          const slashCommandResult = isSlashCommand(trimmedQuery) ? await handleSlashCommand(trimmedQuery) : false;
          if (slashCommandResult) {
            switch (slashCommandResult.type) {
              case "schedule_tool": {
                const { toolName, toolArgs, postSubmitPrompt } = slashCommandResult;
                const toolCallRequest = {
                  callId: `${toolName}-${Date.now()}-${Math.random().toString(16).slice(2)}`,
                  name: toolName,
                  args: toolArgs,
                  isClientInitiated: true,
                  prompt_id
                };
                await scheduleToolCalls([toolCallRequest], abortSignal);
                if (postSubmitPrompt) {
                  localQueryToSendToGemini = postSubmitPrompt;
                  return {
                    queryToSend: localQueryToSendToGemini,
                    shouldProceed: true
                  };
                }
                return { queryToSend: null, shouldProceed: false };
              }
              case "submit_prompt": {
                localQueryToSendToGemini = slashCommandResult.content;
                return {
                  queryToSend: localQueryToSendToGemini,
                  shouldProceed: true
                };
              }
              case "handled": {
                return { queryToSend: null, shouldProceed: false };
              }
              default: {
                const unreachable = slashCommandResult;
                throw new Error(
                  `Unhandled slash command result type: ${unreachable}`
                );
              }
            }
          }
        }
        if (shellModeActive && handleShellCommand(trimmedQuery, abortSignal)) {
          return { queryToSend: null, shouldProceed: false };
        }
        if (isAtCommand(trimmedQuery)) {
          addItem(
            { type: "user" /* USER */, text: trimmedQuery },
            userMessageTimestamp
          );
          const atCommandResult = await handleAtCommand({
            query: trimmedQuery,
            config,
            addItem,
            onDebugMessage,
            messageId: userMessageTimestamp,
            signal: abortSignal,
            escapePastedAtSymbols: settings.merged.ui?.escapePastedAtSymbols
          });
          if (atCommandResult.error) {
            onDebugMessage(atCommandResult.error);
            return { queryToSend: null, shouldProceed: false };
          }
          localQueryToSendToGemini = atCommandResult.processedQuery;
        } else {
          addItem(
            { type: "user" /* USER */, text: trimmedQuery },
            userMessageTimestamp
          );
          localQueryToSendToGemini = trimmedQuery;
        }
      } else {
        localQueryToSendToGemini = query;
      }
      if (localQueryToSendToGemini === null) {
        onDebugMessage(
          "Query processing resulted in null, not sending to Gemini."
        );
        return { queryToSend: null, shouldProceed: false };
      }
      return { queryToSend: localQueryToSendToGemini, shouldProceed: true };
    },
    [
      config,
      addItem,
      onDebugMessage,
      handleShellCommand,
      handleSlashCommand,
      logger,
      shellModeActive,
      scheduleToolCalls,
      settings
    ]
  );
  const handleContentEvent = (0, import_react108.useCallback)(
    (eventValue, currentGeminiMessageBuffer, userMessageTimestamp) => {
      setRetryStatus(null);
      if (turnCancelledRef.current) {
        return "";
      }
      let newGeminiMessageBuffer = currentGeminiMessageBuffer + eventValue;
      if (pendingHistoryItemRef.current?.type !== "gemini" && pendingHistoryItemRef.current?.type !== "gemini_content") {
        if (pendingHistoryItemRef.current) {
          addItem(pendingHistoryItemRef.current, userMessageTimestamp);
        }
        setPendingHistoryItem({ type: "gemini", text: "" });
        newGeminiMessageBuffer = eventValue;
      }
      const splitPoint = findLastSafeSplitPoint(newGeminiMessageBuffer);
      if (splitPoint === newGeminiMessageBuffer.length) {
        setPendingHistoryItem((item) => ({
          // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
          type: item?.type,
          text: newGeminiMessageBuffer
        }));
      } else {
        const beforeText = newGeminiMessageBuffer.substring(0, splitPoint);
        const afterText = newGeminiMessageBuffer.substring(splitPoint);
        if (beforeText.length > 0) {
          addItem(
            {
              // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
              type: pendingHistoryItemRef.current?.type,
              text: beforeText
            },
            userMessageTimestamp
          );
        }
        setPendingHistoryItem({ type: "gemini_content", text: afterText });
        newGeminiMessageBuffer = afterText;
      }
      return newGeminiMessageBuffer;
    },
    [addItem, pendingHistoryItemRef, setPendingHistoryItem]
  );
  const handleThoughtEvent = (0, import_react108.useCallback)(
    (eventValue, _userMessageTimestamp) => {
      setThought(eventValue);
      if (getInlineThinkingMode(settings) === "full") {
        addItem({
          type: "thinking",
          thought: eventValue
        });
      }
    },
    [addItem, settings, setThought]
  );
  const handleUserCancelledEvent = (0, import_react108.useCallback)(
    (userMessageTimestamp) => {
      if (turnCancelledRef.current) {
        return;
      }
      if (pendingHistoryItemRef.current) {
        if (pendingHistoryItemRef.current.type === "tool_group") {
          const updatedTools = pendingHistoryItemRef.current.tools.map(
            (tool) => tool.status === CoreToolCallStatus.Validating || tool.status === CoreToolCallStatus.Scheduled || tool.status === CoreToolCallStatus.AwaitingApproval || tool.status === CoreToolCallStatus.Executing ? { ...tool, status: CoreToolCallStatus.Cancelled } : tool
          );
          const pendingItem = {
            ...pendingHistoryItemRef.current,
            tools: updatedTools
          };
          addItem(pendingItem, userMessageTimestamp);
        } else {
          addItem(pendingHistoryItemRef.current, userMessageTimestamp);
        }
        setPendingHistoryItem(null);
      }
      addItem(
        { type: "info" /* INFO */, text: "User cancelled the request." },
        userMessageTimestamp
      );
      setIsResponding(false);
      setThought(null);
    },
    [
      addItem,
      pendingHistoryItemRef,
      setPendingHistoryItem,
      setThought,
      setIsResponding
    ]
  );
  const handleErrorEvent = (0, import_react108.useCallback)(
    (eventValue, userMessageTimestamp) => {
      if (pendingHistoryItemRef.current) {
        addItem(pendingHistoryItemRef.current, userMessageTimestamp);
        setPendingHistoryItem(null);
      }
      maybeAddSuppressedToolErrorNote(userMessageTimestamp);
      addItem(
        {
          type: "error" /* ERROR */,
          text: parseAndFormatApiError(
            eventValue.error,
            config.getContentGeneratorConfig()?.authType,
            void 0,
            config.getModel(),
            DEFAULT_GEMINI_FLASH_MODEL
          )
        },
        userMessageTimestamp
      );
      maybeAddLowVerbosityFailureNote(userMessageTimestamp);
      setThought(null);
    },
    [
      addItem,
      pendingHistoryItemRef,
      setPendingHistoryItem,
      config,
      setThought,
      maybeAddSuppressedToolErrorNote,
      maybeAddLowVerbosityFailureNote
    ]
  );
  const handleCitationEvent = (0, import_react108.useCallback)(
    (text, userMessageTimestamp) => {
      if (!showCitations(settings)) {
        return;
      }
      if (pendingHistoryItemRef.current) {
        addItem(pendingHistoryItemRef.current, userMessageTimestamp);
        setPendingHistoryItem(null);
      }
      addItem({ type: "info" /* INFO */, text }, userMessageTimestamp);
    },
    [addItem, pendingHistoryItemRef, setPendingHistoryItem, settings]
  );
  const handleFinishedEvent = (0, import_react108.useCallback)(
    (event, userMessageTimestamp) => {
      const finishReason = event.value.reason;
      if (!finishReason) {
        return;
      }
      const finishReasonMessages = {
        [FinishReason.FINISH_REASON_UNSPECIFIED]: void 0,
        [FinishReason.STOP]: void 0,
        [FinishReason.MAX_TOKENS]: "Response truncated due to token limits.",
        [FinishReason.SAFETY]: "Response stopped due to safety reasons.",
        [FinishReason.RECITATION]: "Response stopped due to recitation policy.",
        [FinishReason.LANGUAGE]: "Response stopped due to unsupported language.",
        [FinishReason.BLOCKLIST]: "Response stopped due to forbidden terms.",
        [FinishReason.PROHIBITED_CONTENT]: "Response stopped due to prohibited content.",
        [FinishReason.SPII]: "Response stopped due to sensitive personally identifiable information.",
        [FinishReason.OTHER]: "Response stopped for other reasons.",
        [FinishReason.MALFORMED_FUNCTION_CALL]: "Response stopped due to malformed function call.",
        [FinishReason.IMAGE_SAFETY]: "Response stopped due to image safety violations.",
        [FinishReason.UNEXPECTED_TOOL_CALL]: "Response stopped due to unexpected tool call.",
        [FinishReason.IMAGE_PROHIBITED_CONTENT]: "Response stopped due to prohibited image content.",
        [FinishReason.NO_IMAGE]: "Response stopped because no image was generated."
      };
      const message = finishReasonMessages[finishReason];
      if (message) {
        addItem(
          {
            type: "info",
            text: `\u26A0\uFE0F  ${message}`
          },
          userMessageTimestamp
        );
      }
    },
    [addItem]
  );
  const handleChatCompressionEvent = (0, import_react108.useCallback)(
    (eventValue, userMessageTimestamp) => {
      if (pendingHistoryItemRef.current) {
        addItem(pendingHistoryItemRef.current, userMessageTimestamp);
        setPendingHistoryItem(null);
      }
      const limit = tokenLimit(config.getModel());
      const originalPercentage = Math.round(
        (eventValue?.originalTokenCount ?? 0) / limit * 100
      );
      const newPercentage = Math.round(
        (eventValue?.newTokenCount ?? 0) / limit * 100
      );
      addItem(
        {
          type: "info" /* INFO */,
          text: `Context compressed from ${originalPercentage}% to ${newPercentage}%.`,
          secondaryText: `Change threshold in /settings.`,
          color: theme.status.warning,
          marginBottom: 1
        },
        userMessageTimestamp
      );
    },
    [addItem, pendingHistoryItemRef, setPendingHistoryItem, config]
  );
  const handleMaxSessionTurnsEvent = (0, import_react108.useCallback)(
    () => addItem({
      type: "info",
      text: `The session has reached the maximum number of turns: ${config.getMaxSessionTurns()}. Please update this limit in your setting.json file.`
    }),
    [addItem, config]
  );
  const handleContextWindowWillOverflowEvent = (0, import_react108.useCallback)(
    (estimatedRequestTokenCount, remainingTokenCount) => {
      onCancelSubmit(true);
      const limit = tokenLimit(config.getModel());
      const isMoreThan25PercentUsed = limit > 0 && remainingTokenCount < limit * 0.75;
      let text = `Sending this message (${estimatedRequestTokenCount} tokens) might exceed the context window limit (${remainingTokenCount.toLocaleString()} tokens left).`;
      if (isMoreThan25PercentUsed) {
        text += " Please try reducing the size of your message or use the `/compress` command to compress the chat history.";
      }
      addItem({
        type: "info",
        text
      });
    },
    [addItem, onCancelSubmit, config]
  );
  const handleChatModelEvent = (0, import_react108.useCallback)(
    (eventValue, userMessageTimestamp) => {
      if (!settings.merged.ui.showModelInfoInChat) {
        return;
      }
      if (pendingHistoryItemRef.current) {
        addItem(pendingHistoryItemRef.current, userMessageTimestamp);
        setPendingHistoryItem(null);
      }
      addItem(
        {
          type: "model",
          model: eventValue
        },
        userMessageTimestamp
      );
    },
    [addItem, pendingHistoryItemRef, setPendingHistoryItem, settings]
  );
  const handleAgentExecutionStoppedEvent = (0, import_react108.useCallback)(
    (reason, userMessageTimestamp, systemMessage, contextCleared) => {
      if (pendingHistoryItemRef.current) {
        addItem(pendingHistoryItemRef.current, userMessageTimestamp);
        setPendingHistoryItem(null);
      }
      addItem(
        {
          type: "info" /* INFO */,
          text: `Agent execution stopped: ${systemMessage?.trim() || reason}`
        },
        userMessageTimestamp
      );
      maybeAddLowVerbosityFailureNote(userMessageTimestamp);
      if (contextCleared) {
        addItem(
          {
            type: "info" /* INFO */,
            text: "Conversation context has been cleared."
          },
          userMessageTimestamp
        );
      }
      setIsResponding(false);
    },
    [
      addItem,
      pendingHistoryItemRef,
      setPendingHistoryItem,
      setIsResponding,
      maybeAddLowVerbosityFailureNote
    ]
  );
  const handleAgentExecutionBlockedEvent = (0, import_react108.useCallback)(
    (reason, userMessageTimestamp, systemMessage, contextCleared) => {
      if (pendingHistoryItemRef.current) {
        addItem(pendingHistoryItemRef.current, userMessageTimestamp);
        setPendingHistoryItem(null);
      }
      addItem(
        {
          type: "warning" /* WARNING */,
          text: `Agent execution blocked: ${systemMessage?.trim() || reason}`
        },
        userMessageTimestamp
      );
      maybeAddLowVerbosityFailureNote(userMessageTimestamp);
      if (contextCleared) {
        addItem(
          {
            type: "info" /* INFO */,
            text: "Conversation context has been cleared."
          },
          userMessageTimestamp
        );
      }
    },
    [
      addItem,
      pendingHistoryItemRef,
      setPendingHistoryItem,
      maybeAddLowVerbosityFailureNote
    ]
  );
  const processGeminiStreamEvents = (0, import_react108.useCallback)(
    async (stream, userMessageTimestamp, signal) => {
      let geminiMessageBuffer = "";
      const toolCallRequests = [];
      for await (const event of stream) {
        if (event.type !== GeminiEventType.Thought && thoughtRef.current !== null) {
          setThought(null);
        }
        switch (event.type) {
          case GeminiEventType.Thought:
            setLastGeminiActivityTime(Date.now());
            handleThoughtEvent(event.value, userMessageTimestamp);
            break;
          case GeminiEventType.Content:
            setLastGeminiActivityTime(Date.now());
            geminiMessageBuffer = handleContentEvent(
              event.value,
              geminiMessageBuffer,
              userMessageTimestamp
            );
            break;
          case GeminiEventType.ToolCallRequest:
            toolCallRequests.push(event.value);
            break;
          case GeminiEventType.UserCancelled:
            handleUserCancelledEvent(userMessageTimestamp);
            break;
          case GeminiEventType.Error:
            handleErrorEvent(event.value, userMessageTimestamp);
            break;
          case GeminiEventType.AgentExecutionStopped:
            handleAgentExecutionStoppedEvent(
              event.value.reason,
              userMessageTimestamp,
              event.value.systemMessage,
              event.value.contextCleared
            );
            break;
          case GeminiEventType.AgentExecutionBlocked:
            handleAgentExecutionBlockedEvent(
              event.value.reason,
              userMessageTimestamp,
              event.value.systemMessage,
              event.value.contextCleared
            );
            break;
          case GeminiEventType.ChatCompressed:
            handleChatCompressionEvent(event.value, userMessageTimestamp);
            break;
          case GeminiEventType.ToolCallConfirmation:
          case GeminiEventType.ToolCallResponse:
            break;
          case GeminiEventType.MaxSessionTurns:
            handleMaxSessionTurnsEvent();
            break;
          case GeminiEventType.ContextWindowWillOverflow:
            handleContextWindowWillOverflowEvent(
              event.value.estimatedRequestTokenCount,
              event.value.remainingTokenCount
            );
            break;
          case GeminiEventType.Finished:
            handleFinishedEvent(event, userMessageTimestamp);
            break;
          case GeminiEventType.Citation:
            handleCitationEvent(event.value, userMessageTimestamp);
            break;
          case GeminiEventType.ModelInfo:
            handleChatModelEvent(event.value, userMessageTimestamp);
            break;
          case GeminiEventType.LoopDetected:
            loopDetectedRef.current = true;
            break;
          case GeminiEventType.Retry:
          case GeminiEventType.InvalidStream:
            break;
          default: {
            const unreachable = event;
            return unreachable;
          }
        }
      }
      if (toolCallRequests.length > 0) {
        if (pendingHistoryItemRef.current) {
          addItem(pendingHistoryItemRef.current, userMessageTimestamp);
          setPendingHistoryItem(null);
        }
        await scheduleToolCalls(toolCallRequests, signal);
      }
      return 0 /* Completed */;
    },
    [
      handleContentEvent,
      handleThoughtEvent,
      thoughtRef,
      handleUserCancelledEvent,
      handleErrorEvent,
      scheduleToolCalls,
      handleChatCompressionEvent,
      handleFinishedEvent,
      handleMaxSessionTurnsEvent,
      handleContextWindowWillOverflowEvent,
      handleCitationEvent,
      handleChatModelEvent,
      handleAgentExecutionStoppedEvent,
      handleAgentExecutionBlockedEvent,
      addItem,
      pendingHistoryItemRef,
      setPendingHistoryItem,
      setThought
    ]
  );
  const submitQuery = (0, import_react108.useCallback)(
    async (query, options, prompt_id) => runInDevTraceSpan(
      {
        operation: options?.isContinuation ? GeminiCliOperation.SystemPrompt : GeminiCliOperation.UserPrompt
      },
      async ({ metadata: spanMetadata }) => {
        spanMetadata.input = query;
        if ((isRespondingRef.current || streamingState === "responding" /* Responding */ || streamingState === "waiting_for_confirmation" /* WaitingForConfirmation */) && !options?.isContinuation)
          return;
        const queryId = `${Date.now()}-${Math.random()}`;
        activeQueryIdRef.current = queryId;
        const userMessageTimestamp = Date.now();
        if (!options?.isContinuation) {
          setModelSwitchedFromQuotaError(false);
          config.setQuotaErrorOccurred(false);
          config.resetBillingTurnState(
            settings.merged.billing?.overageStrategy
          );
          suppressedToolErrorCountRef.current = 0;
          suppressedToolErrorNoteShownRef.current = false;
          lowVerbosityFailureNoteShownRef.current = false;
        }
        abortControllerRef.current = new AbortController();
        const abortSignal = abortControllerRef.current.signal;
        turnCancelledRef.current = false;
        if (!prompt_id) {
          prompt_id = config.getSessionId() + "########" + getPromptCount();
        }
        return promptIdContext.run(prompt_id, async () => {
          const { queryToSend, shouldProceed } = await prepareQueryForGemini(
            query,
            userMessageTimestamp,
            abortSignal,
            prompt_id
          );
          if (!shouldProceed || queryToSend === null) {
            return;
          }
          if (!options?.isContinuation) {
            if (typeof queryToSend === "string") {
              const promptText = queryToSend;
              logUserPrompt(
                config,
                new UserPromptEvent(
                  promptText.length,
                  prompt_id,
                  config.getContentGeneratorConfig()?.authType,
                  promptText
                )
              );
            }
            startNewPrompt();
            setThought(null);
          }
          setIsResponding(true);
          setInitError(null);
          lastQueryRef.current = queryToSend;
          lastPromptIdRef.current = prompt_id;
          try {
            const stream = geminiClient.sendMessageStream(
              queryToSend,
              abortSignal,
              prompt_id,
              void 0,
              false,
              query
            );
            const processingStatus = await processGeminiStreamEvents(
              stream,
              userMessageTimestamp,
              abortSignal
            );
            if (processingStatus === 1 /* UserCancelled */) {
              return;
            }
            if (pendingHistoryItemRef.current) {
              addItem(pendingHistoryItemRef.current, userMessageTimestamp);
              setPendingHistoryItem(null);
            }
            if (loopDetectedRef.current) {
              loopDetectedRef.current = false;
              setLoopDetectionConfirmationRequest({
                onComplete: async (result) => {
                  setLoopDetectionConfirmationRequest(null);
                  if (result.userSelection === "disable") {
                    config.getGeminiClient().getLoopDetectionService().disableForSession();
                    addItem({
                      type: "info",
                      text: `Loop detection has been disabled for this session. Retrying request...`
                    });
                    if (lastQueryRef.current && lastPromptIdRef.current) {
                      await submitQuery(
                        lastQueryRef.current,
                        { isContinuation: true },
                        lastPromptIdRef.current
                      );
                    }
                  } else {
                    addItem({
                      type: "info",
                      text: `A potential loop was detected. This can happen due to repetitive tool calls or other model behavior. The request has been halted.`
                    });
                  }
                }
              });
            }
          } catch (error) {
            spanMetadata.error = error;
            if (error instanceof UnauthorizedError) {
              onAuthError("Session expired or is unauthorized.");
            } else if (
              // Suppress ValidationRequiredError if it was marked as handled (e.g. user clicked change_auth or cancelled)
              error instanceof ValidationRequiredError && error.userHandled
            ) {
            } else if (!isNodeError(error) || error.name !== "AbortError") {
              maybeAddSuppressedToolErrorNote(userMessageTimestamp);
              addItem(
                {
                  type: "error" /* ERROR */,
                  text: parseAndFormatApiError(
                    getErrorMessage(error) || "Unknown error",
                    config.getContentGeneratorConfig()?.authType,
                    void 0,
                    config.getModel(),
                    DEFAULT_GEMINI_FLASH_MODEL
                  )
                },
                userMessageTimestamp
              );
              maybeAddLowVerbosityFailureNote(userMessageTimestamp);
            }
          } finally {
            if (activeQueryIdRef.current === queryId) {
              setIsResponding(false);
            }
          }
        });
      }
    ),
    [
      streamingState,
      setModelSwitchedFromQuotaError,
      prepareQueryForGemini,
      processGeminiStreamEvents,
      pendingHistoryItemRef,
      addItem,
      setPendingHistoryItem,
      setInitError,
      geminiClient,
      onAuthError,
      config,
      startNewPrompt,
      getPromptCount,
      setThought,
      maybeAddSuppressedToolErrorNote,
      maybeAddLowVerbosityFailureNote,
      isRespondingRef,
      settings.merged.billing?.overageStrategy,
      setIsResponding
    ]
  );
  const handleApprovalModeChange = (0, import_react108.useCallback)(
    async (newApprovalMode) => {
      if (previousApprovalModeRef.current === ApprovalMode.PLAN && newApprovalMode !== ApprovalMode.PLAN && streamingState === "idle" /* Idle */) {
        if (geminiClient) {
          try {
            await geminiClient.addHistory({
              role: "user",
              parts: [
                {
                  text: getPlanModeExitMessage(newApprovalMode, true)
                }
              ]
            });
          } catch (error) {
            onDebugMessage(
              `Failed to notify model of Plan Mode exit: ${getErrorMessage(error)}`
            );
            addItem({
              type: "error" /* ERROR */,
              text: "Failed to update the model about exiting Plan Mode. The model might be out of sync. Please consider restarting the session if you see unexpected behavior."
            });
          }
        }
      }
      previousApprovalModeRef.current = newApprovalMode;
      if (newApprovalMode === ApprovalMode.YOLO || newApprovalMode === ApprovalMode.AUTO_EDIT) {
        let awaitingApprovalCalls = toolCalls.filter(
          (call) => call.status === "awaiting_approval" && !call.request.forcedAsk
        );
        if (newApprovalMode === ApprovalMode.AUTO_EDIT) {
          awaitingApprovalCalls = awaitingApprovalCalls.filter(
            (call) => EDIT_TOOL_NAMES.has(call.request.name)
          );
        }
        for (const call of awaitingApprovalCalls) {
          if (call.correlationId) {
            try {
              await config.getMessageBus().publish({
                type: MessageBusType.TOOL_CONFIRMATION_RESPONSE,
                correlationId: call.correlationId,
                confirmed: true,
                requiresUserConfirmation: false,
                outcome: ToolConfirmationOutcome.ProceedOnce
              });
            } catch (error) {
              debugLogger.warn(
                `Failed to auto-approve tool call ${call.request.callId}:`,
                error
              );
            }
          }
        }
      }
    },
    [config, toolCalls, geminiClient, streamingState, addItem, onDebugMessage]
  );
  const handleCompletedTools = (0, import_react108.useCallback)(
    async (completedToolCallsFromScheduler) => {
      const completedAndReadyToSubmitTools = completedToolCallsFromScheduler.filter(
        (tc) => {
          const isTerminalState = tc.status === "success" || tc.status === "error" || tc.status === "cancelled";
          if (isTerminalState) {
            const completedOrCancelledCall = tc;
            return completedOrCancelledCall.response?.responseParts !== void 0;
          }
          return false;
        }
      );
      const clientTools = completedAndReadyToSubmitTools.filter(
        (t) => t.request.isClientInitiated
      );
      if (clientTools.length > 0) {
        markToolsAsSubmitted(clientTools.map((t) => t.request.callId));
        if (geminiClient) {
          for (const tool of clientTools) {
            if (tool.request.name !== ACTIVATE_SKILL_TOOL_NAME) {
              continue;
            }
            await geminiClient.addHistory({
              role: "model",
              parts: [
                {
                  functionCall: {
                    name: tool.request.name,
                    args: tool.request.args
                  }
                }
              ]
            });
            await geminiClient.addHistory({
              role: "user",
              parts: tool.response.responseParts
            });
          }
        }
      }
      const newSuccessfulMemorySaves = completedAndReadyToSubmitTools.filter(
        (t) => t.request.name === "save_memory" && t.status === "success" && !processedMemoryToolsRef.current.has(t.request.callId)
      );
      for (const toolCall of completedAndReadyToSubmitTools) {
        const backgroundedTool = getBackgroundedToolInfo(toolCall);
        if (backgroundedTool) {
          registerBackgroundTask(
            backgroundedTool.pid,
            backgroundedTool.command,
            backgroundedTool.initialOutput
          );
        }
      }
      if (newSuccessfulMemorySaves.length > 0) {
        void performMemoryRefresh();
        newSuccessfulMemorySaves.forEach(
          (t) => processedMemoryToolsRef.current.add(t.request.callId)
        );
      }
      const geminiTools = completedAndReadyToSubmitTools.filter(
        (t) => !t.request.isClientInitiated
      );
      if (isLowErrorVerbosity) {
        suppressedToolErrorCountRef.current += geminiTools.filter(
          (tc) => tc.status === CoreToolCallStatus.Error
        ).length;
      }
      if (geminiTools.length === 0) {
        return;
      }
      const stopExecutionTool = geminiTools.find(
        (tc) => tc.response.errorType === ToolErrorType.STOP_EXECUTION
      );
      if (stopExecutionTool && stopExecutionTool.response.error) {
        maybeAddSuppressedToolErrorNote();
        addItem({
          type: "info" /* INFO */,
          text: `Agent execution stopped: ${stopExecutionTool.response.error.message}`
        });
        maybeAddLowVerbosityFailureNote();
        setIsResponding(false);
        const callIdsToMarkAsSubmitted2 = geminiTools.map(
          (toolCall) => toolCall.request.callId
        );
        markToolsAsSubmitted(callIdsToMarkAsSubmitted2);
        return;
      }
      const declinableTools = geminiTools.filter(
        (tc) => !isTopicTool2(tc.request.name)
      );
      const allDeclinableToolsCancelled = declinableTools.length > 0 && declinableTools.every(
        (tc) => tc.status === CoreToolCallStatus.Cancelled
      );
      const allToolsCancelled = geminiTools.length > 0 && geminiTools.every((tc) => tc.status === CoreToolCallStatus.Cancelled);
      if (allDeclinableToolsCancelled || allToolsCancelled) {
        if (!turnCancelledRef.current) {
          addItem({
            type: "info" /* INFO */,
            text: "Request cancelled."
          });
        }
        setIsResponding(false);
        if (geminiClient) {
          const combinedParts = geminiTools.flatMap(
            (toolCall) => toolCall.response.responseParts
          );
          geminiClient.addHistory({
            role: "user",
            parts: combinedParts
          });
        }
        const callIdsToMarkAsSubmitted2 = geminiTools.map(
          (toolCall) => toolCall.request.callId
        );
        markToolsAsSubmitted(callIdsToMarkAsSubmitted2);
        return;
      }
      const responsesToSend = geminiTools.flatMap(
        (toolCall) => toolCall.response.responseParts
      );
      if (consumeUserHint) {
        const userHint = consumeUserHint();
        if (userHint && userHint.trim().length > 0) {
          const hintText = userHint.trim();
          responsesToSend.unshift({
            text: buildUserSteeringHintPrompt(hintText)
          });
        }
      }
      const callIdsToMarkAsSubmitted = geminiTools.map(
        (toolCall) => toolCall.request.callId
      );
      const prompt_ids = geminiTools.map(
        (toolCall) => toolCall.request.prompt_id
      );
      markToolsAsSubmitted(callIdsToMarkAsSubmitted);
      if (modelSwitchedFromQuotaError) {
        return;
      }
      submitQuery(
        responsesToSend,
        {
          isContinuation: true
        },
        prompt_ids[0]
      );
    },
    [
      submitQuery,
      markToolsAsSubmitted,
      geminiClient,
      performMemoryRefresh,
      modelSwitchedFromQuotaError,
      addItem,
      registerBackgroundTask,
      consumeUserHint,
      isLowErrorVerbosity,
      maybeAddSuppressedToolErrorNote,
      maybeAddLowVerbosityFailureNote,
      setIsResponding
    ]
  );
  const pendingHistoryItems = (0, import_react108.useMemo)(
    () => [pendingHistoryItem, ...pendingToolGroupItems].filter(
      (i) => i !== void 0 && i !== null
    ),
    [pendingHistoryItem, pendingToolGroupItems]
  );
  (0, import_react108.useEffect)(() => {
    const saveRestorableToolCalls = async () => {
      if (!config.getCheckpointingEnabled()) {
        return;
      }
      const restorableToolCalls = toolCalls.filter(
        (toolCall) => EDIT_TOOL_NAMES.has(toolCall.request.name) && toolCall.status === CoreToolCallStatus.AwaitingApproval
      );
      if (restorableToolCalls.length > 0) {
        if (!gitService) {
          onDebugMessage(
            "Checkpointing is enabled but Git service is not available. Failed to create snapshot. Ensure Git is installed and working properly."
          );
          return;
        }
        const { checkpointsToWrite, errors } = await processRestorableToolCalls(
          restorableToolCalls.map((call) => call.request),
          gitService,
          geminiClient,
          history
        );
        if (errors.length > 0) {
          errors.forEach(onDebugMessage);
        }
        if (checkpointsToWrite.size > 0) {
          const checkpointDir = storage.getProjectTempCheckpointsDir();
          try {
            await fs6.mkdir(checkpointDir, { recursive: true });
            for (const [fileName, content] of checkpointsToWrite) {
              const filePath = path13.join(checkpointDir, fileName);
              await fs6.writeFile(filePath, content);
            }
          } catch (error) {
            onDebugMessage(
              `Failed to write checkpoint file: ${getErrorMessage(error)}`
            );
          }
        }
      }
    };
    saveRestorableToolCalls();
  }, [
    toolCalls,
    config,
    onDebugMessage,
    gitService,
    history,
    geminiClient,
    storage
  ]);
  const lastOutputTime = Math.max(
    lastToolOutputTime,
    lastShellOutputTime,
    lastGeminiActivityTime
  );
  return {
    streamingState,
    submitQuery,
    initError,
    pendingHistoryItems,
    thought,
    cancelOngoingRequest,
    pendingToolCalls: toolCalls,
    handleApprovalModeChange,
    activePtyId,
    loopDetectionConfirmationRequest,
    lastOutputTime,
    backgroundTaskCount,
    isBackgroundTaskVisible,
    toggleBackgroundTasks,
    backgroundCurrentExecution,
    backgroundTasks,
    dismissBackgroundTask,
    retryStatus
  };
};

// packages/cli/src/ui/hooks/vim.ts
var import_react109 = __toESM(require_react(), 1);
var DIGIT_MULTIPLIER = 10;
var DEFAULT_COUNT = 1;
var DIGIT_1_TO_9 = /^[1-9]$/;
var DOUBLE_ESCAPE_TIMEOUT_MS = 500;
var CMD_TYPES = {
  DELETE_WORD_FORWARD: "dw",
  DELETE_WORD_BACKWARD: "db",
  DELETE_WORD_END: "de",
  DELETE_BIG_WORD_FORWARD: "dW",
  DELETE_BIG_WORD_BACKWARD: "dB",
  DELETE_BIG_WORD_END: "dE",
  CHANGE_WORD_FORWARD: "cw",
  CHANGE_WORD_BACKWARD: "cb",
  CHANGE_WORD_END: "ce",
  CHANGE_BIG_WORD_FORWARD: "cW",
  CHANGE_BIG_WORD_BACKWARD: "cB",
  CHANGE_BIG_WORD_END: "cE",
  DELETE_CHAR: "x",
  DELETE_CHAR_BEFORE: "X",
  TOGGLE_CASE: "~",
  REPLACE_CHAR: "r",
  DELETE_LINE: "dd",
  CHANGE_LINE: "cc",
  DELETE_TO_EOL: "D",
  CHANGE_TO_EOL: "C",
  CHANGE_MOVEMENT: {
    LEFT: "ch",
    DOWN: "cj",
    UP: "ck",
    RIGHT: "cl"
  },
  DELETE_MOVEMENT: {
    LEFT: "dh",
    DOWN: "dj",
    UP: "dk",
    RIGHT: "dl"
  },
  DELETE_TO_SOL: "d0",
  DELETE_TO_FIRST_NONWS: "d^",
  CHANGE_TO_SOL: "c0",
  CHANGE_TO_FIRST_NONWS: "c^",
  DELETE_TO_FIRST_LINE: "dgg",
  DELETE_TO_LAST_LINE: "dG",
  CHANGE_TO_FIRST_LINE: "cgg",
  CHANGE_TO_LAST_LINE: "cG",
  YANK_LINE: "yy",
  YANK_WORD_FORWARD: "yw",
  YANK_BIG_WORD_FORWARD: "yW",
  YANK_WORD_END: "ye",
  YANK_BIG_WORD_END: "yE",
  YANK_TO_EOL: "y$",
  PASTE_AFTER: "p",
  PASTE_BEFORE: "P"
};
var createClearPendingState = () => ({
  count: 0,
  pendingOperator: null,
  pendingFindOp: void 0
});
var initialVimState = {
  mode: "INSERT",
  count: 0,
  pendingOperator: null,
  pendingFindOp: void 0,
  lastCommand: null,
  lastFind: void 0
};
var vimReducer = (state, action) => {
  switch (action.type) {
    case "SET_MODE":
      return { ...state, mode: action.mode };
    case "SET_COUNT":
      return { ...state, count: action.count };
    case "INCREMENT_COUNT":
      return { ...state, count: state.count * DIGIT_MULTIPLIER + action.digit };
    case "CLEAR_COUNT":
      return { ...state, count: 0 };
    case "SET_PENDING_OPERATOR":
      return { ...state, pendingOperator: action.operator };
    case "SET_PENDING_FIND_OP":
      return { ...state, pendingFindOp: action.pendingFindOp };
    case "SET_LAST_FIND":
      return { ...state, lastFind: action.find };
    case "SET_LAST_COMMAND":
      return { ...state, lastCommand: action.command };
    case "CLEAR_PENDING_STATES":
      return {
        ...state,
        ...createClearPendingState()
      };
    case "ESCAPE_TO_NORMAL":
      return {
        ...state,
        ...createClearPendingState()
      };
    default:
      return state;
  }
};
function useVim(buffer, onSubmit) {
  const keyMatchers = useKeyMatchers();
  const { vimEnabled, vimMode, setVimMode } = useVimMode();
  const [state, dispatch] = (0, import_react109.useReducer)(vimReducer, initialVimState);
  const lastEscapeTimestampRef = (0, import_react109.useRef)(0);
  (0, import_react109.useEffect)(() => {
    dispatch({ type: "SET_MODE", mode: vimMode });
  }, [vimMode]);
  const updateMode = (0, import_react109.useCallback)(
    (mode) => {
      setVimMode(mode);
      dispatch({ type: "SET_MODE", mode });
    },
    [setVimMode]
  );
  const getCurrentCount = (0, import_react109.useCallback)(
    () => state.count || DEFAULT_COUNT,
    [state.count]
  );
  const checkDoubleEscape = (0, import_react109.useCallback)(() => {
    const now = Date.now();
    const lastEscape = lastEscapeTimestampRef.current;
    lastEscapeTimestampRef.current = now;
    if (now - lastEscape <= DOUBLE_ESCAPE_TIMEOUT_MS) {
      lastEscapeTimestampRef.current = 0;
      return true;
    }
    return false;
  }, []);
  const executeCommand = (0, import_react109.useCallback)(
    (cmdType, count, char) => {
      switch (cmdType) {
        case CMD_TYPES.DELETE_WORD_FORWARD: {
          buffer.vimDeleteWordForward(count);
          break;
        }
        case CMD_TYPES.DELETE_WORD_BACKWARD: {
          buffer.vimDeleteWordBackward(count);
          break;
        }
        case CMD_TYPES.DELETE_WORD_END: {
          buffer.vimDeleteWordEnd(count);
          break;
        }
        case CMD_TYPES.DELETE_BIG_WORD_FORWARD: {
          buffer.vimDeleteBigWordForward(count);
          break;
        }
        case CMD_TYPES.DELETE_BIG_WORD_BACKWARD: {
          buffer.vimDeleteBigWordBackward(count);
          break;
        }
        case CMD_TYPES.DELETE_BIG_WORD_END: {
          buffer.vimDeleteBigWordEnd(count);
          break;
        }
        case CMD_TYPES.CHANGE_WORD_FORWARD: {
          buffer.vimChangeWordForward(count);
          updateMode("INSERT");
          break;
        }
        case CMD_TYPES.CHANGE_WORD_BACKWARD: {
          buffer.vimChangeWordBackward(count);
          updateMode("INSERT");
          break;
        }
        case CMD_TYPES.CHANGE_WORD_END: {
          buffer.vimChangeWordEnd(count);
          updateMode("INSERT");
          break;
        }
        case CMD_TYPES.CHANGE_BIG_WORD_FORWARD: {
          buffer.vimChangeBigWordForward(count);
          updateMode("INSERT");
          break;
        }
        case CMD_TYPES.CHANGE_BIG_WORD_BACKWARD: {
          buffer.vimChangeBigWordBackward(count);
          updateMode("INSERT");
          break;
        }
        case CMD_TYPES.CHANGE_BIG_WORD_END: {
          buffer.vimChangeBigWordEnd(count);
          updateMode("INSERT");
          break;
        }
        case CMD_TYPES.DELETE_CHAR: {
          buffer.vimDeleteChar(count);
          break;
        }
        case CMD_TYPES.DELETE_CHAR_BEFORE: {
          buffer.vimDeleteCharBefore(count);
          break;
        }
        case CMD_TYPES.TOGGLE_CASE: {
          buffer.vimToggleCase(count);
          break;
        }
        case CMD_TYPES.REPLACE_CHAR: {
          if (char) buffer.vimReplaceChar(char, count);
          break;
        }
        case CMD_TYPES.DELETE_LINE: {
          buffer.vimDeleteLine(count);
          break;
        }
        case CMD_TYPES.CHANGE_LINE: {
          buffer.vimChangeLine(count);
          updateMode("INSERT");
          break;
        }
        case CMD_TYPES.CHANGE_MOVEMENT.LEFT:
        case CMD_TYPES.CHANGE_MOVEMENT.DOWN:
        case CMD_TYPES.CHANGE_MOVEMENT.UP:
        case CMD_TYPES.CHANGE_MOVEMENT.RIGHT: {
          const movementMap = {
            [CMD_TYPES.CHANGE_MOVEMENT.LEFT]: "h",
            [CMD_TYPES.CHANGE_MOVEMENT.DOWN]: "j",
            [CMD_TYPES.CHANGE_MOVEMENT.UP]: "k",
            [CMD_TYPES.CHANGE_MOVEMENT.RIGHT]: "l"
          };
          const movementType = movementMap[cmdType];
          if (movementType) {
            buffer.vimChangeMovement(movementType, count);
            updateMode("INSERT");
          }
          break;
        }
        case CMD_TYPES.DELETE_TO_EOL: {
          buffer.vimDeleteToEndOfLine(count);
          break;
        }
        case CMD_TYPES.DELETE_TO_SOL: {
          buffer.vimDeleteToStartOfLine();
          break;
        }
        case CMD_TYPES.DELETE_MOVEMENT.LEFT:
        case CMD_TYPES.DELETE_MOVEMENT.DOWN:
        case CMD_TYPES.DELETE_MOVEMENT.UP:
        case CMD_TYPES.DELETE_MOVEMENT.RIGHT: {
          const movementMap = {
            [CMD_TYPES.DELETE_MOVEMENT.LEFT]: "h",
            [CMD_TYPES.DELETE_MOVEMENT.DOWN]: "j",
            [CMD_TYPES.DELETE_MOVEMENT.UP]: "k",
            [CMD_TYPES.DELETE_MOVEMENT.RIGHT]: "l"
          };
          const movementType = movementMap[cmdType];
          if (movementType) {
            buffer.vimChangeMovement(movementType, count);
          }
          break;
        }
        case CMD_TYPES.CHANGE_TO_EOL: {
          buffer.vimChangeToEndOfLine(count);
          updateMode("INSERT");
          break;
        }
        case CMD_TYPES.DELETE_TO_FIRST_NONWS: {
          buffer.vimDeleteToFirstNonWhitespace();
          break;
        }
        case CMD_TYPES.CHANGE_TO_SOL: {
          buffer.vimChangeToStartOfLine();
          updateMode("INSERT");
          break;
        }
        case CMD_TYPES.CHANGE_TO_FIRST_NONWS: {
          buffer.vimChangeToFirstNonWhitespace();
          updateMode("INSERT");
          break;
        }
        case CMD_TYPES.DELETE_TO_FIRST_LINE: {
          buffer.vimDeleteToFirstLine(count);
          break;
        }
        case CMD_TYPES.DELETE_TO_LAST_LINE: {
          buffer.vimDeleteToLastLine(count);
          break;
        }
        case CMD_TYPES.CHANGE_TO_FIRST_LINE: {
          buffer.vimDeleteToFirstLine(count);
          updateMode("INSERT");
          break;
        }
        case CMD_TYPES.CHANGE_TO_LAST_LINE: {
          buffer.vimDeleteToLastLine(count);
          updateMode("INSERT");
          break;
        }
        case CMD_TYPES.YANK_LINE: {
          buffer.vimYankLine(count);
          break;
        }
        case CMD_TYPES.YANK_WORD_FORWARD: {
          buffer.vimYankWordForward(count);
          break;
        }
        case CMD_TYPES.YANK_BIG_WORD_FORWARD: {
          buffer.vimYankBigWordForward(count);
          break;
        }
        case CMD_TYPES.YANK_WORD_END: {
          buffer.vimYankWordEnd(count);
          break;
        }
        case CMD_TYPES.YANK_BIG_WORD_END: {
          buffer.vimYankBigWordEnd(count);
          break;
        }
        case CMD_TYPES.YANK_TO_EOL: {
          buffer.vimYankToEndOfLine(count);
          break;
        }
        case CMD_TYPES.PASTE_AFTER: {
          buffer.vimPasteAfter(count);
          break;
        }
        case CMD_TYPES.PASTE_BEFORE: {
          buffer.vimPasteBefore(count);
          break;
        }
        default:
          return false;
      }
      return true;
    },
    [buffer, updateMode]
  );
  const handleInsertModeInput = (0, import_react109.useCallback)(
    (normalizedKey) => {
      if (keyMatchers["basic.cancel" /* ESCAPE */](normalizedKey)) {
        checkDoubleEscape();
        buffer.vimEscapeInsertMode();
        dispatch({ type: "ESCAPE_TO_NORMAL" });
        updateMode("NORMAL");
        return true;
      }
      if (normalizedKey.name === "tab" || normalizedKey.name === "enter" && !normalizedKey.ctrl || normalizedKey.name === "up" || normalizedKey.name === "down" || normalizedKey.ctrl && normalizedKey.name === "r") {
        return false;
      }
      if (normalizedKey.ctrl && (normalizedKey.name === "u" || normalizedKey.name === "k")) {
        return false;
      }
      if (normalizedKey.ctrl && normalizedKey.name === "v") {
        return false;
      }
      if (normalizedKey.sequence === "!" && buffer.text.length === 0) {
        return false;
      }
      if (normalizedKey.name === "enter" && !normalizedKey.alt && !normalizedKey.ctrl && !normalizedKey.cmd) {
        if (buffer.text.trim() && onSubmit) {
          const submittedValue = buffer.text;
          buffer.setText("");
          onSubmit(submittedValue);
          return true;
        }
        return true;
      }
      return buffer.handleInput(normalizedKey);
    },
    [buffer, dispatch, updateMode, onSubmit, checkDoubleEscape, keyMatchers]
  );
  const normalizeKey = (0, import_react109.useCallback)(
    (key) => ({
      name: key.name || "",
      sequence: key.sequence || "",
      shift: key.shift || false,
      alt: key.alt || false,
      ctrl: key.ctrl || false,
      cmd: key.cmd || false,
      insertable: key.insertable || false
    }),
    []
  );
  const handleChangeMovement = (0, import_react109.useCallback)(
    (movement) => {
      const count = getCurrentCount();
      dispatch({ type: "CLEAR_COUNT" });
      buffer.vimChangeMovement(movement, count);
      updateMode("INSERT");
      const cmdTypeMap = {
        h: CMD_TYPES.CHANGE_MOVEMENT.LEFT,
        j: CMD_TYPES.CHANGE_MOVEMENT.DOWN,
        k: CMD_TYPES.CHANGE_MOVEMENT.UP,
        l: CMD_TYPES.CHANGE_MOVEMENT.RIGHT
      };
      dispatch({
        type: "SET_LAST_COMMAND",
        command: { type: cmdTypeMap[movement], count }
      });
      dispatch({ type: "SET_PENDING_OPERATOR", operator: null });
      return true;
    },
    [getCurrentCount, dispatch, buffer, updateMode]
  );
  const handleDeleteMovement = (0, import_react109.useCallback)(
    (movement) => {
      const count = getCurrentCount();
      dispatch({ type: "CLEAR_COUNT" });
      buffer.vimChangeMovement(movement, count);
      const cmdTypeMap = {
        h: CMD_TYPES.DELETE_MOVEMENT.LEFT,
        j: CMD_TYPES.DELETE_MOVEMENT.DOWN,
        k: CMD_TYPES.DELETE_MOVEMENT.UP,
        l: CMD_TYPES.DELETE_MOVEMENT.RIGHT
      };
      dispatch({
        type: "SET_LAST_COMMAND",
        command: { type: cmdTypeMap[movement], count }
      });
      dispatch({ type: "SET_PENDING_OPERATOR", operator: null });
      return true;
    },
    [getCurrentCount, dispatch, buffer]
  );
  const handleOperatorMotion = (0, import_react109.useCallback)(
    (operator2, motion) => {
      const count = getCurrentCount();
      const commandMap = {
        d: {
          w: CMD_TYPES.DELETE_WORD_FORWARD,
          b: CMD_TYPES.DELETE_WORD_BACKWARD,
          e: CMD_TYPES.DELETE_WORD_END,
          W: CMD_TYPES.DELETE_BIG_WORD_FORWARD,
          B: CMD_TYPES.DELETE_BIG_WORD_BACKWARD,
          E: CMD_TYPES.DELETE_BIG_WORD_END
        },
        c: {
          w: CMD_TYPES.CHANGE_WORD_FORWARD,
          b: CMD_TYPES.CHANGE_WORD_BACKWARD,
          e: CMD_TYPES.CHANGE_WORD_END,
          W: CMD_TYPES.CHANGE_BIG_WORD_FORWARD,
          B: CMD_TYPES.CHANGE_BIG_WORD_BACKWARD,
          E: CMD_TYPES.CHANGE_BIG_WORD_END
        }
      };
      const cmdType = commandMap[operator2][motion];
      executeCommand(cmdType, count);
      dispatch({
        type: "SET_LAST_COMMAND",
        command: { type: cmdType, count }
      });
      dispatch({ type: "CLEAR_COUNT" });
      dispatch({ type: "SET_PENDING_OPERATOR", operator: null });
      return true;
    },
    [getCurrentCount, executeCommand, dispatch]
  );
  const handleInput = (0, import_react109.useCallback)(
    (key) => {
      if (!vimEnabled) {
        return false;
      }
      let normalizedKey;
      try {
        normalizedKey = normalizeKey(key);
      } catch (error) {
        debugLogger.warn("Malformed key input in vim mode:", key, error);
        return false;
      }
      if (keyMatchers["edit.clear" /* CLEAR_INPUT */](normalizedKey)) {
        return false;
      }
      if (state.mode === "INSERT") {
        return handleInsertModeInput(normalizedKey);
      }
      if (state.mode === "NORMAL") {
        if (keyMatchers["basic.cancel" /* ESCAPE */](normalizedKey)) {
          if (state.pendingOperator || state.pendingFindOp) {
            dispatch({ type: "CLEAR_PENDING_STATES" });
            lastEscapeTimestampRef.current = 0;
            return true;
          }
          if (checkDoubleEscape()) {
            buffer.setText("");
            return true;
          }
          return false;
        }
        if (DIGIT_1_TO_9.test(normalizedKey.sequence) || normalizedKey.sequence === "0" && state.count > 0) {
          dispatch({
            type: "INCREMENT_COUNT",
            digit: parseInt(normalizedKey.sequence, 10)
          });
          return true;
        }
        const repeatCount = getCurrentCount();
        if (state.pendingFindOp !== void 0) {
          const targetChar = normalizedKey.sequence;
          const { op, operator: operator2, count: findCount } = state.pendingFindOp;
          dispatch({ type: "SET_PENDING_FIND_OP", pendingFindOp: void 0 });
          dispatch({ type: "CLEAR_COUNT" });
          if (targetChar && toCodePoints(targetChar).length === 1) {
            if (op === "r") {
              buffer.vimReplaceChar(targetChar, findCount);
              dispatch({
                type: "SET_LAST_COMMAND",
                command: {
                  type: CMD_TYPES.REPLACE_CHAR,
                  count: findCount,
                  char: targetChar
                }
              });
            } else {
              const isBackward = op === "F" || op === "T";
              const isTill = op === "t" || op === "T";
              if (operator2 === "d" || operator2 === "c") {
                const del = isBackward ? buffer.vimDeleteToCharBackward : buffer.vimDeleteToCharForward;
                del(targetChar, findCount, isTill);
                if (operator2 === "c") updateMode("INSERT");
              } else {
                const find = isBackward ? buffer.vimFindCharBackward : buffer.vimFindCharForward;
                find(targetChar, findCount, isTill);
                dispatch({
                  type: "SET_LAST_FIND",
                  find: { op, char: targetChar }
                });
              }
            }
          }
          return true;
        }
        switch (normalizedKey.sequence) {
          case "h": {
            if (state.pendingOperator === "d") {
              return handleDeleteMovement("h");
            }
            if (state.pendingOperator === "c") {
              return handleChangeMovement("h");
            }
            buffer.vimMoveLeft(repeatCount);
            dispatch({ type: "CLEAR_COUNT" });
            return true;
          }
          case "j": {
            if (state.pendingOperator === "d") {
              return handleDeleteMovement("j");
            }
            if (state.pendingOperator === "c") {
              return handleChangeMovement("j");
            }
            buffer.vimMoveDown(repeatCount);
            dispatch({ type: "CLEAR_COUNT" });
            return true;
          }
          case "k": {
            if (state.pendingOperator === "d") {
              return handleDeleteMovement("k");
            }
            if (state.pendingOperator === "c") {
              return handleChangeMovement("k");
            }
            buffer.vimMoveUp(repeatCount);
            dispatch({ type: "CLEAR_COUNT" });
            return true;
          }
          case "l": {
            if (state.pendingOperator === "d") {
              return handleDeleteMovement("l");
            }
            if (state.pendingOperator === "c") {
              return handleChangeMovement("l");
            }
            buffer.vimMoveRight(repeatCount);
            dispatch({ type: "CLEAR_COUNT" });
            return true;
          }
          case "w": {
            if (state.pendingOperator === "d") {
              return handleOperatorMotion("d", "w");
            }
            if (state.pendingOperator === "c") {
              return handleOperatorMotion("c", "w");
            }
            if (state.pendingOperator === "y") {
              const count = getCurrentCount();
              executeCommand(CMD_TYPES.YANK_WORD_FORWARD, count);
              dispatch({
                type: "SET_LAST_COMMAND",
                command: { type: CMD_TYPES.YANK_WORD_FORWARD, count }
              });
              dispatch({ type: "CLEAR_COUNT" });
              dispatch({ type: "SET_PENDING_OPERATOR", operator: null });
              return true;
            }
            buffer.vimMoveWordForward(repeatCount);
            dispatch({ type: "CLEAR_COUNT" });
            return true;
          }
          case "W": {
            if (state.pendingOperator === "d") {
              return handleOperatorMotion("d", "W");
            }
            if (state.pendingOperator === "c") {
              return handleOperatorMotion("c", "W");
            }
            if (state.pendingOperator === "y") {
              const count = getCurrentCount();
              executeCommand(CMD_TYPES.YANK_BIG_WORD_FORWARD, count);
              dispatch({
                type: "SET_LAST_COMMAND",
                command: { type: CMD_TYPES.YANK_BIG_WORD_FORWARD, count }
              });
              dispatch({ type: "CLEAR_COUNT" });
              dispatch({ type: "SET_PENDING_OPERATOR", operator: null });
              return true;
            }
            buffer.vimMoveBigWordForward(repeatCount);
            dispatch({ type: "CLEAR_COUNT" });
            return true;
          }
          case "b": {
            if (state.pendingOperator === "d") {
              return handleOperatorMotion("d", "b");
            }
            if (state.pendingOperator === "c") {
              return handleOperatorMotion("c", "b");
            }
            buffer.vimMoveWordBackward(repeatCount);
            dispatch({ type: "CLEAR_COUNT" });
            return true;
          }
          case "B": {
            if (state.pendingOperator === "d") {
              return handleOperatorMotion("d", "B");
            }
            if (state.pendingOperator === "c") {
              return handleOperatorMotion("c", "B");
            }
            buffer.vimMoveBigWordBackward(repeatCount);
            dispatch({ type: "CLEAR_COUNT" });
            return true;
          }
          case "e": {
            if (state.pendingOperator === "d") {
              return handleOperatorMotion("d", "e");
            }
            if (state.pendingOperator === "c") {
              return handleOperatorMotion("c", "e");
            }
            if (state.pendingOperator === "y") {
              const count = getCurrentCount();
              executeCommand(CMD_TYPES.YANK_WORD_END, count);
              dispatch({
                type: "SET_LAST_COMMAND",
                command: { type: CMD_TYPES.YANK_WORD_END, count }
              });
              dispatch({ type: "CLEAR_COUNT" });
              dispatch({ type: "SET_PENDING_OPERATOR", operator: null });
              return true;
            }
            buffer.vimMoveWordEnd(repeatCount);
            dispatch({ type: "CLEAR_COUNT" });
            return true;
          }
          case "E": {
            if (state.pendingOperator === "d") {
              return handleOperatorMotion("d", "E");
            }
            if (state.pendingOperator === "c") {
              return handleOperatorMotion("c", "E");
            }
            if (state.pendingOperator === "y") {
              const count = getCurrentCount();
              executeCommand(CMD_TYPES.YANK_BIG_WORD_END, count);
              dispatch({
                type: "SET_LAST_COMMAND",
                command: { type: CMD_TYPES.YANK_BIG_WORD_END, count }
              });
              dispatch({ type: "CLEAR_COUNT" });
              dispatch({ type: "SET_PENDING_OPERATOR", operator: null });
              return true;
            }
            buffer.vimMoveBigWordEnd(repeatCount);
            dispatch({ type: "CLEAR_COUNT" });
            return true;
          }
          case "x": {
            buffer.vimDeleteChar(repeatCount);
            dispatch({
              type: "SET_LAST_COMMAND",
              command: { type: CMD_TYPES.DELETE_CHAR, count: repeatCount }
            });
            dispatch({ type: "CLEAR_COUNT" });
            return true;
          }
          case "X": {
            buffer.vimDeleteCharBefore(repeatCount);
            dispatch({
              type: "SET_LAST_COMMAND",
              command: {
                type: CMD_TYPES.DELETE_CHAR_BEFORE,
                count: repeatCount
              }
            });
            dispatch({ type: "CLEAR_COUNT" });
            return true;
          }
          case "~": {
            buffer.vimToggleCase(repeatCount);
            dispatch({
              type: "SET_LAST_COMMAND",
              command: { type: CMD_TYPES.TOGGLE_CASE, count: repeatCount }
            });
            dispatch({ type: "CLEAR_COUNT" });
            return true;
          }
          case "r": {
            dispatch({ type: "CLEAR_PENDING_STATES" });
            dispatch({
              type: "SET_PENDING_FIND_OP",
              pendingFindOp: {
                op: "r",
                operator: void 0,
                count: repeatCount
              }
            });
            return true;
          }
          case "f":
          case "F":
          case "t":
          case "T": {
            const op = normalizedKey.sequence;
            const operator2 = state.pendingOperator === "d" || state.pendingOperator === "c" ? state.pendingOperator : void 0;
            dispatch({ type: "CLEAR_PENDING_STATES" });
            dispatch({
              type: "SET_PENDING_FIND_OP",
              pendingFindOp: { op, operator: operator2, count: repeatCount }
            });
            return true;
          }
          case ";":
          case ",": {
            if (state.lastFind) {
              const { op, char } = state.lastFind;
              const isForward = op === "f" || op === "t";
              const isTill = op === "t" || op === "T";
              const reverse = normalizedKey.sequence === ",";
              const shouldMoveForward = reverse ? !isForward : isForward;
              if (shouldMoveForward) {
                buffer.vimFindCharForward(char, repeatCount, isTill);
              } else {
                buffer.vimFindCharBackward(char, repeatCount, isTill);
              }
            }
            dispatch({ type: "CLEAR_COUNT" });
            return true;
          }
          case "i": {
            buffer.vimInsertAtCursor();
            updateMode("INSERT");
            dispatch({ type: "CLEAR_COUNT" });
            return true;
          }
          case "a": {
            buffer.vimAppendAtCursor();
            updateMode("INSERT");
            dispatch({ type: "CLEAR_COUNT" });
            return true;
          }
          case "o": {
            buffer.vimOpenLineBelow();
            updateMode("INSERT");
            dispatch({ type: "CLEAR_COUNT" });
            return true;
          }
          case "O": {
            buffer.vimOpenLineAbove();
            updateMode("INSERT");
            dispatch({ type: "CLEAR_COUNT" });
            return true;
          }
          case "0": {
            if (state.pendingOperator === "d") {
              buffer.vimDeleteToStartOfLine();
              dispatch({
                type: "SET_LAST_COMMAND",
                command: { type: CMD_TYPES.DELETE_TO_SOL, count: 1 }
              });
              dispatch({ type: "CLEAR_COUNT" });
              dispatch({ type: "SET_PENDING_OPERATOR", operator: null });
              return true;
            }
            if (state.pendingOperator === "c") {
              buffer.vimChangeToStartOfLine();
              dispatch({
                type: "SET_LAST_COMMAND",
                command: { type: CMD_TYPES.CHANGE_TO_SOL, count: 1 }
              });
              dispatch({ type: "CLEAR_COUNT" });
              dispatch({ type: "SET_PENDING_OPERATOR", operator: null });
              updateMode("INSERT");
              return true;
            }
            buffer.vimMoveToLineStart();
            dispatch({ type: "CLEAR_COUNT" });
            return true;
          }
          case "$": {
            if (state.pendingOperator === "d") {
              buffer.vimDeleteToEndOfLine(repeatCount);
              dispatch({
                type: "SET_LAST_COMMAND",
                command: { type: CMD_TYPES.DELETE_TO_EOL, count: repeatCount }
              });
              dispatch({ type: "CLEAR_COUNT" });
              dispatch({ type: "SET_PENDING_OPERATOR", operator: null });
              return true;
            }
            if (state.pendingOperator === "c") {
              buffer.vimChangeToEndOfLine(repeatCount);
              dispatch({
                type: "SET_LAST_COMMAND",
                command: { type: CMD_TYPES.CHANGE_TO_EOL, count: repeatCount }
              });
              dispatch({ type: "CLEAR_COUNT" });
              dispatch({ type: "SET_PENDING_OPERATOR", operator: null });
              updateMode("INSERT");
              return true;
            }
            if (state.pendingOperator === "y") {
              executeCommand(CMD_TYPES.YANK_TO_EOL, repeatCount);
              dispatch({
                type: "SET_LAST_COMMAND",
                command: { type: CMD_TYPES.YANK_TO_EOL, count: repeatCount }
              });
              dispatch({ type: "CLEAR_COUNT" });
              dispatch({ type: "SET_PENDING_OPERATOR", operator: null });
              return true;
            }
            if (repeatCount > 1) {
              buffer.vimMoveDown(repeatCount - 1);
            }
            buffer.vimMoveToLineEnd();
            dispatch({ type: "CLEAR_COUNT" });
            return true;
          }
          case "^": {
            if (state.pendingOperator === "d") {
              buffer.vimDeleteToFirstNonWhitespace();
              dispatch({
                type: "SET_LAST_COMMAND",
                command: { type: CMD_TYPES.DELETE_TO_FIRST_NONWS, count: 1 }
              });
              dispatch({ type: "CLEAR_COUNT" });
              dispatch({ type: "SET_PENDING_OPERATOR", operator: null });
              return true;
            }
            if (state.pendingOperator === "c") {
              buffer.vimChangeToFirstNonWhitespace();
              dispatch({
                type: "SET_LAST_COMMAND",
                command: { type: CMD_TYPES.CHANGE_TO_FIRST_NONWS, count: 1 }
              });
              dispatch({ type: "CLEAR_COUNT" });
              dispatch({ type: "SET_PENDING_OPERATOR", operator: null });
              updateMode("INSERT");
              return true;
            }
            buffer.vimMoveToFirstNonWhitespace();
            dispatch({ type: "CLEAR_COUNT" });
            return true;
          }
          case "g": {
            if (state.pendingOperator === "d") {
              dispatch({ type: "SET_PENDING_OPERATOR", operator: "dg" });
              return true;
            }
            if (state.pendingOperator === "c") {
              dispatch({ type: "SET_PENDING_OPERATOR", operator: "cg" });
              return true;
            }
            if (state.pendingOperator === "dg") {
              buffer.vimDeleteToFirstLine(state.count);
              dispatch({
                type: "SET_LAST_COMMAND",
                command: {
                  type: CMD_TYPES.DELETE_TO_FIRST_LINE,
                  count: state.count
                }
              });
              dispatch({ type: "SET_PENDING_OPERATOR", operator: null });
              dispatch({ type: "CLEAR_COUNT" });
              return true;
            }
            if (state.pendingOperator === "cg") {
              buffer.vimDeleteToFirstLine(state.count);
              dispatch({
                type: "SET_LAST_COMMAND",
                command: {
                  type: CMD_TYPES.CHANGE_TO_FIRST_LINE,
                  count: state.count
                }
              });
              dispatch({ type: "SET_PENDING_OPERATOR", operator: null });
              dispatch({ type: "CLEAR_COUNT" });
              updateMode("INSERT");
              return true;
            }
            if (state.pendingOperator === "g") {
              if (state.count > 0) {
                buffer.vimMoveToLine(state.count);
              } else {
                buffer.vimMoveToFirstLine();
              }
              dispatch({ type: "SET_PENDING_OPERATOR", operator: null });
              dispatch({ type: "CLEAR_COUNT" });
            } else {
              dispatch({ type: "SET_PENDING_OPERATOR", operator: "g" });
            }
            return true;
          }
          case "G": {
            if (state.pendingOperator === "d") {
              buffer.vimDeleteToLastLine(state.count);
              dispatch({
                type: "SET_LAST_COMMAND",
                command: {
                  type: CMD_TYPES.DELETE_TO_LAST_LINE,
                  count: state.count
                }
              });
              dispatch({ type: "CLEAR_COUNT" });
              dispatch({ type: "SET_PENDING_OPERATOR", operator: null });
              return true;
            }
            if (state.pendingOperator === "c") {
              buffer.vimDeleteToLastLine(state.count);
              dispatch({
                type: "SET_LAST_COMMAND",
                command: {
                  type: CMD_TYPES.CHANGE_TO_LAST_LINE,
                  count: state.count
                }
              });
              dispatch({ type: "CLEAR_COUNT" });
              dispatch({ type: "SET_PENDING_OPERATOR", operator: null });
              updateMode("INSERT");
              return true;
            }
            if (state.count > 0) {
              buffer.vimMoveToLine(state.count);
            } else {
              buffer.vimMoveToLastLine();
            }
            dispatch({ type: "CLEAR_COUNT" });
            return true;
          }
          case "I": {
            buffer.vimInsertAtLineStart();
            updateMode("INSERT");
            dispatch({ type: "CLEAR_COUNT" });
            return true;
          }
          case "A": {
            buffer.vimAppendAtLineEnd();
            updateMode("INSERT");
            dispatch({ type: "CLEAR_COUNT" });
            return true;
          }
          case "d": {
            if (state.pendingOperator === "d") {
              const repeatCount2 = getCurrentCount();
              executeCommand(CMD_TYPES.DELETE_LINE, repeatCount2);
              dispatch({
                type: "SET_LAST_COMMAND",
                command: { type: CMD_TYPES.DELETE_LINE, count: repeatCount2 }
              });
              dispatch({ type: "CLEAR_COUNT" });
              dispatch({ type: "SET_PENDING_OPERATOR", operator: null });
            } else {
              dispatch({ type: "SET_PENDING_OPERATOR", operator: "d" });
            }
            return true;
          }
          case "c": {
            if (state.pendingOperator === "c") {
              const repeatCount2 = getCurrentCount();
              executeCommand(CMD_TYPES.CHANGE_LINE, repeatCount2);
              dispatch({
                type: "SET_LAST_COMMAND",
                command: { type: CMD_TYPES.CHANGE_LINE, count: repeatCount2 }
              });
              dispatch({ type: "CLEAR_COUNT" });
              dispatch({ type: "SET_PENDING_OPERATOR", operator: null });
            } else {
              dispatch({ type: "SET_PENDING_OPERATOR", operator: "c" });
            }
            return true;
          }
          case "y": {
            if (state.pendingOperator === "y") {
              const repeatCount2 = getCurrentCount();
              executeCommand(CMD_TYPES.YANK_LINE, repeatCount2);
              dispatch({
                type: "SET_LAST_COMMAND",
                command: { type: CMD_TYPES.YANK_LINE, count: repeatCount2 }
              });
              dispatch({ type: "CLEAR_COUNT" });
              dispatch({ type: "SET_PENDING_OPERATOR", operator: null });
            } else if (state.pendingOperator === null) {
              dispatch({ type: "SET_PENDING_OPERATOR", operator: "y" });
            } else {
              dispatch({ type: "CLEAR_PENDING_STATES" });
            }
            return true;
          }
          case "Y": {
            const repeatCount2 = getCurrentCount();
            executeCommand(CMD_TYPES.YANK_TO_EOL, repeatCount2);
            dispatch({
              type: "SET_LAST_COMMAND",
              command: { type: CMD_TYPES.YANK_TO_EOL, count: repeatCount2 }
            });
            dispatch({ type: "CLEAR_COUNT" });
            return true;
          }
          case "p": {
            executeCommand(CMD_TYPES.PASTE_AFTER, repeatCount);
            dispatch({
              type: "SET_LAST_COMMAND",
              command: { type: CMD_TYPES.PASTE_AFTER, count: repeatCount }
            });
            dispatch({ type: "CLEAR_COUNT" });
            return true;
          }
          case "P": {
            executeCommand(CMD_TYPES.PASTE_BEFORE, repeatCount);
            dispatch({
              type: "SET_LAST_COMMAND",
              command: { type: CMD_TYPES.PASTE_BEFORE, count: repeatCount }
            });
            dispatch({ type: "CLEAR_COUNT" });
            return true;
          }
          case "D": {
            executeCommand(CMD_TYPES.DELETE_TO_EOL, repeatCount);
            dispatch({
              type: "SET_LAST_COMMAND",
              command: { type: CMD_TYPES.DELETE_TO_EOL, count: repeatCount }
            });
            dispatch({ type: "CLEAR_COUNT" });
            return true;
          }
          case "C": {
            executeCommand(CMD_TYPES.CHANGE_TO_EOL, repeatCount);
            dispatch({
              type: "SET_LAST_COMMAND",
              command: { type: CMD_TYPES.CHANGE_TO_EOL, count: repeatCount }
            });
            dispatch({ type: "CLEAR_COUNT" });
            return true;
          }
          case "u": {
            for (let i = 0; i < repeatCount; i++) {
              buffer.undo();
            }
            dispatch({ type: "CLEAR_COUNT" });
            return true;
          }
          case ".": {
            if (state.lastCommand) {
              const cmdData = state.lastCommand;
              const count = state.count > 0 ? state.count : cmdData.count;
              executeCommand(cmdData.type, count, cmdData.char);
            }
            dispatch({ type: "CLEAR_COUNT" });
            return true;
          }
          default: {
            if (normalizedKey.name === "left") {
              if (state.pendingOperator === "d") {
                return handleDeleteMovement("h");
              }
              if (state.pendingOperator === "c") {
                return handleChangeMovement("h");
              }
              buffer.vimMoveLeft(repeatCount);
              dispatch({ type: "CLEAR_COUNT" });
              return true;
            }
            if (normalizedKey.name === "down") {
              if (state.pendingOperator === "d") {
                return handleDeleteMovement("j");
              }
              if (state.pendingOperator === "c") {
                return handleChangeMovement("j");
              }
              buffer.vimMoveDown(repeatCount);
              dispatch({ type: "CLEAR_COUNT" });
              return true;
            }
            if (normalizedKey.name === "up") {
              if (state.pendingOperator === "d") {
                return handleDeleteMovement("k");
              }
              if (state.pendingOperator === "c") {
                return handleChangeMovement("k");
              }
              buffer.vimMoveUp(repeatCount);
              dispatch({ type: "CLEAR_COUNT" });
              return true;
            }
            if (normalizedKey.name === "right") {
              if (state.pendingOperator === "d") {
                return handleDeleteMovement("l");
              }
              if (state.pendingOperator === "c") {
                return handleChangeMovement("l");
              }
              buffer.vimMoveRight(repeatCount);
              dispatch({ type: "CLEAR_COUNT" });
              return true;
            }
            dispatch({ type: "CLEAR_PENDING_STATES" });
            return false;
          }
        }
      }
      return false;
    },
    [
      vimEnabled,
      normalizeKey,
      handleInsertModeInput,
      state.mode,
      state.count,
      state.pendingOperator,
      state.pendingFindOp,
      state.lastCommand,
      state.lastFind,
      dispatch,
      getCurrentCount,
      handleChangeMovement,
      handleDeleteMovement,
      handleOperatorMotion,
      buffer,
      executeCommand,
      updateMode,
      checkDoubleEscape,
      keyMatchers
    ]
  );
  return {
    mode: state.mode,
    vimModeEnabled: vimEnabled,
    handleInput
    // Expose the input handler for InputPrompt to use
  };
}

// packages/cli/src/ui/hooks/useTimer.ts
var import_react110 = __toESM(require_react(), 1);
var useTimer = (isActive, resetKey) => {
  const [elapsedTime, setElapsedTime] = (0, import_react110.useState)(0);
  const timerRef = (0, import_react110.useRef)(null);
  const prevResetKeyRef = (0, import_react110.useRef)(resetKey);
  const prevIsActiveRef = (0, import_react110.useRef)(isActive);
  (0, import_react110.useEffect)(() => {
    let shouldResetTime = false;
    if (prevResetKeyRef.current !== resetKey) {
      shouldResetTime = true;
      prevResetKeyRef.current = resetKey;
    }
    if (prevIsActiveRef.current === false && isActive) {
      shouldResetTime = true;
    }
    if (shouldResetTime) {
      setElapsedTime(0);
    }
    prevIsActiveRef.current = isActive;
    if (isActive) {
      if (timerRef.current) {
        clearInterval(timerRef.current);
      }
      timerRef.current = setInterval(() => {
        setElapsedTime((prev) => prev + 1);
      }, 1e3);
    } else {
      if (timerRef.current) {
        clearInterval(timerRef.current);
        timerRef.current = null;
      }
    }
    return () => {
      if (timerRef.current) {
        clearInterval(timerRef.current);
        timerRef.current = null;
      }
    };
  }, [isActive, resetKey]);
  return elapsedTime;
};

// packages/cli/src/ui/hooks/useLoadingIndicator.ts
var import_react111 = __toESM(require_react(), 1);
var LOW_VERBOSITY_RETRY_HINT_ATTEMPT_THRESHOLD = 2;
var useLoadingIndicator = ({
  streamingState,
  shouldShowFocusHint,
  retryStatus,
  showTips = true,
  showWit = false,
  customWittyPhrases,
  errorVerbosity = "full",
  maxLength
}) => {
  const [timerResetKey, setTimerResetKey] = (0, import_react111.useState)(0);
  const isTimerActive = streamingState === "responding" /* Responding */;
  const elapsedTimeFromTimer = useTimer(isTimerActive, timerResetKey);
  const isPhraseCyclingActive = streamingState === "responding" /* Responding */;
  const isWaiting = streamingState === "waiting_for_confirmation" /* WaitingForConfirmation */;
  const { currentTip, currentWittyPhrase } = usePhraseCycler(
    isPhraseCyclingActive,
    isWaiting,
    shouldShowFocusHint,
    showTips,
    showWit,
    customWittyPhrases,
    maxLength
  );
  const [retainedElapsedTime, setRetainedElapsedTime] = (0, import_react111.useState)(0);
  const prevStreamingStateRef = (0, import_react111.useRef)(null);
  (0, import_react111.useEffect)(() => {
    if (prevStreamingStateRef.current === "waiting_for_confirmation" /* WaitingForConfirmation */ && streamingState === "responding" /* Responding */) {
      setTimerResetKey((prevKey) => prevKey + 1);
      setRetainedElapsedTime(0);
    } else if (streamingState === "idle" /* Idle */ && prevStreamingStateRef.current === "responding" /* Responding */) {
      setTimerResetKey((prevKey) => prevKey + 1);
      setRetainedElapsedTime(0);
    } else if (streamingState === "waiting_for_confirmation" /* WaitingForConfirmation */) {
      setRetainedElapsedTime(elapsedTimeFromTimer);
    }
    prevStreamingStateRef.current = streamingState;
  }, [streamingState, elapsedTimeFromTimer]);
  const retryPhrase = streamingState === "responding" /* Responding */ && retryStatus ? errorVerbosity === "low" ? retryStatus.attempt >= LOW_VERBOSITY_RETRY_HINT_ATTEMPT_THRESHOLD ? "This is taking a bit longer, we're still on it." : null : `Trying to reach ${getDisplayString(retryStatus.model)} (Attempt ${retryStatus.attempt + 1}/${retryStatus.maxAttempts})` : null;
  return {
    elapsedTime: streamingState === "waiting_for_confirmation" /* WaitingForConfirmation */ ? retainedElapsedTime : elapsedTimeFromTimer,
    currentLoadingPhrase: retryPhrase || currentTip || currentWittyPhrase,
    currentTip,
    currentWittyPhrase
  };
};

// packages/cli/src/ui/hooks/useTurnActivityMonitor.ts
var import_react112 = __toESM(require_react(), 1);
var useTurnActivityMonitor = (streamingState, activePtyId, pendingToolCalls = []) => {
  const [operationStartTime, setOperationStartTime] = (0, import_react112.useState)(0);
  const prevPtyIdRef = (0, import_react112.useRef)(void 0);
  const prevStreamingStateRef = (0, import_react112.useRef)(void 0);
  (0, import_react112.useEffect)(() => {
    const isNowResponding = streamingState === "responding" /* Responding */;
    const wasResponding = prevStreamingStateRef.current === "responding" /* Responding */;
    const ptyChanged = activePtyId !== prevPtyIdRef.current;
    if (isNowResponding && (!wasResponding || ptyChanged)) {
      setOperationStartTime(Date.now());
    } else if (!isNowResponding && wasResponding) {
      setOperationStartTime(0);
    }
    prevPtyIdRef.current = activePtyId;
    prevStreamingStateRef.current = streamingState;
  }, [streamingState, activePtyId]);
  const isRedirectionActive = (0, import_react112.useMemo)(
    () => (
      // Check active tool calls for run_shell_command
      pendingToolCalls.some((tc) => {
        if (tc.request.name !== "run_shell_command") return false;
        const command = tc.request.args?.command || "";
        return hasRedirection(command);
      })
    ),
    [pendingToolCalls]
  );
  return {
    operationStartTime,
    isRedirectionActive
  };
};

// packages/cli/src/ui/hooks/useShellInactivityStatus.ts
var useShellInactivityStatus = ({
  activePtyId,
  lastOutputTime,
  streamingState,
  pendingToolCalls,
  embeddedShellFocused,
  isInteractiveShellEnabled
}) => {
  const { operationStartTime, isRedirectionActive } = useTurnActivityMonitor(
    streamingState,
    activePtyId,
    pendingToolCalls
  );
  const isAwaitingFocus = !!activePtyId && !embeddedShellFocused && isInteractiveShellEnabled;
  const hasProducedOutput = lastOutputTime > operationStartTime;
  const shouldShowFocusHint = useInactivityTimer(
    isAwaitingFocus && !isRedirectionActive,
    lastOutputTime,
    hasProducedOutput ? SHELL_FOCUS_HINT_DELAY_MS : SHELL_FOCUS_HINT_DELAY_MS * 4
  );
  const shouldShowActionRequiredTitle = useInactivityTimer(
    isAwaitingFocus && !isRedirectionActive && hasProducedOutput,
    lastOutputTime,
    SHELL_ACTION_REQUIRED_TITLE_DELAY_MS
  );
  const shouldShowSilentWorkingTitle = useInactivityTimer(
    isAwaitingFocus && (isRedirectionActive || !hasProducedOutput),
    lastOutputTime,
    isRedirectionActive ? SHELL_SILENT_WORKING_TITLE_DELAY_MS : SHELL_ACTION_REQUIRED_TITLE_DELAY_MS * 2
  );
  let inactivityStatus = "none";
  if (shouldShowActionRequiredTitle) {
    inactivityStatus = "action_required";
  } else if (shouldShowSilentWorkingTitle) {
    inactivityStatus = "silent_working";
  }
  return {
    shouldShowFocusHint,
    inactivityStatus
  };
};

// packages/cli/src/ui/hooks/useFolderTrust.ts
var import_react113 = __toESM(require_react(), 1);
import * as process12 from "node:process";
var useFolderTrust = (settings, onTrustChange, addItem) => {
  const [isTrusted, setIsTrusted] = (0, import_react113.useState)(void 0);
  const [isFolderTrustDialogOpen, setIsFolderTrustDialogOpen] = (0, import_react113.useState)(false);
  const [discoveryResults, setDiscoveryResults] = (0, import_react113.useState)(null);
  const [isRestarting, setIsRestarting] = (0, import_react113.useState)(false);
  const startupMessageSent = (0, import_react113.useRef)(false);
  const folderTrust = settings.merged.security.folderTrust.enabled ?? true;
  (0, import_react113.useEffect)(() => {
    let isMounted = true;
    const { isTrusted: trusted } = isWorkspaceTrusted(settings.merged);
    if (trusted === void 0 || trusted === false) {
      void FolderTrustDiscoveryService.discover(process12.cwd()).then((results) => {
        if (isMounted) {
          setDiscoveryResults(results);
        }
      }).catch(() => {
      });
    }
    const showUntrustedMessage = () => {
      if (trusted === false && !startupMessageSent.current) {
        addItem(
          {
            type: "info" /* INFO */,
            text: "This folder is untrusted, project settings, hooks, MCPs, and GEMINI.md files will not be applied for this folder.\nUse the `/permissions` command to change the trust level."
          },
          Date.now()
        );
        startupMessageSent.current = true;
      }
    };
    if (isHeadlessMode()) {
      if (isMounted) {
        setIsTrusted(trusted);
        setIsFolderTrustDialogOpen(false);
        onTrustChange(true);
        showUntrustedMessage();
      }
    } else if (isMounted) {
      setIsTrusted(trusted);
      setIsFolderTrustDialogOpen(trusted === void 0);
      onTrustChange(trusted);
      showUntrustedMessage();
    }
    return () => {
      isMounted = false;
    };
  }, [folderTrust, onTrustChange, settings.merged, addItem]);
  const handleFolderTrustSelect = (0, import_react113.useCallback)(
    async (choice) => {
      const trustLevelMap = {
        ["trust_folder" /* TRUST_FOLDER */]: "TRUST_FOLDER" /* TRUST_FOLDER */,
        ["trust_parent" /* TRUST_PARENT */]: "TRUST_PARENT" /* TRUST_PARENT */,
        ["do_not_trust" /* DO_NOT_TRUST */]: "DO_NOT_TRUST" /* DO_NOT_TRUST */
      };
      const trustLevel = trustLevelMap[choice];
      if (!trustLevel) return;
      const cwd5 = process12.cwd();
      const trustedFolders = loadTrustedFolders();
      try {
        await trustedFolders.setValue(cwd5, trustLevel);
      } catch {
        coreEvents.emitFeedback(
          "error",
          "Failed to save trust settings. Exiting Gemini CLI."
        );
        setTimeout(async () => {
          await runExitCleanup();
          process12.exit(ExitCodes.FATAL_CONFIG_ERROR);
        }, 100);
        return;
      }
      const currentIsTrusted = trustLevel === "TRUST_FOLDER" /* TRUST_FOLDER */ || trustLevel === "TRUST_PARENT" /* TRUST_PARENT */;
      onTrustChange(currentIsTrusted);
      setIsTrusted(currentIsTrusted);
      const wasTrusted = isTrusted ?? false;
      if (wasTrusted !== currentIsTrusted) {
        setIsRestarting(true);
        setIsFolderTrustDialogOpen(true);
      } else {
        setIsFolderTrustDialogOpen(false);
      }
    },
    [onTrustChange, isTrusted]
  );
  return {
    isTrusted,
    isFolderTrustDialogOpen,
    discoveryResults,
    handleFolderTrustSelect,
    isRestarting
  };
};

// node_modules/ky/distribution/errors/HTTPError.js
var HTTPError = class extends Error {
  response;
  request;
  options;
  constructor(response, request, options) {
    const code = response.status || response.status === 0 ? response.status : "";
    const title = response.statusText ?? "";
    const status = `${code} ${title}`.trim();
    const reason = status ? `status code ${status}` : "an unknown error";
    super(`Request failed with ${reason}: ${request.method} ${request.url}`);
    this.name = "HTTPError";
    this.response = response;
    this.request = request;
    this.options = options;
  }
};

// node_modules/ky/distribution/errors/NonError.js
var NonError = class extends Error {
  name = "NonError";
  value;
  constructor(value) {
    let message = "Non-error value was thrown";
    try {
      if (typeof value === "string") {
        message = value;
      } else if (value && typeof value === "object" && "message" in value && typeof value.message === "string") {
        message = value.message;
      }
    } catch {
    }
    super(message);
    this.value = value;
  }
};

// node_modules/ky/distribution/core/constants.js
var supportsRequestStreams = (() => {
  let duplexAccessed = false;
  let hasContentType = false;
  const supportsReadableStream = typeof globalThis.ReadableStream === "function";
  const supportsRequest = typeof globalThis.Request === "function";
  if (supportsReadableStream && supportsRequest) {
    try {
      hasContentType = new globalThis.Request("https://empty.invalid", {
        body: new globalThis.ReadableStream(),
        method: "POST",
        // @ts-expect-error - Types are outdated.
        get duplex() {
          duplexAccessed = true;
          return "half";
        }
      }).headers.has("Content-Type");
    } catch (error) {
      if (error instanceof Error && error.message === "unsupported BodyInit type") {
        return false;
      }
      throw error;
    }
  }
  return duplexAccessed && !hasContentType;
})();
var supportsAbortController = typeof globalThis.AbortController === "function";
var supportsAbortSignal = typeof globalThis.AbortSignal === "function" && typeof globalThis.AbortSignal.any === "function";
var supportsResponseStreams = typeof globalThis.ReadableStream === "function";
var supportsFormData = typeof globalThis.FormData === "function";
var requestMethods = ["get", "post", "put", "patch", "head", "delete"];
var validate = () => void 0;
validate();
var responseTypes = {
  json: "application/json",
  text: "text/*",
  formData: "multipart/form-data",
  arrayBuffer: "*/*",
  blob: "*/*",
  // Supported in modern Fetch implementations (for example, browsers and recent Node.js/undici).
  // We still feature-check at runtime before exposing the shortcut.
  bytes: "*/*"
};
var maxSafeTimeout = 2147483647;
var usualFormBoundarySize = new TextEncoder().encode("------WebKitFormBoundaryaxpyiPgbbPti10Rw").length;
var stop = Symbol("stop");
var kyOptionKeys = {
  json: true,
  parseJson: true,
  stringifyJson: true,
  searchParams: true,
  prefixUrl: true,
  retry: true,
  timeout: true,
  hooks: true,
  throwHttpErrors: true,
  onDownloadProgress: true,
  onUploadProgress: true,
  fetch: true,
  context: true
};
var vendorSpecificOptions = {
  next: true
  // Next.js cache revalidation (revalidate, tags)
};
var requestOptionsRegistry = {
  method: true,
  headers: true,
  body: true,
  mode: true,
  credentials: true,
  cache: true,
  redirect: true,
  referrer: true,
  referrerPolicy: true,
  integrity: true,
  keepalive: true,
  signal: true,
  window: true,
  duplex: true
};

// node_modules/ky/distribution/utils/body.js
var getBodySize = (body) => {
  if (!body) {
    return 0;
  }
  if (body instanceof FormData) {
    let size = 0;
    for (const [key, value] of body) {
      size += usualFormBoundarySize;
      size += new TextEncoder().encode(`Content-Disposition: form-data; name="${key}"`).length;
      size += typeof value === "string" ? new TextEncoder().encode(value).length : value.size;
    }
    return size;
  }
  if (body instanceof Blob) {
    return body.size;
  }
  if (body instanceof ArrayBuffer) {
    return body.byteLength;
  }
  if (typeof body === "string") {
    return new TextEncoder().encode(body).length;
  }
  if (body instanceof URLSearchParams) {
    return new TextEncoder().encode(body.toString()).length;
  }
  if ("byteLength" in body) {
    return body.byteLength;
  }
  if (typeof body === "object" && body !== null) {
    try {
      const jsonString = JSON.stringify(body);
      return new TextEncoder().encode(jsonString).length;
    } catch {
      return 0;
    }
  }
  return 0;
};
var withProgress = (stream, totalBytes, onProgress) => {
  let previousChunk;
  let transferredBytes = 0;
  return stream.pipeThrough(new TransformStream({
    transform(currentChunk, controller) {
      controller.enqueue(currentChunk);
      if (previousChunk) {
        transferredBytes += previousChunk.byteLength;
        let percent = totalBytes === 0 ? 0 : transferredBytes / totalBytes;
        if (percent >= 1) {
          percent = 1 - Number.EPSILON;
        }
        onProgress?.({ percent, totalBytes: Math.max(totalBytes, transferredBytes), transferredBytes }, previousChunk);
      }
      previousChunk = currentChunk;
    },
    flush() {
      if (previousChunk) {
        transferredBytes += previousChunk.byteLength;
        onProgress?.({ percent: 1, totalBytes: Math.max(totalBytes, transferredBytes), transferredBytes }, previousChunk);
      }
    }
  }));
};
var streamResponse = (response, onDownloadProgress) => {
  if (!response.body) {
    return response;
  }
  if (response.status === 204) {
    return new Response(null, {
      status: response.status,
      statusText: response.statusText,
      headers: response.headers
    });
  }
  const totalBytes = Math.max(0, Number(response.headers.get("content-length")) || 0);
  return new Response(withProgress(response.body, totalBytes, onDownloadProgress), {
    status: response.status,
    statusText: response.statusText,
    headers: response.headers
  });
};
var streamRequest = (request, onUploadProgress, originalBody) => {
  if (!request.body) {
    return request;
  }
  const totalBytes = getBodySize(originalBody ?? request.body);
  return new Request(request, {
    // @ts-expect-error - Types are outdated.
    duplex: "half",
    body: withProgress(request.body, totalBytes, onUploadProgress)
  });
};

// node_modules/ky/distribution/utils/is.js
var isObject = (value) => value !== null && typeof value === "object";

// node_modules/ky/distribution/utils/merge.js
var validateAndMerge = (...sources) => {
  for (const source2 of sources) {
    if ((!isObject(source2) || Array.isArray(source2)) && source2 !== void 0) {
      throw new TypeError("The `options` argument must be an object");
    }
  }
  return deepMerge({}, ...sources);
};
var mergeHeaders = (source1 = {}, source2 = {}) => {
  const result = new globalThis.Headers(source1);
  const isHeadersInstance = source2 instanceof globalThis.Headers;
  const source3 = new globalThis.Headers(source2);
  for (const [key, value] of source3.entries()) {
    if (isHeadersInstance && value === "undefined" || value === void 0) {
      result.delete(key);
    } else {
      result.set(key, value);
    }
  }
  return result;
};
function newHookValue(original, incoming, property) {
  return Object.hasOwn(incoming, property) && incoming[property] === void 0 ? [] : deepMerge(original[property] ?? [], incoming[property] ?? []);
}
var mergeHooks = (original = {}, incoming = {}) => ({
  beforeRequest: newHookValue(original, incoming, "beforeRequest"),
  beforeRetry: newHookValue(original, incoming, "beforeRetry"),
  afterResponse: newHookValue(original, incoming, "afterResponse"),
  beforeError: newHookValue(original, incoming, "beforeError")
});
var appendSearchParameters = (target, source2) => {
  const result = new URLSearchParams();
  for (const input of [target, source2]) {
    if (input === void 0) {
      continue;
    }
    if (input instanceof URLSearchParams) {
      for (const [key, value] of input.entries()) {
        result.append(key, value);
      }
    } else if (Array.isArray(input)) {
      for (const pair of input) {
        if (!Array.isArray(pair) || pair.length !== 2) {
          throw new TypeError("Array search parameters must be provided in [[key, value], ...] format");
        }
        result.append(String(pair[0]), String(pair[1]));
      }
    } else if (isObject(input)) {
      for (const [key, value] of Object.entries(input)) {
        if (value !== void 0) {
          result.append(key, String(value));
        }
      }
    } else {
      const parameters = new URLSearchParams(input);
      for (const [key, value] of parameters.entries()) {
        result.append(key, value);
      }
    }
  }
  return result;
};
var deepMerge = (...sources) => {
  let returnValue = {};
  let headers = {};
  let hooks = {};
  let searchParameters;
  const signals = [];
  for (const source2 of sources) {
    if (Array.isArray(source2)) {
      if (!Array.isArray(returnValue)) {
        returnValue = [];
      }
      returnValue = [...returnValue, ...source2];
    } else if (isObject(source2)) {
      for (let [key, value] of Object.entries(source2)) {
        if (key === "signal" && value instanceof globalThis.AbortSignal) {
          signals.push(value);
          continue;
        }
        if (key === "context") {
          if (value !== void 0 && value !== null && (!isObject(value) || Array.isArray(value))) {
            throw new TypeError("The `context` option must be an object");
          }
          returnValue = {
            ...returnValue,
            context: value === void 0 || value === null ? {} : { ...returnValue.context, ...value }
          };
          continue;
        }
        if (key === "searchParams") {
          if (value === void 0 || value === null) {
            searchParameters = void 0;
          } else {
            searchParameters = searchParameters === void 0 ? value : appendSearchParameters(searchParameters, value);
          }
          continue;
        }
        if (isObject(value) && key in returnValue) {
          value = deepMerge(returnValue[key], value);
        }
        returnValue = { ...returnValue, [key]: value };
      }
      if (isObject(source2.hooks)) {
        hooks = mergeHooks(hooks, source2.hooks);
        returnValue.hooks = hooks;
      }
      if (isObject(source2.headers)) {
        headers = mergeHeaders(headers, source2.headers);
        returnValue.headers = headers;
      }
    }
  }
  if (searchParameters !== void 0) {
    returnValue.searchParams = searchParameters;
  }
  if (signals.length > 0) {
    if (signals.length === 1) {
      returnValue.signal = signals[0];
    } else if (supportsAbortSignal) {
      returnValue.signal = AbortSignal.any(signals);
    } else {
      returnValue.signal = signals.at(-1);
    }
  }
  if (returnValue.context === void 0) {
    returnValue.context = {};
  }
  return returnValue;
};

// node_modules/ky/distribution/utils/normalize.js
var normalizeRequestMethod = (input) => requestMethods.includes(input) ? input.toUpperCase() : input;
var retryMethods = ["get", "put", "head", "delete", "options", "trace"];
var retryStatusCodes = [408, 413, 429, 500, 502, 503, 504];
var retryAfterStatusCodes = [413, 429, 503];
var defaultRetryOptions = {
  limit: 2,
  methods: retryMethods,
  statusCodes: retryStatusCodes,
  afterStatusCodes: retryAfterStatusCodes,
  maxRetryAfter: Number.POSITIVE_INFINITY,
  backoffLimit: Number.POSITIVE_INFINITY,
  delay: (attemptCount) => 0.3 * 2 ** (attemptCount - 1) * 1e3,
  jitter: void 0,
  retryOnTimeout: false
};
var normalizeRetryOptions = (retry = {}) => {
  if (typeof retry === "number") {
    return {
      ...defaultRetryOptions,
      limit: retry
    };
  }
  if (retry.methods && !Array.isArray(retry.methods)) {
    throw new Error("retry.methods must be an array");
  }
  if (retry.statusCodes && !Array.isArray(retry.statusCodes)) {
    throw new Error("retry.statusCodes must be an array");
  }
  return {
    ...defaultRetryOptions,
    ...retry
  };
};

// node_modules/ky/distribution/errors/TimeoutError.js
var TimeoutError = class extends Error {
  request;
  constructor(request) {
    super(`Request timed out: ${request.method} ${request.url}`);
    this.name = "TimeoutError";
    this.request = request;
  }
};

// node_modules/ky/distribution/utils/timeout.js
async function timeout(request, init, abortController, options) {
  return new Promise((resolve3, reject) => {
    const timeoutId2 = setTimeout(() => {
      if (abortController) {
        abortController.abort();
      }
      reject(new TimeoutError(request));
    }, options.timeout);
    void options.fetch(request, init).then(resolve3).catch(reject).then(() => {
      clearTimeout(timeoutId2);
    });
  });
}

// node_modules/ky/distribution/utils/delay.js
async function delay(ms, { signal }) {
  return new Promise((resolve3, reject) => {
    if (signal) {
      signal.throwIfAborted();
      signal.addEventListener("abort", abortHandler, { once: true });
    }
    function abortHandler() {
      clearTimeout(timeoutId2);
      reject(signal.reason);
    }
    const timeoutId2 = setTimeout(() => {
      signal?.removeEventListener("abort", abortHandler);
      resolve3();
    }, ms);
  });
}

// node_modules/ky/distribution/utils/options.js
var findUnknownOptions = (request, options) => {
  const unknownOptions = {};
  for (const key in options) {
    if (!Object.hasOwn(options, key)) {
      continue;
    }
    if (!(key in requestOptionsRegistry) && !(key in kyOptionKeys) && (!(key in request) || key in vendorSpecificOptions)) {
      unknownOptions[key] = options[key];
    }
  }
  return unknownOptions;
};
var hasSearchParameters = (search) => {
  if (search === void 0) {
    return false;
  }
  if (Array.isArray(search)) {
    return search.length > 0;
  }
  if (search instanceof URLSearchParams) {
    return search.size > 0;
  }
  if (typeof search === "object") {
    return Object.keys(search).length > 0;
  }
  if (typeof search === "string") {
    return search.trim().length > 0;
  }
  return Boolean(search);
};

// node_modules/ky/distribution/utils/type-guards.js
function isHTTPError(error) {
  return error instanceof HTTPError || error?.name === HTTPError.name;
}
function isTimeoutError(error) {
  return error instanceof TimeoutError || error?.name === TimeoutError.name;
}

// node_modules/ky/distribution/core/Ky.js
var Ky = class _Ky {
  static create(input, options) {
    const ky2 = new _Ky(input, options);
    const function_ = async () => {
      if (typeof ky2.#options.timeout === "number" && ky2.#options.timeout > maxSafeTimeout) {
        throw new RangeError(`The \`timeout\` option cannot be greater than ${maxSafeTimeout}`);
      }
      await Promise.resolve();
      let response = await ky2.#fetch();
      for (const hook of ky2.#options.hooks.afterResponse) {
        const modifiedResponse = await hook(ky2.request, ky2.#getNormalizedOptions(), ky2.#decorateResponse(response.clone()), { retryCount: ky2.#retryCount });
        if (modifiedResponse instanceof globalThis.Response) {
          response = modifiedResponse;
        }
      }
      ky2.#decorateResponse(response);
      if (!response.ok && ky2.#options.throwHttpErrors) {
        let error = new HTTPError(response, ky2.request, ky2.#getNormalizedOptions());
        for (const hook of ky2.#options.hooks.beforeError) {
          error = await hook(error, { retryCount: ky2.#retryCount });
        }
        throw error;
      }
      if (ky2.#options.onDownloadProgress) {
        if (typeof ky2.#options.onDownloadProgress !== "function") {
          throw new TypeError("The `onDownloadProgress` option must be a function");
        }
        if (!supportsResponseStreams) {
          throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");
        }
        return streamResponse(response.clone(), ky2.#options.onDownloadProgress);
      }
      return response;
    };
    const isRetriableMethod = ky2.#options.retry.methods.includes(ky2.request.method.toLowerCase());
    const result = (isRetriableMethod ? ky2.#retry(function_) : function_()).finally(async () => {
      const originalRequest = ky2.#originalRequest;
      const cleanupPromises = [];
      if (originalRequest && !originalRequest.bodyUsed) {
        cleanupPromises.push(originalRequest.body?.cancel());
      }
      if (!ky2.request.bodyUsed) {
        cleanupPromises.push(ky2.request.body?.cancel());
      }
      await Promise.all(cleanupPromises);
    });
    for (const [type, mimeType] of Object.entries(responseTypes)) {
      if (type === "bytes" && typeof globalThis.Response?.prototype?.bytes !== "function") {
        continue;
      }
      result[type] = async () => {
        ky2.request.headers.set("accept", ky2.request.headers.get("accept") || mimeType);
        const response = await result;
        if (type === "json") {
          if (response.status === 204) {
            return "";
          }
          const text = await response.text();
          if (text === "") {
            return "";
          }
          if (options.parseJson) {
            return options.parseJson(text);
          }
          return JSON.parse(text);
        }
        return response[type]();
      };
    }
    return result;
  }
  // eslint-disable-next-line unicorn/prevent-abbreviations
  static #normalizeSearchParams(searchParams) {
    if (searchParams && typeof searchParams === "object" && !Array.isArray(searchParams) && !(searchParams instanceof URLSearchParams)) {
      return Object.fromEntries(Object.entries(searchParams).filter(([, value]) => value !== void 0));
    }
    return searchParams;
  }
  request;
  #abortController;
  #retryCount = 0;
  // eslint-disable-next-line @typescript-eslint/prefer-readonly -- False positive: #input is reassigned on line 202
  #input;
  #options;
  #originalRequest;
  #userProvidedAbortSignal;
  #cachedNormalizedOptions;
  // eslint-disable-next-line complexity
  constructor(input, options = {}) {
    this.#input = input;
    this.#options = {
      ...options,
      headers: mergeHeaders(this.#input.headers, options.headers),
      hooks: mergeHooks({
        beforeRequest: [],
        beforeRetry: [],
        beforeError: [],
        afterResponse: []
      }, options.hooks),
      method: normalizeRequestMethod(options.method ?? this.#input.method ?? "GET"),
      // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
      prefixUrl: String(options.prefixUrl || ""),
      retry: normalizeRetryOptions(options.retry),
      throwHttpErrors: options.throwHttpErrors !== false,
      timeout: options.timeout ?? 1e4,
      fetch: options.fetch ?? globalThis.fetch.bind(globalThis),
      context: options.context ?? {}
    };
    if (typeof this.#input !== "string" && !(this.#input instanceof URL || this.#input instanceof globalThis.Request)) {
      throw new TypeError("`input` must be a string, URL, or Request");
    }
    if (this.#options.prefixUrl && typeof this.#input === "string") {
      if (this.#input.startsWith("/")) {
        throw new Error("`input` must not begin with a slash when using `prefixUrl`");
      }
      if (!this.#options.prefixUrl.endsWith("/")) {
        this.#options.prefixUrl += "/";
      }
      this.#input = this.#options.prefixUrl + this.#input;
    }
    if (supportsAbortController && supportsAbortSignal) {
      this.#userProvidedAbortSignal = this.#options.signal ?? this.#input.signal;
      this.#abortController = new globalThis.AbortController();
      this.#options.signal = this.#userProvidedAbortSignal ? AbortSignal.any([this.#userProvidedAbortSignal, this.#abortController.signal]) : this.#abortController.signal;
    }
    if (supportsRequestStreams) {
      this.#options.duplex = "half";
    }
    if (this.#options.json !== void 0) {
      this.#options.body = this.#options.stringifyJson?.(this.#options.json) ?? JSON.stringify(this.#options.json);
      this.#options.headers.set("content-type", this.#options.headers.get("content-type") ?? "application/json");
    }
    const userProvidedContentType = options.headers && new globalThis.Headers(options.headers).has("content-type");
    if (this.#input instanceof globalThis.Request && (supportsFormData && this.#options.body instanceof globalThis.FormData || this.#options.body instanceof URLSearchParams) && !userProvidedContentType) {
      this.#options.headers.delete("content-type");
    }
    this.request = new globalThis.Request(this.#input, this.#options);
    if (hasSearchParameters(this.#options.searchParams)) {
      const textSearchParams = typeof this.#options.searchParams === "string" ? this.#options.searchParams.replace(/^\?/, "") : new URLSearchParams(_Ky.#normalizeSearchParams(this.#options.searchParams)).toString();
      const searchParams = "?" + textSearchParams;
      const url2 = this.request.url.replace(/(?:\?.*?)?(?=#|$)/, searchParams);
      this.request = new globalThis.Request(new globalThis.Request(url2, { ...this.request }), this.#options);
    }
    if (this.#options.onUploadProgress) {
      if (typeof this.#options.onUploadProgress !== "function") {
        throw new TypeError("The `onUploadProgress` option must be a function");
      }
      if (!supportsRequestStreams) {
        throw new Error("Request streams are not supported in your environment. The `duplex` option for `Request` is not available.");
      }
      const originalBody = this.request.body;
      if (originalBody) {
        this.request = streamRequest(this.request, this.#options.onUploadProgress, this.#options.body);
      }
    }
  }
  #calculateDelay() {
    const retryDelay = this.#options.retry.delay(this.#retryCount);
    let jitteredDelay = retryDelay;
    if (this.#options.retry.jitter === true) {
      jitteredDelay = Math.random() * retryDelay;
    } else if (typeof this.#options.retry.jitter === "function") {
      jitteredDelay = this.#options.retry.jitter(retryDelay);
      if (!Number.isFinite(jitteredDelay) || jitteredDelay < 0) {
        jitteredDelay = retryDelay;
      }
    }
    return Math.min(this.#options.retry.backoffLimit, jitteredDelay);
  }
  async #calculateRetryDelay(error) {
    this.#retryCount++;
    if (this.#retryCount > this.#options.retry.limit) {
      throw error;
    }
    const errorObject = error instanceof Error ? error : new NonError(error);
    if (this.#options.retry.shouldRetry !== void 0) {
      const result = await this.#options.retry.shouldRetry({ error: errorObject, retryCount: this.#retryCount });
      if (result === false) {
        throw error;
      }
      if (result === true) {
        return this.#calculateDelay();
      }
    }
    if (isTimeoutError(error) && !this.#options.retry.retryOnTimeout) {
      throw error;
    }
    if (isHTTPError(error)) {
      if (!this.#options.retry.statusCodes.includes(error.response.status)) {
        throw error;
      }
      const retryAfter = error.response.headers.get("Retry-After") ?? error.response.headers.get("RateLimit-Reset") ?? error.response.headers.get("X-RateLimit-Retry-After") ?? error.response.headers.get("X-RateLimit-Reset") ?? error.response.headers.get("X-Rate-Limit-Reset");
      if (retryAfter && this.#options.retry.afterStatusCodes.includes(error.response.status)) {
        let after = Number(retryAfter) * 1e3;
        if (Number.isNaN(after)) {
          after = Date.parse(retryAfter) - Date.now();
        } else if (after >= Date.parse("2024-01-01")) {
          after -= Date.now();
        }
        const max = this.#options.retry.maxRetryAfter ?? after;
        return after < max ? after : max;
      }
      if (error.response.status === 413) {
        throw error;
      }
    }
    return this.#calculateDelay();
  }
  #decorateResponse(response) {
    if (this.#options.parseJson) {
      response.json = async () => this.#options.parseJson(await response.text());
    }
    return response;
  }
  async #retry(function_) {
    try {
      return await function_();
    } catch (error) {
      const ms = Math.min(await this.#calculateRetryDelay(error), maxSafeTimeout);
      if (this.#retryCount < 1) {
        throw error;
      }
      await delay(ms, this.#userProvidedAbortSignal ? { signal: this.#userProvidedAbortSignal } : {});
      for (const hook of this.#options.hooks.beforeRetry) {
        const hookResult = await hook({
          request: this.request,
          options: this.#getNormalizedOptions(),
          error,
          retryCount: this.#retryCount
        });
        if (hookResult instanceof globalThis.Request) {
          this.request = hookResult;
          break;
        }
        if (hookResult instanceof globalThis.Response) {
          return hookResult;
        }
        if (hookResult === stop) {
          return;
        }
      }
      return this.#retry(function_);
    }
  }
  async #fetch() {
    if (this.#abortController?.signal.aborted) {
      this.#abortController = new globalThis.AbortController();
      this.#options.signal = this.#userProvidedAbortSignal ? AbortSignal.any([this.#userProvidedAbortSignal, this.#abortController.signal]) : this.#abortController.signal;
      this.request = new globalThis.Request(this.request, { signal: this.#options.signal });
    }
    for (const hook of this.#options.hooks.beforeRequest) {
      const result = await hook(this.request, this.#getNormalizedOptions(), { retryCount: this.#retryCount });
      if (result instanceof Request) {
        this.request = result;
        break;
      }
      if (result instanceof Response) {
        return result;
      }
    }
    const nonRequestOptions = findUnknownOptions(this.request, this.#options);
    this.#originalRequest = this.request;
    this.request = this.#originalRequest.clone();
    if (this.#options.timeout === false) {
      return this.#options.fetch(this.#originalRequest, nonRequestOptions);
    }
    return timeout(this.#originalRequest, nonRequestOptions, this.#abortController, this.#options);
  }
  #getNormalizedOptions() {
    if (!this.#cachedNormalizedOptions) {
      const { hooks, ...normalizedOptions } = this.#options;
      this.#cachedNormalizedOptions = Object.freeze(normalizedOptions);
    }
    return this.#cachedNormalizedOptions;
  }
};

// node_modules/ky/distribution/index.js
var createInstance = (defaults) => {
  const ky2 = (input, options) => Ky.create(input, validateAndMerge(defaults, options));
  for (const method of requestMethods) {
    ky2[method] = (input, options) => Ky.create(input, validateAndMerge(defaults, options, { method }));
  }
  ky2.create = (newDefaults) => createInstance(validateAndMerge(newDefaults));
  ky2.extend = (newDefaults) => {
    if (typeof newDefaults === "function") {
      newDefaults = newDefaults(defaults ?? {});
    }
    return createInstance(validateAndMerge(defaults, newDefaults));
  };
  ky2.stop = stop;
  return ky2;
};
var ky = createInstance();
var distribution_default = ky;

// node_modules/registry-url/index.js
var import_rc = __toESM(require_rc(), 1);
function registryUrl(scope) {
  const result = (0, import_rc.default)("npm", { registry: "https://registry.npmjs.org/" });
  const url2 = result[`${scope}:registry`] || result.config_registry || result.registry;
  return url2.slice(-1) === "/" ? url2 : `${url2}/`;
}

// node_modules/package-json/index.js
var import_registry_auth_token = __toESM(require_registry_auth_token(), 1);
var import_semver = __toESM(require_semver(), 1);
var PackageNotFoundError = class extends Error {
  constructor(packageName) {
    super(`Package \`${packageName}\` could not be found`);
    this.name = "PackageNotFoundError";
  }
};
var VersionNotFoundError = class extends Error {
  constructor(packageName, version) {
    super(`Version \`${version}\` for package \`${packageName}\` could not be found`);
    this.name = "VersionNotFoundError";
  }
};
async function packageJson(packageName, options = {}) {
  let { version = "latest" } = options;
  const { omitDeprecated = true } = options;
  const scope = packageName.split("/")[0];
  const registryUrl_ = options.registryUrl ?? registryUrl(scope);
  const packageUrl = new URL(encodeURIComponent(packageName).replace(/^%40/, "@"), registryUrl_);
  const authInfo = (0, import_registry_auth_token.default)(registryUrl_.toString(), { recursive: true });
  const headers = {
    accept: "application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*"
  };
  if (options.fullMetadata) {
    delete headers.accept;
  }
  if (authInfo) {
    headers.authorization = `${authInfo.type} ${authInfo.token}`;
  }
  let data;
  try {
    data = await distribution_default(packageUrl, { headers, keepalive: true }).json();
  } catch (error) {
    if (error?.response?.status === 404) {
      throw new PackageNotFoundError(packageName);
    }
    throw error;
  }
  if (options.allVersions) {
    return data;
  }
  const versionError = new VersionNotFoundError(packageName, version);
  if (data["dist-tags"][version]) {
    const { time } = data;
    data = data.versions[data["dist-tags"][version]];
    data.time = time;
  } else if (version) {
    const versionExists = Boolean(data.versions[version]);
    if (omitDeprecated && !versionExists) {
      for (const [metadataVersion, metadata] of Object.entries(data.versions)) {
        if (metadata.deprecated) {
          delete data.versions[metadataVersion];
        }
      }
    }
    if (!versionExists) {
      const versions = Object.keys(data.versions);
      version = import_semver.default.maxSatisfying(versions, version);
      if (!version) {
        throw versionError;
      }
    }
    const { time } = data;
    data = data.versions[version];
    data.time = time;
    if (!data) {
      throw versionError;
    }
  }
  return data;
}

// node_modules/latest-version/index.js
async function latestVersion(packageName, options) {
  const { version } = await packageJson(packageName.toLowerCase(), options);
  return version;
}

// packages/cli/src/ui/utils/updateCheck.ts
var import_semver2 = __toESM(require_semver(), 1);
import { fileURLToPath } from "node:url";
import path14 from "node:path";
var __filename = fileURLToPath(import.meta.url);
var __dirname2 = path14.dirname(__filename);
function getBestAvailableUpdate(nightly, stable) {
  if (!nightly) return stable || null;
  if (!stable) return nightly || null;
  if (import_semver2.default.coerce(stable)?.version === import_semver2.default.coerce(nightly)?.version) {
    return nightly;
  }
  return import_semver2.default.gt(stable, nightly) ? stable : nightly;
}
async function checkForUpdates(settings) {
  try {
    if (!settings.merged.general.enableAutoUpdateNotification) {
      return null;
    }
    if (false) {
      return null;
    }
    const packageJson2 = await getPackageJson(__dirname2);
    if (!packageJson2 || !packageJson2.name || !packageJson2.version) {
      return null;
    }
    const { name, version: currentVersion } = packageJson2;
    const isNightly = currentVersion.includes("nightly");
    if (isNightly) {
      const [nightlyUpdate, latestUpdate] = await Promise.all([
        latestVersion(name, { version: "nightly" }),
        latestVersion(name)
      ]);
      const bestUpdate = getBestAvailableUpdate(nightlyUpdate, latestUpdate);
      if (bestUpdate && import_semver2.default.gt(bestUpdate, currentVersion)) {
        const message = `A new version of Gemini CLI is available! ${currentVersion} \u2192 ${bestUpdate}`;
        const type = import_semver2.default.diff(bestUpdate, currentVersion) || void 0;
        return {
          message,
          update: {
            latest: bestUpdate,
            current: currentVersion,
            name,
            type
          }
        };
      }
    } else {
      const latestUpdate = await latestVersion(name);
      if (latestUpdate && import_semver2.default.gt(latestUpdate, currentVersion)) {
        const message = `Gemini CLI update available! ${currentVersion} \u2192 ${latestUpdate}`;
        const type = import_semver2.default.diff(latestUpdate, currentVersion) || void 0;
        return {
          message,
          update: {
            latest: latestUpdate,
            current: currentVersion,
            name,
            type
          }
        };
      }
    }
    return null;
  } catch (e) {
    debugLogger.warn("Failed to check for updates: " + e);
    return null;
  }
}

// packages/cli/src/ui/hooks/useMessageQueue.ts
var import_react114 = __toESM(require_react(), 1);
function useMessageQueue({
  isConfigInitialized,
  streamingState,
  submitQuery,
  isMcpReady
}) {
  const [messageQueue2, setMessageQueue] = (0, import_react114.useState)([]);
  const addMessage = (0, import_react114.useCallback)((message) => {
    const trimmedMessage = message.trim();
    if (trimmedMessage.length > 0) {
      setMessageQueue((prev) => [...prev, trimmedMessage]);
    }
  }, []);
  const clearQueue = (0, import_react114.useCallback)(() => {
    setMessageQueue([]);
  }, []);
  const getQueuedMessagesText = (0, import_react114.useCallback)(() => {
    if (messageQueue2.length === 0) return "";
    return messageQueue2.join("\n\n");
  }, [messageQueue2]);
  const popAllMessages = (0, import_react114.useCallback)(() => {
    if (messageQueue2.length === 0) {
      return void 0;
    }
    const allMessages = messageQueue2.join("\n\n");
    setMessageQueue([]);
    return allMessages;
  }, [messageQueue2]);
  (0, import_react114.useEffect)(() => {
    if (isConfigInitialized && streamingState === "idle" /* Idle */ && isMcpReady && messageQueue2.length > 0) {
      const combinedMessage = messageQueue2.join("\n\n");
      setMessageQueue([]);
      submitQuery(combinedMessage);
    }
  }, [
    isConfigInitialized,
    streamingState,
    isMcpReady,
    messageQueue2,
    submitQuery
  ]);
  return {
    messageQueue: messageQueue2,
    addMessage,
    clearQueue,
    getQueuedMessagesText,
    popAllMessages
  };
}

// packages/cli/src/ui/hooks/useMcpStatus.ts
var import_react115 = __toESM(require_react(), 1);
function useMcpStatus(config) {
  const [discoveryState, setDiscoveryState] = (0, import_react115.useState)(
    () => config.getMcpClientManager()?.getDiscoveryState() ?? MCPDiscoveryState.NOT_STARTED
  );
  const [mcpServerCount, setMcpServerCount] = (0, import_react115.useState)(
    () => config.getMcpClientManager()?.getMcpServerCount() ?? 0
  );
  (0, import_react115.useEffect)(() => {
    const onChange = () => {
      const manager = config.getMcpClientManager();
      if (manager) {
        setDiscoveryState(manager.getDiscoveryState());
        setMcpServerCount(manager.getMcpServerCount());
      }
    };
    coreEvents.on(CoreEvent.McpClientUpdate, onChange);
    return () => {
      coreEvents.off(CoreEvent.McpClientUpdate, onChange);
    };
  }, [config]);
  const isMcpReady = discoveryState === MCPDiscoveryState.COMPLETED || discoveryState === MCPDiscoveryState.NOT_STARTED && mcpServerCount === 0;
  return {
    discoveryState,
    mcpServerCount,
    isMcpReady
  };
}

// packages/cli/src/ui/hooks/useApprovalModeIndicator.ts
var import_react116 = __toESM(require_react(), 1);
function useApprovalModeIndicator({
  config,
  addItem,
  onApprovalModeChange,
  isActive = true,
  allowPlanMode = false
}) {
  const keyMatchers = useKeyMatchers();
  const currentConfigValue = config.getApprovalMode();
  const [showApprovalMode, setApprovalMode] = (0, import_react116.useState)(currentConfigValue);
  (0, import_react116.useEffect)(() => {
    setApprovalMode(currentConfigValue);
  }, [currentConfigValue]);
  useKeypress(
    (key) => {
      let nextApprovalMode;
      if (keyMatchers["app.toggleYolo" /* TOGGLE_YOLO */](key)) {
        if (config.isYoloModeDisabled() && config.getApprovalMode() !== ApprovalMode.YOLO) {
          if (addItem) {
            let text = "You cannot enter YOLO mode since it is disabled in your settings.";
            const adminSettings = config.getRemoteAdminSettings();
            const hasSettings = adminSettings && Object.keys(adminSettings).length > 0;
            if (hasSettings && !adminSettings.strictModeDisabled) {
              text = getAdminErrorMessage("YOLO mode", config);
            }
            addItem(
              {
                type: "warning" /* WARNING */,
                text
              },
              Date.now()
            );
          }
          return;
        }
        nextApprovalMode = config.getApprovalMode() === ApprovalMode.YOLO ? ApprovalMode.DEFAULT : ApprovalMode.YOLO;
      } else if (keyMatchers["app.cycleApprovalMode" /* CYCLE_APPROVAL_MODE */](key)) {
        const currentMode = config.getApprovalMode();
        switch (currentMode) {
          case ApprovalMode.DEFAULT:
            nextApprovalMode = ApprovalMode.AUTO_EDIT;
            break;
          case ApprovalMode.AUTO_EDIT:
            nextApprovalMode = allowPlanMode ? ApprovalMode.PLAN : ApprovalMode.DEFAULT;
            break;
          case ApprovalMode.PLAN:
            nextApprovalMode = ApprovalMode.DEFAULT;
            break;
          case ApprovalMode.YOLO:
            nextApprovalMode = ApprovalMode.AUTO_EDIT;
            break;
          default:
        }
      }
      if (nextApprovalMode) {
        try {
          config.setApprovalMode(nextApprovalMode);
          setApprovalMode(nextApprovalMode);
          onApprovalModeChange?.(nextApprovalMode);
        } catch (e) {
          if (addItem) {
            addItem(
              {
                type: "info" /* INFO */,
                // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
                text: e.message
              },
              Date.now()
            );
          }
        }
      }
    },
    { isActive }
  );
  return showApprovalMode;
}

// packages/cli/src/ui/hooks/useGitBranchName.ts
var import_react117 = __toESM(require_react(), 1);
import fs7 from "node:fs";
import fsPromises from "node:fs/promises";
import path15 from "node:path";
function useGitBranchName(cwd5) {
  const [branchName, setBranchName] = (0, import_react117.useState)(void 0);
  const fetchBranchName = (0, import_react117.useCallback)(async () => {
    try {
      const { stdout } = await spawnAsync(
        "git",
        ["rev-parse", "--abbrev-ref", "HEAD"],
        { cwd: cwd5 }
      );
      const branch = stdout.toString().trim();
      if (branch && branch !== "HEAD") {
        setBranchName(branch);
      } else {
        const { stdout: hashStdout } = await spawnAsync(
          "git",
          ["rev-parse", "--short", "HEAD"],
          { cwd: cwd5 }
        );
        setBranchName(hashStdout.toString().trim());
      }
    } catch {
      setBranchName(void 0);
    }
  }, [cwd5, setBranchName]);
  (0, import_react117.useEffect)(() => {
    fetchBranchName();
    const gitLogsHeadPath = path15.join(cwd5, ".git", "logs", "HEAD");
    let watcher;
    let cancelled = false;
    const setupWatcher = async () => {
      try {
        await fsPromises.access(gitLogsHeadPath, fs7.constants.F_OK);
        if (cancelled) return;
        watcher = fs7.watch(gitLogsHeadPath, (eventType) => {
          if (eventType === "change" || eventType === "rename") {
            fetchBranchName();
          }
        });
      } catch {
      }
    };
    setupWatcher();
    return () => {
      cancelled = true;
      watcher?.close();
    };
  }, [cwd5, fetchBranchName]);
  return branchName;
}

// packages/cli/src/ui/hooks/useSessionResume.ts
var import_react118 = __toESM(require_react(), 1);
function useSessionResume({
  config,
  historyManager,
  refreshStatic,
  isGeminiClientInitialized,
  setQuittingMessages,
  resumedSessionData,
  isAuthenticating
}) {
  const [isResuming, setIsResuming] = (0, import_react118.useState)(false);
  const historyManagerRef = (0, import_react118.useRef)(historyManager);
  const refreshStaticRef = (0, import_react118.useRef)(refreshStatic);
  (0, import_react118.useEffect)(() => {
    historyManagerRef.current = historyManager;
    refreshStaticRef.current = refreshStatic;
  });
  const loadHistoryForResume = (0, import_react118.useCallback)(
    async (uiHistory, clientHistory, resumedData) => {
      if (!isGeminiClientInitialized) {
        return;
      }
      setIsResuming(true);
      try {
        setQuittingMessages(null);
        historyManagerRef.current.clearItems();
        uiHistory.forEach((item, index) => {
          historyManagerRef.current.addItem(item, index, true);
        });
        refreshStaticRef.current();
        if (resumedData.conversation.directories && resumedData.conversation.directories.length > 0) {
          const workspaceContext = config.getWorkspaceContext();
          workspaceContext.addDirectories(resumedData.conversation.directories);
        }
        await config.getGeminiClient()?.resumeChat(clientHistory, resumedData);
      } catch (error) {
        coreEvents.emitFeedback(
          "error",
          "Failed to resume session. Please try again.",
          error
        );
      } finally {
        setIsResuming(false);
      }
    },
    [config, isGeminiClientInitialized, setQuittingMessages]
  );
  const hasLoadedResumedSession = (0, import_react118.useRef)(false);
  (0, import_react118.useEffect)(() => {
    if (resumedSessionData && !isAuthenticating && isGeminiClientInitialized && !hasLoadedResumedSession.current) {
      hasLoadedResumedSession.current = true;
      const historyData = convertSessionToHistoryFormats(
        resumedSessionData.conversation.messages
      );
      void loadHistoryForResume(
        historyData.uiHistory,
        convertSessionToClientHistory(resumedSessionData.conversation.messages),
        resumedSessionData
      );
    }
  }, [
    resumedSessionData,
    isAuthenticating,
    isGeminiClientInitialized,
    loadHistoryForResume
  ]);
  return { loadHistoryForResume, isResuming };
}

// packages/cli/src/ui/hooks/useIncludeDirsTrust.tsx
var import_react119 = __toESM(require_react(), 1);
var import_jsx_runtime140 = __toESM(require_jsx_runtime(), 1);
async function finishAddingDirectories(config, addItem, added, errors) {
  if (!config) {
    addItem({
      type: "error" /* ERROR */,
      text: "Configuration is not available."
    });
    return;
  }
  try {
    if (config.shouldLoadMemoryFromIncludeDirectories()) {
      await refreshServerHierarchicalMemory(config);
    }
  } catch (error) {
    errors.push(`Error refreshing memory: ${error.message}`);
  }
  if (added.length > 0) {
    const gemini = config.getGeminiClient();
    if (gemini) {
      await gemini.addDirectoryContext();
    }
  }
  if (errors.length > 0) {
    addItem({ type: "error" /* ERROR */, text: errors.join("\n") });
  }
}
function useIncludeDirsTrust(config, isTrustedFolder, historyManager, setCustomDialog) {
  const { addItem } = historyManager;
  (0, import_react119.useEffect)(() => {
    if (isTrustedFolder === void 0 || !config) {
      return;
    }
    const pendingDirs = config.getPendingIncludeDirectories();
    if (pendingDirs.length === 0) {
      return;
    }
    if (config.getFolderTrust() === false || isTrustedFolder === false) {
      const added2 = [];
      const errors2 = [];
      const workspaceContext2 = config.getWorkspaceContext();
      const result = batchAddDirectories(workspaceContext2, pendingDirs);
      added2.push(...result.added);
      errors2.push(...result.errors);
      if (added2.length > 0 || errors2.length > 0) {
        finishAddingDirectories(config, addItem, added2, errors2);
      }
      config.clearPendingIncludeDirectories();
      return;
    }
    const trustedFolders = loadTrustedFolders();
    const untrustedDirs = [];
    const undefinedTrustDirs = [];
    const trustedDirs = [];
    const added = [];
    const errors = [];
    for (const pathToAdd of pendingDirs) {
      const expandedPath = expandHomeDir(pathToAdd.trim());
      const isTrusted = trustedFolders.isPathTrusted(expandedPath);
      if (isTrusted === false) {
        untrustedDirs.push(pathToAdd.trim());
      } else if (isTrusted === void 0) {
        undefinedTrustDirs.push(pathToAdd.trim());
      } else {
        trustedDirs.push(pathToAdd.trim());
      }
    }
    if (untrustedDirs.length > 0) {
      errors.push(
        `The following directories are explicitly untrusted and cannot be added to a trusted workspace:
- ${untrustedDirs.join(
          "\n- "
        )}
Please use the permissions command to modify their trust level.`
      );
    }
    const workspaceContext = config.getWorkspaceContext();
    if (trustedDirs.length > 0) {
      const result = batchAddDirectories(workspaceContext, trustedDirs);
      added.push(...result.added);
      errors.push(...result.errors);
    }
    if (undefinedTrustDirs.length > 0) {
      debugLogger.log(
        "Creating custom dialog with undecidedDirs:",
        undefinedTrustDirs
      );
      setCustomDialog(
        /* @__PURE__ */ (0, import_jsx_runtime140.jsx)(
          MultiFolderTrustDialog,
          {
            folders: undefinedTrustDirs,
            onComplete: () => {
              setCustomDialog(null);
              config.clearPendingIncludeDirectories();
            },
            trustedDirs: added,
            errors,
            finishAddingDirectories,
            config,
            addItem
          }
        )
      );
    } else if (added.length > 0 || errors.length > 0) {
      finishAddingDirectories(config, addItem, added, errors);
      config.clearPendingIncludeDirectories();
    }
  }, [isTrustedFolder, config, addItem, setCustomDialog]);
}

// packages/cli/src/ui/hooks/useInputHistoryStore.ts
var import_react120 = __toESM(require_react(), 1);
function useInputHistoryStore() {
  const [inputHistory, setInputHistory] = (0, import_react120.useState)([]);
  const [_pastSessionMessages, setPastSessionMessages] = (0, import_react120.useState)([]);
  const [_currentSessionMessages, setCurrentSessionMessages] = (0, import_react120.useState)([]);
  const [isInitialized, setIsInitialized] = (0, import_react120.useState)(false);
  const recalculateHistory = (0, import_react120.useCallback)(
    (currentSession, pastSession) => {
      const combinedMessages = [...currentSession, ...pastSession];
      const deduplicatedMessages = [];
      if (combinedMessages.length > 0) {
        deduplicatedMessages.push(combinedMessages[0]);
        for (let i = 1; i < combinedMessages.length; i++) {
          if (combinedMessages[i] !== combinedMessages[i - 1]) {
            deduplicatedMessages.push(combinedMessages[i]);
          }
        }
      }
      setInputHistory(deduplicatedMessages.reverse());
    },
    []
  );
  const initializeFromLogger = (0, import_react120.useCallback)(
    async (logger) => {
      if (isInitialized || !logger) return;
      try {
        const pastMessages = await logger.getPreviousUserMessages() || [];
        setPastSessionMessages(pastMessages);
        recalculateHistory([], pastMessages);
        setIsInitialized(true);
      } catch (error) {
        debugLogger.warn(
          "Failed to initialize input history from logger:",
          error
        );
        setPastSessionMessages([]);
        recalculateHistory([], []);
        setIsInitialized(true);
      }
    },
    [isInitialized, recalculateHistory]
  );
  const addInput = (0, import_react120.useCallback)(
    (input) => {
      const trimmedInput = input.trim();
      if (!trimmedInput) return;
      setCurrentSessionMessages((prevCurrent) => {
        const newCurrentSession = [...prevCurrent, trimmedInput];
        setPastSessionMessages((prevPast) => {
          recalculateHistory(
            newCurrentSession.slice().reverse(),
            // Convert to newest first
            prevPast
          );
          return prevPast;
        });
        return newCurrentSession;
      });
    },
    [recalculateHistory]
  );
  return {
    inputHistory,
    addInput,
    initializeFromLogger
  };
}

// packages/cli/src/ui/hooks/useHookDisplayState.ts
var import_react121 = __toESM(require_react(), 1);
var useHookDisplayState = () => {
  const [activeHooks, setActiveHooks] = (0, import_react121.useState)([]);
  const hookStartTimes = (0, import_react121.useRef)(/* @__PURE__ */ new Map());
  const timeouts = (0, import_react121.useRef)(/* @__PURE__ */ new Set());
  (0, import_react121.useEffect)(() => {
    const activeTimeouts = timeouts.current;
    const startTimes = hookStartTimes.current;
    const handleHookStart = (payload) => {
      const key = `${payload.hookName}:${payload.eventName}`;
      const now = Date.now();
      if (!startTimes.has(key)) {
        startTimes.set(key, []);
      }
      startTimes.get(key).push(now);
      setActiveHooks((prev) => [
        ...prev,
        {
          name: payload.hookName,
          eventName: payload.eventName,
          source: payload.source,
          index: payload.hookIndex,
          total: payload.totalHooks
        }
      ]);
    };
    const handleHookEnd = (payload) => {
      const key = `${payload.hookName}:${payload.eventName}`;
      const starts = startTimes.get(key);
      const startTime = starts?.shift();
      if (starts && starts.length === 0) {
        startTimes.delete(key);
      }
      const now = Date.now();
      const elapsed = startTime ? now - startTime : WARNING_PROMPT_DURATION_MS;
      const remaining = WARNING_PROMPT_DURATION_MS - elapsed;
      const removeHook = () => {
        setActiveHooks((prev) => {
          const index = prev.findIndex(
            (h) => h.name === payload.hookName && h.eventName === payload.eventName
          );
          if (index === -1) return prev;
          const newHooks = [...prev];
          newHooks.splice(index, 1);
          return newHooks;
        });
      };
      if (remaining > 0) {
        const timeoutId2 = setTimeout(() => {
          removeHook();
          activeTimeouts.delete(timeoutId2);
        }, remaining);
        activeTimeouts.add(timeoutId2);
      } else {
        removeHook();
      }
    };
    coreEvents.on(CoreEvent.HookStart, handleHookStart);
    coreEvents.on(CoreEvent.HookEnd, handleHookEnd);
    return () => {
      coreEvents.off(CoreEvent.HookStart, handleHookStart);
      coreEvents.off(CoreEvent.HookEnd, handleHookEnd);
      activeTimeouts.forEach(clearTimeout);
      activeTimeouts.clear();
    };
  }, []);
  return activeHooks;
};

// packages/cli/src/ui/hooks/useBackgroundTaskManager.ts
var import_react122 = __toESM(require_react(), 1);
function useBackgroundTaskManager({
  backgroundTasks,
  backgroundTaskCount,
  isBackgroundTaskVisible,
  activePtyId,
  embeddedShellFocused,
  setEmbeddedShellFocused,
  terminalHeight
}) {
  const [isBackgroundTaskListOpen, setIsBackgroundTaskListOpen] = (0, import_react122.useState)(false);
  const [activeBackgroundTaskPid, setActiveBackgroundTaskPid] = (0, import_react122.useState)(null);
  (0, import_react122.useEffect)(() => {
    if (backgroundTasks.size === 0) {
      if (activeBackgroundTaskPid !== null) {
        setActiveBackgroundTaskPid(null);
      }
      if (isBackgroundTaskListOpen) {
        setIsBackgroundTaskListOpen(false);
      }
    } else if (activeBackgroundTaskPid === null || !backgroundTasks.has(activeBackgroundTaskPid)) {
      setActiveBackgroundTaskPid(backgroundTasks.keys().next().value ?? null);
    }
  }, [
    backgroundTasks,
    activeBackgroundTaskPid,
    backgroundTaskCount,
    isBackgroundTaskListOpen
  ]);
  (0, import_react122.useEffect)(() => {
    if (embeddedShellFocused) {
      const hasActiveForegroundShell = !!activePtyId;
      const hasVisibleBackgroundTask = isBackgroundTaskVisible && backgroundTasks.size > 0;
      if (!hasActiveForegroundShell && !hasVisibleBackgroundTask) {
        setEmbeddedShellFocused(false);
      }
    }
  }, [
    isBackgroundTaskVisible,
    backgroundTasks,
    embeddedShellFocused,
    backgroundTaskCount,
    activePtyId,
    setEmbeddedShellFocused
  ]);
  const backgroundTaskHeight = (0, import_react122.useMemo)(
    () => isBackgroundTaskVisible && backgroundTasks.size > 0 ? Math.max(Math.floor(terminalHeight * 0.3), 5) : 0,
    [isBackgroundTaskVisible, backgroundTasks.size, terminalHeight]
  );
  return {
    isBackgroundTaskListOpen,
    setIsBackgroundTaskListOpen,
    activeBackgroundTaskPid,
    setActiveBackgroundTaskPid,
    backgroundTaskHeight
  };
}

// packages/cli/src/ui/auth/LoginWithGoogleRestartDialog.tsx
var import_jsx_runtime141 = __toESM(require_jsx_runtime(), 1);
var LoginWithGoogleRestartDialog = ({
  onDismiss,
  config
}) => {
  useKeypress(
    (key) => {
      if (key.name === "escape") {
        onDismiss();
        return true;
      } else if (key.name === "r" || key.name === "R") {
        setTimeout(async () => {
          if (process.send) {
            const remoteSettings = config.getRemoteAdminSettings();
            if (remoteSettings) {
              process.send({
                type: "admin-settings-update",
                settings: remoteSettings
              });
            }
          }
          await relaunchApp();
        }, 100);
        return true;
      }
      return false;
    },
    { isActive: true }
  );
  const message = "You've successfully signed in with Google. Gemini CLI needs to be restarted.";
  return /* @__PURE__ */ (0, import_jsx_runtime141.jsx)(Box_default, { borderStyle: "round", borderColor: theme.status.warning, paddingX: 1, children: /* @__PURE__ */ (0, import_jsx_runtime141.jsxs)(Text, { color: theme.status.warning, children: [
    message,
    " Press R to restart, or Esc to choose a different authentication method."
  ] }) });
};

// packages/cli/src/ui/hooks/useTerminalTheme.ts
var import_react123 = __toESM(require_react(), 1);
function useTerminalTheme(handleThemeSelect, config, refreshStatic) {
  const settings = useSettings();
  const { subscribe: subscribe2, unsubscribe, queryTerminalBackground } = useTerminalContext();
  (0, import_react123.useEffect)(() => {
    if (settings.merged.ui.autoThemeSwitching === false) {
      return;
    }
    if (config.getTerminalBackground() === void 0) {
      return;
    }
    const pollIntervalId = setInterval(() => {
      const currentThemeName = settings.merged.ui.theme;
      if (!themeManager.isDefaultTheme(currentThemeName)) {
        return;
      }
      void queryTerminalBackground();
    }, settings.merged.ui.terminalBackgroundPollingInterval * 1e3);
    const handleTerminalBackground = (colorStr) => {
      const match = /^rgb:([0-9a-fA-F]{1,4})\/([0-9a-fA-F]{1,4})\/([0-9a-fA-F]{1,4})$/.exec(
        colorStr
      );
      if (!match) return;
      const hexColor = parseColor(match[1], match[2], match[3]);
      if (!hexColor) return;
      const previousColor = config.getTerminalBackground();
      const luminance = getLuminance(hexColor);
      const currentThemeName = settings.merged.ui.theme;
      const newTheme = shouldSwitchTheme(
        currentThemeName,
        luminance,
        DEFAULT_THEME.name,
        DefaultLight.name
      );
      if (previousColor === hexColor) {
        if (newTheme) {
          void handleThemeSelect(newTheme, "User" /* User */);
        }
        return;
      }
      config.setTerminalBackground(hexColor);
      themeManager.setTerminalBackground(hexColor);
      if (newTheme) {
        void handleThemeSelect(newTheme, "User" /* User */);
      } else {
        refreshStatic();
      }
    };
    subscribe2(handleTerminalBackground);
    return () => {
      clearInterval(pollIntervalId);
      unsubscribe(handleTerminalBackground);
    };
  }, [
    settings.merged.ui.theme,
    settings.merged.ui.autoThemeSwitching,
    settings.merged.ui.terminalBackgroundPollingInterval,
    config,
    handleThemeSelect,
    subscribe2,
    unsubscribe,
    queryTerminalBackground,
    refreshStatic
  ]);
}

// packages/cli/src/ui/hooks/useTimedMessage.ts
var import_react124 = __toESM(require_react(), 1);
function useTimedMessage(durationMs) {
  const [message, setMessage] = (0, import_react124.useState)(null);
  const timeoutRef = (0, import_react124.useRef)(null);
  const showMessage = (0, import_react124.useCallback)(
    (msg) => {
      setMessage(msg);
      if (timeoutRef.current) {
        clearTimeout(timeoutRef.current);
      }
      if (msg !== null) {
        timeoutRef.current = setTimeout(() => {
          setMessage(null);
        }, durationMs);
      }
    },
    [durationMs]
  );
  (0, import_react124.useEffect)(
    () => () => {
      if (timeoutRef.current) {
        clearTimeout(timeoutRef.current);
      }
    },
    []
  );
  return [message, showMessage];
}

// packages/cli/src/ui/hooks/useSuspend.ts
var import_react125 = __toESM(require_react(), 1);
import process13 from "node:process";
function useSuspend({
  handleWarning,
  setRawMode,
  refreshStatic,
  setForceRerenderKey,
  shouldUseAlternateScreen
}) {
  const [ctrlZPressCount, setCtrlZPressCount] = (0, import_react125.useState)(0);
  const ctrlZTimerRef = (0, import_react125.useRef)(null);
  const onResumeHandlerRef = (0, import_react125.useRef)(null);
  (0, import_react125.useEffect)(
    () => () => {
      if (ctrlZTimerRef.current) {
        clearTimeout(ctrlZTimerRef.current);
        ctrlZTimerRef.current = null;
      }
      if (onResumeHandlerRef.current) {
        process13.off("SIGCONT", onResumeHandlerRef.current);
        onResumeHandlerRef.current = null;
      }
    },
    []
  );
  (0, import_react125.useEffect)(() => {
    if (ctrlZTimerRef.current) {
      clearTimeout(ctrlZTimerRef.current);
      ctrlZTimerRef.current = null;
    }
    const suspendKey = formatCommand("app.suspend" /* SUSPEND_APP */);
    if (ctrlZPressCount > 1) {
      setCtrlZPressCount(0);
      if (process13.platform === "win32") {
        handleWarning(`${suspendKey} suspend is not supported on Windows.`);
        return;
      }
      if (shouldUseAlternateScreen) {
        exitAlternateScreen();
        enableLineWrapping();
        writeToStdout("\x1B[2J\x1B[H");
      }
      writeToStdout("\x1B[?25h");
      disableMouseEvents();
      cleanupTerminalOnExit();
      if (process13.stdin.isTTY) {
        process13.stdin.setRawMode(false);
      }
      setRawMode(false);
      const onResume = () => {
        try {
          if (process13.stdin.isTTY) {
            process13.stdin.setRawMode(true);
            process13.stdin.resume();
            process13.stdin.ref();
          }
          setRawMode(true);
          if (shouldUseAlternateScreen) {
            enterAlternateScreen();
            disableLineWrapping();
            writeToStdout("\x1B[2J\x1B[H");
          }
          terminalCapabilityManager.enableSupportedModes();
          writeToStdout("\x1B[?25l");
          if (shouldUseAlternateScreen) {
            enableMouseEvents();
          }
          process13.stdout.emit("resize");
          setImmediate(() => {
            refreshStatic();
            setForceRerenderKey((prev) => prev + 1);
          });
        } finally {
          if (onResumeHandlerRef.current === onResume) {
            onResumeHandlerRef.current = null;
          }
        }
      };
      if (onResumeHandlerRef.current) {
        process13.off("SIGCONT", onResumeHandlerRef.current);
      }
      onResumeHandlerRef.current = onResume;
      process13.once("SIGCONT", onResume);
      process13.kill(0, "SIGTSTP");
    } else if (ctrlZPressCount > 0) {
      const undoKey = formatCommand("edit.undo" /* UNDO */);
      handleWarning(
        `Press ${suspendKey} again to suspend. Undo has moved to ${undoKey}.`
      );
      ctrlZTimerRef.current = setTimeout(() => {
        setCtrlZPressCount(0);
        ctrlZTimerRef.current = null;
      }, WARNING_PROMPT_DURATION_MS);
    }
  }, [
    ctrlZPressCount,
    handleWarning,
    setRawMode,
    refreshStatic,
    setForceRerenderKey,
    shouldUseAlternateScreen
  ]);
  const handleSuspend = (0, import_react125.useCallback)(() => {
    setCtrlZPressCount((prev) => prev + 1);
  }, []);
  return { handleSuspend };
}

// packages/cli/src/ui/hooks/useRunEventNotifications.ts
var import_react127 = __toESM(require_react(), 1);

// packages/cli/src/ui/utils/pendingAttentionNotification.ts
var import_react126 = __toESM(require_react(), 1);

// packages/cli/src/utils/terminalNotifications.ts
var MAX_NOTIFICATION_TITLE_CHARS = 48;
var MAX_NOTIFICATION_SUBTITLE_CHARS = 64;
var MAX_NOTIFICATION_BODY_CHARS = 180;
var BEL2 = "\x07";
var OSC9_PREFIX = "\x1B]9;";
var OSC9_SEPARATOR = " | ";
var MAX_OSC9_MESSAGE_CHARS = MAX_NOTIFICATION_TITLE_CHARS + MAX_NOTIFICATION_SUBTITLE_CHARS + MAX_NOTIFICATION_BODY_CHARS + OSC9_SEPARATOR.length * 2;
function sanitizeNotificationContent(content) {
  const title = sanitizeForDisplay(content.title, MAX_NOTIFICATION_TITLE_CHARS);
  const subtitle = content.subtitle ? sanitizeForDisplay(content.subtitle, MAX_NOTIFICATION_SUBTITLE_CHARS) : void 0;
  const body = sanitizeForDisplay(content.body, MAX_NOTIFICATION_BODY_CHARS);
  return {
    title: title || "Gemini CLI",
    subtitle: subtitle || void 0,
    body: body || "Open Gemini CLI for details."
  };
}
function buildRunEventNotificationContent(event) {
  if (event.type === "attention") {
    return sanitizeNotificationContent({
      title: "Gemini CLI needs your attention",
      subtitle: event.heading ?? "Action required",
      body: event.detail ?? "Open Gemini CLI to continue."
    });
  }
  return sanitizeNotificationContent({
    title: "Gemini CLI session complete",
    subtitle: "Run finished",
    body: event.detail ?? "The session finished successfully."
  });
}
function isNotificationsEnabled(settings) {
  const general = settings.merged.general;
  return general?.enableNotifications === true;
}
function buildTerminalNotificationMessage(content) {
  const pieces = [content.title, content.subtitle, content.body].filter(
    Boolean
  );
  const combined = pieces.join(OSC9_SEPARATOR);
  return sanitizeForDisplay(combined, MAX_OSC9_MESSAGE_CHARS);
}
function emitOsc9Notification(content) {
  const message = buildTerminalNotificationMessage(content);
  if (!TerminalCapabilityManager.getInstance().supportsOsc9Notifications()) {
    writeToStdout(BEL2);
    return;
  }
  writeToStdout(`${OSC9_PREFIX}${message}${BEL2}`);
}
async function notifyViaTerminal(notificationsEnabled, content) {
  if (!notificationsEnabled) {
    return false;
  }
  try {
    emitOsc9Notification(sanitizeNotificationContent(content));
    return true;
  } catch (error) {
    debugLogger.debug("Failed to emit terminal notification:", error);
    return false;
  }
}

// packages/cli/src/ui/utils/pendingAttentionNotification.ts
function keyFromReactNode(node) {
  if (typeof node === "string" || typeof node === "number") {
    return String(node);
  }
  if (Array.isArray(node)) {
    return node.map((item) => keyFromReactNode(item)).join("|");
  }
  return "react-node";
}
function getPendingAttentionNotification(pendingHistoryItems, commandConfirmationRequest, authConsentRequest, permissionConfirmationRequest, hasConfirmUpdateExtensionRequests, hasLoopDetectionConfirmationRequest) {
  const confirmingToolState = getConfirmingToolState(pendingHistoryItems);
  if (confirmingToolState) {
    const details = confirmingToolState.tool.confirmationDetails;
    if (details?.type === "ask_user") {
      const firstQuestion = details.questions.at(0)?.header;
      return {
        key: `ask_user:${confirmingToolState.tool.callId}`,
        event: {
          type: "attention",
          heading: "Answer requested by agent",
          detail: firstQuestion || "The agent needs your response to continue."
        }
      };
    }
    const toolTitle = details?.title || confirmingToolState.tool.description;
    return {
      key: `tool_confirmation:${confirmingToolState.tool.callId}`,
      event: {
        type: "attention",
        heading: "Approval required",
        detail: toolTitle ? `Approve tool action: ${toolTitle}` : "Approve a pending tool action to continue."
      }
    };
  }
  if (commandConfirmationRequest) {
    const promptKey = keyFromReactNode(commandConfirmationRequest.prompt);
    return {
      key: `command_confirmation:${promptKey}`,
      event: {
        type: "attention",
        heading: "Confirmation required",
        detail: "A command is waiting for your confirmation."
      }
    };
  }
  if (authConsentRequest) {
    const promptKey = keyFromReactNode(authConsentRequest.prompt);
    return {
      key: `auth_consent:${promptKey}`,
      event: {
        type: "attention",
        heading: "Authentication confirmation required",
        detail: "Authentication is waiting for your confirmation."
      }
    };
  }
  if (permissionConfirmationRequest) {
    const filesKey = permissionConfirmationRequest.files.join("|");
    return {
      key: `filesystem_permission_confirmation:${filesKey}`,
      event: {
        type: "attention",
        heading: "Filesystem permission required",
        detail: "Read-only path access is waiting for your confirmation."
      }
    };
  }
  if (hasConfirmUpdateExtensionRequests) {
    return {
      key: "extension_update_confirmation",
      event: {
        type: "attention",
        heading: "Extension update confirmation required",
        detail: "An extension update is waiting for your confirmation."
      }
    };
  }
  if (hasLoopDetectionConfirmationRequest) {
    return {
      key: "loop_detection_confirmation",
      event: {
        type: "attention",
        heading: "Loop detection confirmation required",
        detail: "A loop detection prompt is waiting for your response."
      }
    };
  }
  return null;
}

// packages/cli/src/ui/hooks/useRunEventNotifications.ts
var ATTENTION_NOTIFICATION_COOLDOWN_MS = 2e4;
function useRunEventNotifications({
  notificationsEnabled,
  isFocused,
  hasReceivedFocusEvent,
  streamingState,
  hasPendingActionRequired,
  pendingHistoryItems,
  commandConfirmationRequest,
  authConsentRequest,
  permissionConfirmationRequest,
  hasConfirmUpdateExtensionRequests,
  hasLoopDetectionConfirmationRequest
}) {
  const pendingAttentionNotification = (0, import_react127.useMemo)(
    () => getPendingAttentionNotification(
      pendingHistoryItems,
      commandConfirmationRequest,
      authConsentRequest,
      permissionConfirmationRequest,
      hasConfirmUpdateExtensionRequests,
      hasLoopDetectionConfirmationRequest
    ),
    [
      pendingHistoryItems,
      commandConfirmationRequest,
      authConsentRequest,
      permissionConfirmationRequest,
      hasConfirmUpdateExtensionRequests,
      hasLoopDetectionConfirmationRequest
    ]
  );
  const hadPendingAttentionRef = (0, import_react127.useRef)(false);
  const previousFocusedRef = (0, import_react127.useRef)(isFocused);
  const previousStreamingStateRef = (0, import_react127.useRef)(streamingState);
  const lastSentAttentionNotificationRef = (0, import_react127.useRef)(null);
  (0, import_react127.useEffect)(() => {
    if (!notificationsEnabled) {
      return;
    }
    const wasFocused = previousFocusedRef.current;
    previousFocusedRef.current = isFocused;
    const hasPendingAttention = pendingAttentionNotification !== null;
    const hadPendingAttention = hadPendingAttentionRef.current;
    hadPendingAttentionRef.current = hasPendingAttention;
    if (!hasPendingAttention) {
      lastSentAttentionNotificationRef.current = null;
      return;
    }
    const shouldSuppressForFocus = hasReceivedFocusEvent && isFocused;
    if (shouldSuppressForFocus) {
      return;
    }
    const justEnteredAttentionState = !hadPendingAttention;
    const justLostFocus = wasFocused && !isFocused;
    const now = Date.now();
    const currentKey = pendingAttentionNotification.key;
    const lastSent = lastSentAttentionNotificationRef.current;
    const keyChanged = !lastSent || lastSent.key !== currentKey;
    const onCooldown = !!lastSent && lastSent.key === currentKey && now - lastSent.sentAt < ATTENTION_NOTIFICATION_COOLDOWN_MS;
    const shouldNotifyByStateChange = hasReceivedFocusEvent ? justEnteredAttentionState || justLostFocus || keyChanged : justEnteredAttentionState || keyChanged;
    if (!shouldNotifyByStateChange || onCooldown) {
      return;
    }
    lastSentAttentionNotificationRef.current = {
      key: currentKey,
      sentAt: now
    };
    void notifyViaTerminal(
      notificationsEnabled,
      buildRunEventNotificationContent(pendingAttentionNotification.event)
    );
  }, [
    isFocused,
    hasReceivedFocusEvent,
    notificationsEnabled,
    pendingAttentionNotification
  ]);
  (0, import_react127.useEffect)(() => {
    if (!notificationsEnabled) {
      return;
    }
    const previousStreamingState = previousStreamingStateRef.current;
    previousStreamingStateRef.current = streamingState;
    const justCompletedTurn = previousStreamingState === "responding" /* Responding */ && streamingState === "idle" /* Idle */;
    const shouldSuppressForFocus = hasReceivedFocusEvent && isFocused;
    if (!justCompletedTurn || shouldSuppressForFocus || hasPendingActionRequired) {
      return;
    }
    void notifyViaTerminal(
      notificationsEnabled,
      buildRunEventNotificationContent({
        type: "session_complete",
        detail: "Gemini CLI finished responding."
      })
    );
  }, [
    streamingState,
    isFocused,
    hasReceivedFocusEvent,
    notificationsEnabled,
    hasPendingActionRequired
  ]);
}

// packages/cli/src/ui/hooks/useVisibilityToggle.ts
var import_react128 = __toESM(require_react(), 1);
var APPROVAL_MODE_REVEAL_DURATION_MS = 1200;
var FOCUS_UI_ENABLED_STATE_KEY = "focusUiEnabled";
function useVisibilityToggle() {
  const [focusUiEnabledByDefault] = (0, import_react128.useState)(
    () => persistentState.get(FOCUS_UI_ENABLED_STATE_KEY) === true
  );
  const [cleanUiDetailsVisible, setCleanUiDetailsVisibleState] = (0, import_react128.useState)(
    !focusUiEnabledByDefault
  );
  const modeRevealTimeoutRef = (0, import_react128.useRef)(null);
  const cleanUiDetailsPinnedRef = (0, import_react128.useRef)(!focusUiEnabledByDefault);
  const clearModeRevealTimeout = (0, import_react128.useCallback)(() => {
    if (modeRevealTimeoutRef.current) {
      clearTimeout(modeRevealTimeoutRef.current);
      modeRevealTimeoutRef.current = null;
    }
  }, []);
  const persistFocusUiPreference = (0, import_react128.useCallback)((isFullUiVisible) => {
    persistentState.set(FOCUS_UI_ENABLED_STATE_KEY, !isFullUiVisible);
  }, []);
  const setCleanUiDetailsVisible = (0, import_react128.useCallback)(
    (visible) => {
      clearModeRevealTimeout();
      cleanUiDetailsPinnedRef.current = visible;
      setCleanUiDetailsVisibleState(visible);
      persistFocusUiPreference(visible);
    },
    [clearModeRevealTimeout, persistFocusUiPreference]
  );
  const toggleCleanUiDetailsVisible = (0, import_react128.useCallback)(() => {
    clearModeRevealTimeout();
    setCleanUiDetailsVisibleState((visible) => {
      const nextVisible = !visible;
      cleanUiDetailsPinnedRef.current = nextVisible;
      persistFocusUiPreference(nextVisible);
      return nextVisible;
    });
  }, [clearModeRevealTimeout, persistFocusUiPreference]);
  const revealCleanUiDetailsTemporarily = (0, import_react128.useCallback)(
    (durationMs = APPROVAL_MODE_REVEAL_DURATION_MS) => {
      if (cleanUiDetailsPinnedRef.current) {
        return;
      }
      clearModeRevealTimeout();
      setCleanUiDetailsVisibleState(true);
      modeRevealTimeoutRef.current = setTimeout(() => {
        if (!cleanUiDetailsPinnedRef.current) {
          setCleanUiDetailsVisibleState(false);
        }
        modeRevealTimeoutRef.current = null;
      }, durationMs);
    },
    [clearModeRevealTimeout]
  );
  (0, import_react128.useEffect)(() => () => clearModeRevealTimeout(), [clearModeRevealTimeout]);
  return {
    cleanUiDetailsVisible,
    setCleanUiDetailsVisible,
    toggleCleanUiDetailsVisible,
    revealCleanUiDetailsTemporarily
  };
}

// packages/cli/src/ui/AppContainer.tsx
var import_jsx_runtime142 = __toESM(require_jsx_runtime(), 1);
var SHELL_WIDTH_FRACTION = 0.89;
var SHELL_HEIGHT_PADDING = 10;
var AppContainer = (props) => {
  const isHelpDismissKey = useIsHelpDismissKey();
  const keyMatchers = useKeyMatchers();
  const { config, initializationResult, resumedSessionData } = props;
  const settings = useSettings();
  const { reset } = useOverflowActions();
  const notificationsEnabled = isNotificationsEnabled(settings);
  const { setOptions, dumpCurrentFrame, startRecording, stopRecording } = (0, import_react129.useContext)(AppContext_default);
  const recordingFilenameRef = (0, import_react129.useRef)(null);
  const historyManager = useHistory({
    chatRecordingService: config.getGeminiClient()?.getChatRecordingService()
  });
  useMemoryMonitor(historyManager);
  const isAlternateBuffer = config.getUseAlternateBuffer();
  const [mouseMode, setMouseMode] = (0, import_react129.useState)(
    () => config.getUseAlternateBuffer()
  );
  (0, import_react129.useEffect)(() => {
    setOptions({
      stickyHeadersInBackbuffer: mouseMode
    });
    if (mouseMode) {
      enableMouseEvents();
    } else {
      disableMouseEvents();
    }
  }, [mouseMode, setOptions]);
  const [corgiMode, setCorgiMode] = (0, import_react129.useState)(false);
  const [forceRerenderKey, setForceRerenderKey] = (0, import_react129.useState)(0);
  const [debugMessage, setDebugMessage] = (0, import_react129.useState)("");
  const [quittingMessages, setQuittingMessages] = (0, import_react129.useState)(null);
  const [showPrivacyNotice, setShowPrivacyNotice] = (0, import_react129.useState)(false);
  const [themeError, setThemeError] = (0, import_react129.useState)(
    initializationResult.themeError
  );
  const [isProcessing, setIsProcessing] = (0, import_react129.useState)(false);
  const [embeddedShellFocused, setEmbeddedShellFocused] = (0, import_react129.useState)(false);
  const [showDebugProfiler, setShowDebugProfiler] = (0, import_react129.useState)(false);
  const [customDialog, setCustomDialog] = (0, import_react129.useState)(
    null
  );
  const [copyModeEnabled, setCopyModeEnabled] = (0, import_react129.useState)(false);
  const [pendingRestorePrompt, setPendingRestorePrompt] = (0, import_react129.useState)(false);
  const toggleBackgroundTasksRef = (0, import_react129.useRef)(() => {
  });
  const isBackgroundTaskVisibleRef = (0, import_react129.useRef)(false);
  const backgroundTasksRef = (0, import_react129.useRef)(/* @__PURE__ */ new Map());
  const [adminSettingsChanged, setAdminSettingsChanged] = (0, import_react129.useState)(false);
  const [expandedTools, setExpandedTools] = (0, import_react129.useState)(/* @__PURE__ */ new Set());
  const toggleExpansion = (0, import_react129.useCallback)((callId) => {
    setExpandedTools((prev) => {
      const next = new Set(prev);
      if (next.has(callId)) {
        next.delete(callId);
      } else {
        next.add(callId);
      }
      return next;
    });
  }, []);
  const toggleAllExpansion = (0, import_react129.useCallback)((callIds) => {
    setExpandedTools((prev) => {
      const next = new Set(prev);
      const anyCollapsed = callIds.some((id) => !next.has(id));
      if (anyCollapsed) {
        callIds.forEach((id) => next.add(id));
      } else {
        callIds.forEach((id) => next.delete(id));
      }
      return next;
    });
  }, []);
  const isExpanded = (0, import_react129.useCallback)(
    (callId) => expandedTools.has(callId),
    [expandedTools]
  );
  const [shellModeActive, setShellModeActive] = (0, import_react129.useState)(false);
  const [modelSwitchedFromQuotaError, setModelSwitchedFromQuotaError] = (0, import_react129.useState)(false);
  const [historyRemountKey, setHistoryRemountKey] = (0, import_react129.useState)(0);
  const [settingsNonce, setSettingsNonce] = (0, import_react129.useState)(0);
  const activeHooks = useHookDisplayState();
  const [updateInfo, setUpdateInfo] = (0, import_react129.useState)(null);
  const [isTrustedFolder, setIsTrustedFolder] = (0, import_react129.useState)(
    () => isWorkspaceTrusted(settings.merged).isTrusted
  );
  const [queueErrorMessage, setQueueErrorMessage] = useTimedMessage(
    QUEUE_ERROR_DISPLAY_DURATION_MS
  );
  const [newAgents, setNewAgents] = (0, import_react129.useState)(null);
  const [constrainHeight, setConstrainHeight] = (0, import_react129.useState)(true);
  const [expandHintTrigger, triggerExpandHint] = useTimedMessage(
    EXPAND_HINT_DURATION_MS
  );
  const showIsExpandableHint = Boolean(expandHintTrigger);
  const overflowState = useOverflowState();
  const overflowingIdsSize = overflowState?.overflowingIds.size ?? 0;
  const hasOverflowState = overflowingIdsSize > 0 || !constrainHeight;
  (0, import_react129.useEffect)(() => {
    if (hasOverflowState) {
      triggerExpandHint(true);
    }
  }, [hasOverflowState, overflowingIdsSize, triggerExpandHint]);
  const [defaultBannerText, setDefaultBannerText] = (0, import_react129.useState)("");
  const [warningBannerText, setWarningBannerText] = (0, import_react129.useState)("");
  const [bannerVisible, setBannerVisible] = (0, import_react129.useState)(true);
  const bannerData = (0, import_react129.useMemo)(
    () => ({
      defaultText: defaultBannerText,
      warningText: warningBannerText
    }),
    [defaultBannerText, warningBannerText]
  );
  const { bannerText } = useBanner(bannerData);
  const extensionManager = config.getExtensionLoader();
  extensionManager.setRequestConsent(
    (description) => requestConsentInteractive(description, addConfirmUpdateExtensionRequest)
  );
  extensionManager.setRequestSetting();
  const { addConfirmUpdateExtensionRequest, confirmUpdateExtensionRequests } = useConfirmUpdateRequests();
  const {
    extensionsUpdateState,
    extensionsUpdateStateInternal,
    dispatchExtensionStateUpdate
  } = useExtensionUpdates(
    extensionManager,
    historyManager.addItem,
    config.getEnableExtensionReloading()
  );
  const [isPermissionsDialogOpen, setPermissionsDialogOpen] = (0, import_react129.useState)(false);
  const [permissionsDialogProps, setPermissionsDialogProps] = (0, import_react129.useState)(null);
  const openPermissionsDialog = (0, import_react129.useCallback)(
    (props2) => {
      setPermissionsDialogOpen(true);
      setPermissionsDialogProps(props2 ?? null);
    },
    []
  );
  const closePermissionsDialog = (0, import_react129.useCallback)(() => {
    setPermissionsDialogOpen(false);
    setPermissionsDialogProps(null);
  }, []);
  const [isAgentConfigDialogOpen, setIsAgentConfigDialogOpen] = (0, import_react129.useState)(false);
  const [selectedAgentName, setSelectedAgentName] = (0, import_react129.useState)();
  const [selectedAgentDisplayName, setSelectedAgentDisplayName] = (0, import_react129.useState)();
  const [selectedAgentDefinition, setSelectedAgentDefinition] = (0, import_react129.useState)();
  const openAgentConfigDialog = (0, import_react129.useCallback)(
    (name, displayName, definition) => {
      setSelectedAgentName(name);
      setSelectedAgentDisplayName(displayName);
      setSelectedAgentDefinition(definition);
      setIsAgentConfigDialogOpen(true);
    },
    []
  );
  const closeAgentConfigDialog = (0, import_react129.useCallback)(() => {
    setIsAgentConfigDialogOpen(false);
    setSelectedAgentName(void 0);
    setSelectedAgentDisplayName(void 0);
    setSelectedAgentDefinition(void 0);
  }, []);
  const toggleDebugProfiler = (0, import_react129.useCallback)(
    () => setShowDebugProfiler((prev) => !prev),
    []
  );
  const [currentModel, setCurrentModel] = (0, import_react129.useState)(config.getModel());
  const [userTier, setUserTier] = (0, import_react129.useState)(void 0);
  const [quotaStats, setQuotaStats] = (0, import_react129.useState)(() => {
    const remaining = config.getQuotaRemaining();
    const limit = config.getQuotaLimit();
    const resetTime = config.getQuotaResetTime();
    return remaining !== void 0 || limit !== void 0 || resetTime !== void 0 ? { remaining, limit, resetTime } : void 0;
  });
  const [paidTier, setPaidTier] = (0, import_react129.useState)(
    void 0
  );
  const [isConfigInitialized, setConfigInitialized] = (0, import_react129.useState)(false);
  const logger = useLogger(config.storage);
  const { inputHistory, addInput, initializeFromLogger } = useInputHistoryStore();
  const { columns: terminalWidth, rows: terminalHeight } = useTerminalSize();
  const { stdin, setRawMode } = use_stdin_default();
  const { stdout } = use_stdout_default();
  const app = use_app_default();
  const { stats: sessionStats } = useSessionStats();
  const branchName = useGitBranchName(config.getTargetDir());
  const rootUiRef = (0, import_react129.useRef)(null);
  const lastTitleRef = (0, import_react129.useRef)(null);
  const staticExtraHeight = 3;
  (0, import_react129.useEffect)(() => {
    (async () => {
      if (!config.isInitialized()) {
        await config.initialize();
      }
      setConfigInitialized(true);
      startupProfiler.flush(config);
      if (config.isMemoryManagerEnabled()) {
        startMemoryService(config).catch((e) => {
          debugLogger.error("Failed to start memory service:", e);
        });
      }
      const sessionStartSource = resumedSessionData ? SessionStartSource.Resume : SessionStartSource.Startup;
      const result = await config.getHookSystem()?.fireSessionStartEvent(sessionStartSource);
      if (result) {
        if (result.systemMessage) {
          historyManager.addItem(
            {
              type: "info" /* INFO */,
              text: result.systemMessage
            },
            Date.now()
          );
        }
        const additionalContext = result.getAdditionalContext();
        const geminiClient2 = config.getGeminiClient();
        if (additionalContext && geminiClient2) {
          await geminiClient2.addHistory({
            role: "user",
            parts: [
              { text: `<hook_context>${additionalContext}</hook_context>` }
            ]
          });
        }
      }
      generateSummary(config).catch((e) => {
        debugLogger.warn("Background summary generation failed:", e);
      });
    })();
    registerCleanup(async () => {
      disableMouseEvents();
      await Promise.all(
        Array.from(backgroundTasksRef.current.keys()).map(
          (pid) => ShellExecutionService.kill(pid)
        )
      );
      const ideClient = await IdeClient.getInstance();
      await ideClient.disconnect();
      await config?.getHookSystem()?.fireSessionEndEvent(SessionEndReason.Exit);
    });
  }, [config, resumedSessionData]);
  (0, import_react129.useEffect)(
    () => setUpdateHandler(historyManager.addItem, setUpdateInfo),
    [historyManager.addItem]
  );
  (0, import_react129.useEffect)(() => {
    const handleModelChanged = () => {
      setCurrentModel(config.getModel());
    };
    const handleQuotaChanged = (payload) => {
      setQuotaStats({
        remaining: payload.remaining,
        limit: payload.limit,
        resetTime: payload.resetTime
      });
    };
    coreEvents.on(CoreEvent.ModelChanged, handleModelChanged);
    coreEvents.on(CoreEvent.QuotaChanged, handleQuotaChanged);
    return () => {
      coreEvents.off(CoreEvent.ModelChanged, handleModelChanged);
      coreEvents.off(CoreEvent.QuotaChanged, handleQuotaChanged);
    };
  }, [config]);
  (0, import_react129.useEffect)(() => {
    const handleSettingsChanged = () => {
      setSettingsNonce((prev) => prev + 1);
    };
    const handleAdminSettingsChanged = () => {
      setAdminSettingsChanged(true);
    };
    const handleAgentsDiscovered = (payload) => {
      setNewAgents(payload.agents);
    };
    coreEvents.on(CoreEvent.SettingsChanged, handleSettingsChanged);
    coreEvents.on(CoreEvent.AdminSettingsChanged, handleAdminSettingsChanged);
    coreEvents.on(CoreEvent.AgentsDiscovered, handleAgentsDiscovered);
    return () => {
      coreEvents.off(CoreEvent.SettingsChanged, handleSettingsChanged);
      coreEvents.off(
        CoreEvent.AdminSettingsChanged,
        handleAdminSettingsChanged
      );
      coreEvents.off(CoreEvent.AgentsDiscovered, handleAgentsDiscovered);
    };
  }, [settings]);
  const { errorCount, clearErrorCount } = useErrorCount();
  const mainAreaWidth = calculateMainAreaWidth(terminalWidth, config);
  const { inputWidth, suggestionsWidth } = (0, import_react129.useMemo)(() => {
    const { inputWidth: inputWidth2, suggestionsWidth: suggestionsWidth2 } = calculatePromptWidths(mainAreaWidth);
    return { inputWidth: inputWidth2, suggestionsWidth: suggestionsWidth2 };
  }, [mainAreaWidth]);
  const staticAreaMaxItemHeight = Math.max(terminalHeight * 4, 100);
  const getPreferredEditor = (0, import_react129.useCallback)(
    // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
    () => settings.merged.general.preferredEditor,
    [settings.merged.general.preferredEditor]
  );
  const buffer = useTextBuffer({
    initialText: "",
    viewport: { height: 10, width: inputWidth },
    stdin,
    setRawMode,
    escapePastedPaths: true,
    shellModeActive,
    getPreferredEditor
  });
  const bufferRef = (0, import_react129.useRef)(buffer);
  (0, import_react129.useEffect)(() => {
    bufferRef.current = buffer;
  }, [buffer]);
  const stableSetText = (0, import_react129.useCallback)((text) => {
    bufferRef.current.setText(text);
  }, []);
  (0, import_react129.useEffect)(() => {
    initializeFromLogger(logger);
  }, [logger, initializeFromLogger]);
  useTerminalSetupPrompt({
    addConfirmUpdateExtensionRequest,
    addItem: historyManager.addItem
  });
  const refreshStatic = (0, import_react129.useCallback)(() => {
    if (!isAlternateBuffer && !config.getUseTerminalBuffer()) {
      stdout.write(base_exports.clearTerminal);
      setHistoryRemountKey((prev) => prev + 1);
    }
  }, [setHistoryRemountKey, isAlternateBuffer, stdout, config]);
  const shouldUseAlternateScreen = shouldEnterAlternateScreen(
    isAlternateBuffer,
    config.getScreenReader()
  );
  const handleEditorClose = (0, import_react129.useCallback)(() => {
    if (shouldUseAlternateScreen) {
      enterAlternateScreen();
      enableMouseEvents();
      disableLineWrapping();
      app.rerender();
    }
    terminalCapabilityManager.enableSupportedModes();
    refreshStatic();
  }, [refreshStatic, shouldUseAlternateScreen, app]);
  const [editorError, setEditorError] = (0, import_react129.useState)(null);
  const {
    isEditorDialogOpen,
    openEditorDialog,
    handleEditorSelect,
    exitEditorDialog
  } = useEditorSettings(settings, setEditorError, historyManager.addItem);
  (0, import_react129.useEffect)(() => {
    coreEvents.on(CoreEvent.ExternalEditorClosed, handleEditorClose);
    coreEvents.on(CoreEvent.RequestEditorSelection, openEditorDialog);
    return () => {
      coreEvents.off(CoreEvent.ExternalEditorClosed, handleEditorClose);
      coreEvents.off(CoreEvent.RequestEditorSelection, openEditorDialog);
    };
  }, [handleEditorClose, openEditorDialog]);
  (0, import_react129.useEffect)(() => {
    if (!(settings.merged.ui.hideBanner || config.getScreenReader()) && bannerVisible && bannerText) {
      refreshStatic();
    }
  }, [bannerVisible, bannerText, settings, config, refreshStatic]);
  const { isSettingsDialogOpen, openSettingsDialog, closeSettingsDialog } = useSettingsCommand();
  const {
    isThemeDialogOpen,
    openThemeDialog,
    closeThemeDialog,
    handleThemeSelect,
    handleThemeHighlight
  } = useThemeCommand(
    settings,
    setThemeError,
    historyManager.addItem,
    initializationResult.themeError,
    refreshStatic
  );
  useTerminalTheme(handleThemeSelect, config, refreshStatic);
  const {
    authState,
    setAuthState,
    authError,
    onAuthError,
    apiKeyDefaultValue,
    reloadApiKey,
    accountSuspensionInfo,
    setAccountSuspensionInfo
  } = useAuthCommand(
    settings,
    config,
    initializationResult.authError,
    initializationResult.accountSuspensionInfo
  );
  const [authContext, setAuthContext] = (0, import_react129.useState)(
    {}
  );
  (0, import_react129.useEffect)(() => {
    if (authState === "authenticated" /* Authenticated */ && authContext.requiresRestart) {
      setAuthState("awaiting_google_login_restart" /* AwaitingGoogleLoginRestart */);
      setAuthContext({});
    }
  }, [authState, authContext, setAuthState]);
  const {
    proQuotaRequest,
    handleProQuotaChoice,
    validationRequest,
    handleValidationChoice,
    // G1 AI Credits
    overageMenuRequest,
    handleOverageMenuChoice,
    emptyWalletRequest,
    handleEmptyWalletChoice
  } = useQuotaAndFallback({
    config,
    historyManager,
    userTier,
    paidTier,
    settings,
    setModelSwitchedFromQuotaError,
    onShowAuthSelection: () => setAuthState("updating" /* Updating */),
    errorVerbosity: settings.merged.ui.errorVerbosity
  });
  const isAuthDialogOpen = authState === "updating" /* Updating */;
  const isAuthenticating = authState === "unauthenticated" /* Unauthenticated */ && settings.merged.security.auth.selectedType !== AuthType.USE_GEMINI;
  const isGeminiClientInitialized = config.getGeminiClient()?.isInitialized();
  const { loadHistoryForResume, isResuming } = useSessionResume({
    config,
    historyManager,
    refreshStatic,
    isGeminiClientInitialized,
    setQuittingMessages,
    resumedSessionData,
    isAuthenticating
  });
  const {
    isSessionBrowserOpen,
    openSessionBrowser,
    closeSessionBrowser,
    handleResumeSession,
    handleDeleteSession: handleDeleteSessionSync
  } = useSessionBrowser(config, loadHistoryForResume);
  const handleDeleteSession = (0, import_react129.useCallback)(
    async (session) => {
      await handleDeleteSessionSync(session);
    },
    [handleDeleteSessionSync]
  );
  const handleAuthSelect = (0, import_react129.useCallback)(
    async (authType, scope) => {
      if (authType) {
        const previousAuthType = config.getContentGeneratorConfig()?.authType ?? "unknown";
        if (authType === AuthType.LOGIN_WITH_GOOGLE) {
          setAuthContext({ requiresRestart: true });
        } else {
          setAuthContext({});
        }
        await clearCachedCredentialFile();
        settings.setValue(scope, "security.auth.selectedType", authType);
        try {
          config.setRemoteAdminSettings(void 0);
          await config.refreshAuth(authType);
          setAuthState("authenticated" /* Authenticated */);
          logBillingEvent(
            config,
            new ApiKeyUpdatedEvent(previousAuthType, authType)
          );
        } catch (e) {
          if (e instanceof ChangeAuthRequestedError) {
            return;
          }
          if (e instanceof ProjectIdRequiredError) {
            onAuthError(getErrorMessage(e));
            return;
          }
          onAuthError(
            `Failed to authenticate: ${e instanceof Error ? e.message : String(e)}`
          );
          return;
        }
        if (authType === AuthType.LOGIN_WITH_GOOGLE && config.isBrowserLaunchSuppressed()) {
          writeToStdout(`
----------------------------------------------------------------
Logging in with Google... Restarting Gemini CLI to continue.
----------------------------------------------------------------
          `);
          await relaunchApp();
        }
      }
      setAuthState("authenticated" /* Authenticated */);
    },
    [settings, config, setAuthState, onAuthError, setAuthContext]
  );
  const handleApiKeySubmit = (0, import_react129.useCallback)(
    async (apiKey) => {
      try {
        onAuthError(null);
        if (!apiKey.trim() && apiKey.length > 1) {
          onAuthError(
            "API key cannot be empty string with length greater than 1."
          );
          return;
        }
        await saveApiKey(apiKey);
        await reloadApiKey();
        await config.refreshAuth(AuthType.USE_GEMINI);
        setAuthState("authenticated" /* Authenticated */);
      } catch (e) {
        onAuthError(
          `Failed to save API key: ${e instanceof Error ? e.message : String(e)}`
        );
      }
    },
    [setAuthState, onAuthError, reloadApiKey, config]
  );
  const handleApiKeyCancel = (0, import_react129.useCallback)(() => {
    setAuthState("updating" /* Updating */);
  }, [setAuthState]);
  (0, import_react129.useEffect)(() => {
    if (authState === "authenticated" /* Authenticated */) {
      setUserTier(config.getUserTier());
      setPaidTier(config.getUserPaidTier());
    }
  }, [config, authState]);
  (0, import_react129.useEffect)(() => {
    if (settings.merged.security.auth.enforcedType && settings.merged.security.auth.selectedType && settings.merged.security.auth.enforcedType !== settings.merged.security.auth.selectedType) {
      onAuthError(
        `Authentication is enforced to be ${settings.merged.security.auth.enforcedType}, but you are currently using ${settings.merged.security.auth.selectedType}.`
      );
    } else if (settings.merged.security.auth.selectedType && !settings.merged.security.auth.useExternal) {
      if (settings.merged.security.auth.selectedType === AuthType.USE_GEMINI) {
        return;
      }
      const error = validateAuthMethod(
        settings.merged.security.auth.selectedType
      );
      if (error) {
        onAuthError(error);
      }
    }
  }, [
    settings.merged.security.auth.selectedType,
    settings.merged.security.auth.enforcedType,
    settings.merged.security.auth.useExternal,
    onAuthError
  ]);
  const { isModelDialogOpen, openModelDialog, closeModelDialog } = useModelCommand();
  const { toggleVimEnabled } = useVimMode();
  const setIsBackgroundTaskListOpenRef = (0, import_react129.useRef)(
    () => {
    }
  );
  const [shortcutsHelpVisible, setShortcutsHelpVisible] = (0, import_react129.useState)(false);
  const {
    cleanUiDetailsVisible,
    setCleanUiDetailsVisible,
    toggleCleanUiDetailsVisible,
    revealCleanUiDetailsTemporarily
  } = useVisibilityToggle();
  const slashCommandActions = (0, import_react129.useMemo)(
    () => ({
      openAuthDialog: () => setAuthState("updating" /* Updating */),
      openThemeDialog,
      openEditorDialog,
      openPrivacyNotice: () => setShowPrivacyNotice(true),
      openSettingsDialog,
      openSessionBrowser,
      openModelDialog,
      openAgentConfigDialog,
      openPermissionsDialog,
      quit: (messages) => {
        setQuittingMessages(messages);
        setTimeout(async () => {
          await runExitCleanup();
          process14.exit(0);
        }, 100);
      },
      setDebugMessage,
      toggleCorgiMode: () => setCorgiMode((prev) => !prev),
      toggleDebugProfiler,
      dispatchExtensionStateUpdate,
      addConfirmUpdateExtensionRequest,
      toggleBackgroundTasks: () => {
        toggleBackgroundTasksRef.current();
        if (!isBackgroundTaskVisibleRef.current) {
          setEmbeddedShellFocused(true);
          if (backgroundTasksRef.current.size > 1) {
            setIsBackgroundTaskListOpenRef.current(true);
          } else {
            setIsBackgroundTaskListOpenRef.current(false);
          }
        }
      },
      toggleShortcutsHelp: () => setShortcutsHelpVisible((visible) => !visible),
      setText: stableSetText
    }),
    [
      setAuthState,
      openThemeDialog,
      openEditorDialog,
      openSettingsDialog,
      openSessionBrowser,
      openModelDialog,
      openAgentConfigDialog,
      setQuittingMessages,
      setDebugMessage,
      setShowPrivacyNotice,
      setCorgiMode,
      dispatchExtensionStateUpdate,
      openPermissionsDialog,
      addConfirmUpdateExtensionRequest,
      toggleDebugProfiler,
      setShortcutsHelpVisible,
      stableSetText
    ]
  );
  const {
    handleSlashCommand,
    slashCommands,
    pendingHistoryItems: pendingSlashCommandHistoryItems,
    commandContext,
    confirmationRequest: commandConfirmationRequest
  } = useSlashCommandProcessor(
    config,
    settings,
    historyManager.addItem,
    historyManager.clearItems,
    historyManager.loadHistory,
    refreshStatic,
    toggleVimEnabled,
    setIsProcessing,
    slashCommandActions,
    extensionsUpdateStateInternal,
    isConfigInitialized,
    setBannerVisible,
    setCustomDialog
  );
  const [authConsentRequest, setAuthConsentRequest] = (0, import_react129.useState)(null);
  const [permissionConfirmationRequest, setPermissionConfirmationRequest] = (0, import_react129.useState)(null);
  (0, import_react129.useEffect)(() => {
    const handleConsentRequest = (payload) => {
      setAuthConsentRequest({
        prompt: payload.prompt,
        onConfirm: (confirmed) => {
          setAuthConsentRequest(null);
          payload.onConfirm(confirmed);
        }
      });
    };
    coreEvents.on(CoreEvent.ConsentRequest, handleConsentRequest);
    return () => {
      coreEvents.off(CoreEvent.ConsentRequest, handleConsentRequest);
    };
  }, []);
  const performMemoryRefresh = (0, import_react129.useCallback)(async () => {
    historyManager.addItem(
      {
        type: "info" /* INFO */,
        text: "Refreshing hierarchical memory (GEMINI.md or other context files)..."
      },
      Date.now()
    );
    try {
      let flattenedMemory;
      let fileCount;
      if (config.isJitContextEnabled()) {
        await config.getMemoryContextManager()?.refresh();
        config.updateSystemInstructionIfInitialized();
        flattenedMemory = flattenMemory(config.getUserMemory());
        fileCount = config.getGeminiMdFileCount();
      } else {
        const result = await refreshServerHierarchicalMemory(config);
        flattenedMemory = flattenMemory(result.memoryContent);
        fileCount = result.fileCount;
      }
      historyManager.addItem(
        {
          type: "info" /* INFO */,
          text: `Memory reloaded successfully. ${flattenedMemory.length > 0 ? `Loaded ${flattenedMemory.length} characters from ${fileCount} file(s)` : "No memory content found"}`
        },
        Date.now()
      );
      if (config.getDebugMode()) {
        debugLogger.log(
          `[DEBUG] Refreshed memory content in config: ${flattenedMemory.substring(
            0,
            200
          )}...`
        );
      }
    } catch (error) {
      const errorMessage = getErrorMessage(error);
      historyManager.addItem(
        {
          type: "error" /* ERROR */,
          text: `Error refreshing memory: ${errorMessage}`
        },
        Date.now()
      );
      debugLogger.warn("Error refreshing memory:", error);
    }
  }, [config, historyManager]);
  const cancelHandlerRef = (0, import_react129.useRef)(
    () => {
    }
  );
  const onCancelSubmit = (0, import_react129.useCallback)((shouldRestorePrompt) => {
    if (shouldRestorePrompt) {
      setPendingRestorePrompt(true);
    } else {
      setPendingRestorePrompt(false);
      cancelHandlerRef.current(false);
    }
  }, []);
  (0, import_react129.useEffect)(() => {
    if (pendingRestorePrompt) {
      const lastHistoryUserMsg = historyManager.history.findLast(
        (h) => h.type === "user"
      );
      const lastUserMsg = inputHistory.at(-1);
      if (!lastHistoryUserMsg || typeof lastHistoryUserMsg.text === "string" && lastHistoryUserMsg.text === lastUserMsg) {
        cancelHandlerRef.current(true);
        setPendingRestorePrompt(false);
      }
    }
  }, [pendingRestorePrompt, inputHistory, historyManager.history]);
  const pendingHintsRef = (0, import_react129.useRef)([]);
  const [pendingHintCount, setPendingHintCount] = (0, import_react129.useState)(0);
  const consumePendingHints = (0, import_react129.useCallback)(() => {
    if (pendingHintsRef.current.length === 0) {
      return null;
    }
    const hint = pendingHintsRef.current.join("\n");
    pendingHintsRef.current = [];
    setPendingHintCount(0);
    return hint;
  }, []);
  (0, import_react129.useEffect)(() => {
    const hintListener = (text, source2) => {
      if (source2 !== "user_steering" && source2 !== "background_completion") {
        return;
      }
      pendingHintsRef.current.push(text);
      setPendingHintCount((prev) => prev + 1);
    };
    config.injectionService.onInjection(hintListener);
    return () => {
      config.injectionService.offInjection(hintListener);
    };
  }, [config]);
  const {
    streamingState,
    submitQuery,
    initError,
    pendingHistoryItems: pendingGeminiHistoryItems,
    thought,
    cancelOngoingRequest,
    pendingToolCalls,
    handleApprovalModeChange,
    activePtyId,
    loopDetectionConfirmationRequest,
    lastOutputTime,
    backgroundTaskCount,
    isBackgroundTaskVisible,
    toggleBackgroundTasks,
    backgroundCurrentExecution,
    backgroundTasks,
    dismissBackgroundTask,
    retryStatus
  } = useGeminiStream(
    config.getGeminiClient(),
    historyManager.history,
    historyManager.addItem,
    config,
    settings,
    setDebugMessage,
    handleSlashCommand,
    shellModeActive,
    getPreferredEditor,
    onAuthError,
    performMemoryRefresh,
    modelSwitchedFromQuotaError,
    setModelSwitchedFromQuotaError,
    onCancelSubmit,
    setEmbeddedShellFocused,
    terminalWidth,
    terminalHeight,
    embeddedShellFocused,
    consumePendingHints
  );
  const pendingHistoryItems = (0, import_react129.useMemo)(
    () => [...pendingSlashCommandHistoryItems, ...pendingGeminiHistoryItems],
    [pendingSlashCommandHistoryItems, pendingGeminiHistoryItems]
  );
  toggleBackgroundTasksRef.current = toggleBackgroundTasks;
  isBackgroundTaskVisibleRef.current = isBackgroundTaskVisible;
  backgroundTasksRef.current = backgroundTasks;
  const {
    activeBackgroundTaskPid,
    setIsBackgroundTaskListOpen,
    isBackgroundTaskListOpen,
    setActiveBackgroundTaskPid,
    backgroundTaskHeight
  } = useBackgroundTaskManager({
    backgroundTasks,
    backgroundTaskCount,
    isBackgroundTaskVisible,
    activePtyId,
    embeddedShellFocused,
    setEmbeddedShellFocused,
    terminalHeight
  });
  setIsBackgroundTaskListOpenRef.current = setIsBackgroundTaskListOpen;
  const lastOutputTimeRef = (0, import_react129.useRef)(0);
  (0, import_react129.useEffect)(() => {
    lastOutputTimeRef.current = lastOutputTime;
  }, [lastOutputTime]);
  const { shouldShowFocusHint, inactivityStatus } = useShellInactivityStatus({
    activePtyId,
    lastOutputTime,
    streamingState,
    pendingToolCalls,
    embeddedShellFocused,
    isInteractiveShellEnabled: config.isInteractiveShellEnabled()
  });
  const shouldShowActionRequiredTitle = inactivityStatus === "action_required";
  const shouldShowSilentWorkingTitle = inactivityStatus === "silent_working";
  const handleApprovalModeChangeWithUiReveal = (0, import_react129.useCallback)(
    (mode) => {
      void handleApprovalModeChange(mode);
      if (!cleanUiDetailsVisible) {
        revealCleanUiDetailsTemporarily(APPROVAL_MODE_REVEAL_DURATION_MS);
      }
    },
    [
      handleApprovalModeChange,
      cleanUiDetailsVisible,
      revealCleanUiDetailsTemporarily
    ]
  );
  const { isMcpReady } = useMcpStatus(config);
  const {
    messageQueue: messageQueue2,
    addMessage,
    clearQueue,
    getQueuedMessagesText,
    popAllMessages
  } = useMessageQueue({
    isConfigInitialized,
    streamingState,
    submitQuery,
    isMcpReady
  });
  cancelHandlerRef.current = (0, import_react129.useCallback)(
    (shouldRestorePrompt = true) => {
      if (isToolAwaitingConfirmation(pendingHistoryItems)) {
        return;
      }
      if (isToolExecuting(pendingHistoryItems)) {
        buffer.setText("");
        return;
      }
      if (!shouldRestorePrompt) {
        return;
      }
      const lastUserMessage = inputHistory.at(-1);
      let textToSet = lastUserMessage || "";
      const queuedText = getQueuedMessagesText();
      if (queuedText) {
        textToSet = textToSet ? `${textToSet}

${queuedText}` : queuedText;
        clearQueue();
      }
      if (textToSet) {
        buffer.setText(textToSet);
      }
    },
    [
      buffer,
      inputHistory,
      getQueuedMessagesText,
      clearQueue,
      pendingHistoryItems
    ]
  );
  const handleHintSubmit = (0, import_react129.useCallback)(
    (hint) => {
      const trimmed = hint.trim();
      if (!trimmed) {
        return;
      }
      config.injectionService.addInjection(trimmed, "user_steering");
      historyManager.addItem({
        type: "hint",
        text: trimmed
      });
    },
    [config, historyManager]
  );
  const handleFinalSubmit = (0, import_react129.useCallback)(
    async (submittedValue) => {
      reset();
      triggerExpandHint(null);
      if (!constrainHeight) {
        setConstrainHeight(true);
        if (!isAlternateBuffer) {
          refreshStatic();
        }
      }
      const isSlash = isSlashCommand(submittedValue.trim());
      const isIdle = streamingState === "idle" /* Idle */;
      const isAgentRunning = streamingState === "responding" /* Responding */ || isToolExecuting(pendingHistoryItems);
      if (isSlash && isAgentRunning) {
        const { commandToExecute } = parseSlashCommand(
          submittedValue,
          slashCommands ?? []
        );
        if (commandToExecute?.isSafeConcurrent) {
          void handleSlashCommand(submittedValue);
          addInput(submittedValue);
          return;
        }
      }
      if (config.isModelSteeringEnabled() && isAgentRunning && !isSlash) {
        handleHintSubmit(submittedValue);
        addInput(submittedValue);
        return;
      }
      const isMcpOrConfigReady = isConfigInitialized && isMcpReady;
      if (isSlash && isConfigInitialized || isIdle && isMcpOrConfigReady) {
        if (!isSlash) {
          const permissions = await checkPermissions(submittedValue, config);
          if (permissions.length > 0) {
            setPermissionConfirmationRequest({
              files: permissions,
              onComplete: (result) => {
                setPermissionConfirmationRequest(null);
                if (result.allowed) {
                  permissions.forEach(
                    (p) => config.getWorkspaceContext().addReadOnlyPath(p)
                  );
                }
                void submitQuery(submittedValue);
              }
            });
            addInput(submittedValue);
            return;
          }
        }
        void submitQuery(submittedValue);
      } else {
        if (isIdle && !isMcpOrConfigReady && messageQueue2.length === 0) {
          coreEvents.emitFeedback(
            "info",
            !isConfigInitialized ? "Initializing... Prompts will be queued." : "Waiting for MCP servers to initialize... Slash commands are still available and prompts will be queued."
          );
        }
        addMessage(submittedValue);
      }
      addInput(submittedValue);
    },
    [
      addMessage,
      addInput,
      submitQuery,
      handleSlashCommand,
      slashCommands,
      isMcpReady,
      streamingState,
      messageQueue2.length,
      pendingHistoryItems,
      config,
      constrainHeight,
      setConstrainHeight,
      isAlternateBuffer,
      refreshStatic,
      reset,
      handleHintSubmit,
      isConfigInitialized,
      triggerExpandHint
    ]
  );
  const handleClearScreen = (0, import_react129.useCallback)(() => {
    reset();
    triggerExpandHint(null);
    historyManager.clearItems();
    clearErrorCount();
    refreshStatic();
  }, [
    historyManager,
    clearErrorCount,
    refreshStatic,
    reset,
    triggerExpandHint
  ]);
  const { handleInput: vimHandleInput } = useVim(buffer, handleFinalSubmit);
  const isInputActive = !initError && !isProcessing && !isResuming && (streamingState === "idle" /* Idle */ || streamingState === "responding" /* Responding */ || streamingState === "waiting_for_confirmation" /* WaitingForConfirmation */) && !proQuotaRequest;
  const observerRef = (0, import_react129.useRef)(null);
  (0, import_react129.useEffect)(
    () => () => {
      observerRef.current?.disconnect();
    },
    []
  );
  const [controlsHeight, setControlsHeight] = (0, import_react129.useState)(0);
  const [lastNonCopyControlsHeight, setLastNonCopyControlsHeight] = (0, import_react129.useState)(0);
  (0, import_react129.useLayoutEffect)(() => {
    if (!copyModeEnabled && controlsHeight > 0) {
      setLastNonCopyControlsHeight(controlsHeight);
    }
  }, [copyModeEnabled, controlsHeight]);
  const stableControlsHeight = copyModeEnabled && lastNonCopyControlsHeight > 0 ? lastNonCopyControlsHeight : controlsHeight;
  const mainControlsRef = (0, import_react129.useCallback)((node) => {
    if (observerRef.current) {
      observerRef.current.disconnect();
      observerRef.current = null;
    }
    if (node) {
      const observer = new ResizeObserver((entries) => {
        const entry = entries[0];
        if (entry) {
          const roundedHeight = Math.round(entry.contentRect.height);
          setControlsHeight(
            (prev) => roundedHeight !== prev ? roundedHeight : prev
          );
        }
      });
      observer.observe(node);
      observerRef.current = observer;
    }
  }, []);
  const availableTerminalHeight = Math.max(
    0,
    terminalHeight - stableControlsHeight - backgroundTaskHeight - 1
  );
  config.setShellExecutionConfig({
    terminalWidth: Math.floor(terminalWidth * SHELL_WIDTH_FRACTION),
    terminalHeight: Math.max(
      Math.floor(availableTerminalHeight - SHELL_HEIGHT_PADDING),
      1
    ),
    pager: settings.merged.tools.shell.pager,
    showColor: settings.merged.tools.shell.showColor,
    sanitizationConfig: config.sanitizationConfig,
    sandboxManager: config.sandboxManager
  });
  const { isFocused, hasReceivedFocusEvent } = useFocus();
  const contextFileNames = (0, import_react129.useMemo)(() => {
    const fromSettings = settings.merged.context.fileName;
    return fromSettings ? Array.isArray(fromSettings) ? fromSettings : [fromSettings] : getAllGeminiMdFilenames();
  }, [settings.merged.context.fileName]);
  const initialPrompt = (0, import_react129.useMemo)(() => config.getQuestion(), [config]);
  const initialPromptSubmitted = (0, import_react129.useRef)(false);
  const geminiClient = config.getGeminiClient();
  (0, import_react129.useEffect)(() => {
    if (initialPrompt && isConfigInitialized && !initialPromptSubmitted.current && !isAuthenticating && !isAuthDialogOpen && !isThemeDialogOpen && !isEditorDialogOpen && !showPrivacyNotice && geminiClient?.isInitialized?.()) {
      void handleFinalSubmit(initialPrompt);
      initialPromptSubmitted.current = true;
    }
  }, [
    initialPrompt,
    isConfigInitialized,
    handleFinalSubmit,
    isAuthenticating,
    isAuthDialogOpen,
    isThemeDialogOpen,
    isEditorDialogOpen,
    showPrivacyNotice,
    geminiClient
  ]);
  const [idePromptAnswered, setIdePromptAnswered] = (0, import_react129.useState)(false);
  const [currentIDE, setCurrentIDE] = (0, import_react129.useState)(null);
  (0, import_react129.useEffect)(() => {
    const getIde = async () => {
      const ideClient = await IdeClient.getInstance();
      const currentIde = ideClient.getCurrentIde();
      setCurrentIDE(currentIde || null);
    };
    getIde();
  }, []);
  const shouldShowIdePrompt = Boolean(
    currentIDE && !config.getIdeMode() && !settings.merged.ide.hasSeenNudge && !idePromptAnswered
  );
  const [showErrorDetails, setShowErrorDetails] = (0, import_react129.useState)(false);
  const [showFullTodos, setShowFullTodos] = (0, import_react129.useState)(false);
  const [renderMarkdown, setRenderMarkdown] = (0, import_react129.useState)(true);
  const handleExitRepeat = (0, import_react129.useCallback)(
    (count) => {
      if (count > 2) {
        recordExitFail(config);
      }
      if (count > 1) {
        void handleSlashCommand("/quit", void 0, void 0, false);
      }
    },
    [config, handleSlashCommand]
  );
  const { pressCount: ctrlCPressCount, handlePress: handleCtrlCPress } = useRepeatedKeyPress({
    windowMs: WARNING_PROMPT_DURATION_MS,
    onRepeat: handleExitRepeat
  });
  const { pressCount: ctrlDPressCount, handlePress: handleCtrlDPress } = useRepeatedKeyPress({
    windowMs: WARNING_PROMPT_DURATION_MS,
    onRepeat: handleExitRepeat
  });
  const [ideContextState, setIdeContextState] = (0, import_react129.useState)();
  const [showEscapePrompt, setShowEscapePrompt] = (0, import_react129.useState)(false);
  const [showIdeRestartPrompt, setShowIdeRestartPrompt] = (0, import_react129.useState)(false);
  const [transientMessage, showTransientMessage] = useTimedMessage(WARNING_PROMPT_DURATION_MS);
  const {
    isFolderTrustDialogOpen,
    discoveryResults: folderDiscoveryResults,
    handleFolderTrustSelect,
    isRestarting
  } = useFolderTrust(settings, setIsTrustedFolder, historyManager.addItem);
  const policyUpdateConfirmationRequest = config.getPolicyUpdateConfirmationRequest();
  const [isPolicyUpdateDialogOpen, setIsPolicyUpdateDialogOpen] = (0, import_react129.useState)(
    !!policyUpdateConfirmationRequest
  );
  const {
    needsRestart: ideNeedsRestart,
    restartReason: ideTrustRestartReason
  } = useIdeTrustListener();
  const isInitialMount = (0, import_react129.useRef)(true);
  useIncludeDirsTrust(config, isTrustedFolder, historyManager, setCustomDialog);
  const tabFocusTimeoutRef = (0, import_react129.useRef)(null);
  (0, import_react129.useEffect)(() => {
    const handleTransientMessage = (payload) => {
      showTransientMessage({ text: payload.message, type: payload.type });
    };
    const handleSelectionWarning = () => {
      showTransientMessage({
        text: "Press Ctrl-S to enter selection mode to copy text.",
        type: "warning" /* Warning */
      });
    };
    const handlePasteTimeout = () => {
      showTransientMessage({
        text: "Paste Timed out. Possibly due to slow connection.",
        type: "warning" /* Warning */
      });
    };
    appEvents.on("transient-message" /* TransientMessage */, handleTransientMessage);
    appEvents.on("selection-warning" /* SelectionWarning */, handleSelectionWarning);
    appEvents.on("paste-timeout" /* PasteTimeout */, handlePasteTimeout);
    return () => {
      appEvents.off("transient-message" /* TransientMessage */, handleTransientMessage);
      appEvents.off("selection-warning" /* SelectionWarning */, handleSelectionWarning);
      appEvents.off("paste-timeout" /* PasteTimeout */, handlePasteTimeout);
      if (tabFocusTimeoutRef.current) {
        clearTimeout(tabFocusTimeoutRef.current);
      }
    };
  }, [showTransientMessage]);
  const handleWarning = (0, import_react129.useCallback)(
    (message) => {
      showTransientMessage({
        text: message,
        type: "warning" /* Warning */
      });
    },
    [showTransientMessage]
  );
  const { handleSuspend } = useSuspend({
    handleWarning,
    setRawMode,
    refreshStatic,
    setForceRerenderKey,
    shouldUseAlternateScreen
  });
  (0, import_react129.useEffect)(() => {
    if (ideNeedsRestart) {
      setShowIdeRestartPrompt(true);
    }
  }, [ideNeedsRestart]);
  (0, import_react129.useEffect)(() => {
    if (isInitialMount.current) {
      isInitialMount.current = false;
      return;
    }
    const handler = setTimeout(() => {
      refreshStatic();
    }, 300);
    return () => {
      clearTimeout(handler);
    };
  }, [terminalWidth, refreshStatic]);
  (0, import_react129.useEffect)(() => {
    const unsubscribe = ideContextStore.subscribe(setIdeContextState);
    setIdeContextState(ideContextStore.get());
    return unsubscribe;
  }, []);
  (0, import_react129.useEffect)(() => {
    const openDebugConsole = () => {
      setShowErrorDetails(true);
      setConstrainHeight(false);
    };
    appEvents.on("open-debug-console" /* OpenDebugConsole */, openDebugConsole);
    return () => {
      appEvents.off("open-debug-console" /* OpenDebugConsole */, openDebugConsole);
    };
  }, [config]);
  const handleEscapePromptChange = (0, import_react129.useCallback)((showPrompt) => {
    setShowEscapePrompt(showPrompt);
  }, []);
  const handleIdePromptComplete = (0, import_react129.useCallback)(
    (result) => {
      if (result.userSelection === "yes") {
        handleSlashCommand("/ide install");
        settings.setValue("User" /* User */, "ide.hasSeenNudge", true);
      } else if (result.userSelection === "dismiss") {
        settings.setValue("User" /* User */, "ide.hasSeenNudge", true);
      }
      setIdePromptAnswered(true);
    },
    [handleSlashCommand, settings]
  );
  const handleGlobalKeypress = (0, import_react129.useCallback)(
    (key) => {
      if (settings.merged.general.debugKeystrokeLogging) {
        debugLogger.log("[DEBUG] Keystroke:", JSON.stringify(key));
      }
      if (shortcutsHelpVisible && isHelpDismissKey(key)) {
        setShortcutsHelpVisible(false);
      }
      if (keyMatchers["app.toggleMouseMode" /* TOGGLE_MOUSE_MODE */](key)) {
        setMouseMode((prev) => !prev);
        if (mouseMode && !isAlternateBuffer) {
          appEvents.emit("scroll-to-bottom" /* ScrollToBottom */);
        }
        return true;
      }
      if (isAlternateBuffer && keyMatchers["app.toggleCopyMode" /* TOGGLE_COPY_MODE */](key)) {
        setCopyModeEnabled(true);
        disableMouseEvents();
        return true;
      }
      if (keyMatchers["basic.quit" /* QUIT */](key)) {
        cancelOngoingRequest?.();
        handleCtrlCPress();
        return true;
      } else if (keyMatchers["basic.exit" /* EXIT */](key)) {
        if (bufferRef.current.text.length > 0) {
          return false;
        }
        handleCtrlDPress();
        return true;
      } else if (keyMatchers["app.suspend" /* SUSPEND_APP */](key)) {
        handleSuspend();
      } else if (keyMatchers["app.dumpFrame" /* DUMP_FRAME */](key)) {
        const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
        const filename = `snapshot-${timestamp}.json`;
        if (dumpCurrentFrame) {
          dumpCurrentFrame(filename);
          debugLogger.log(`Dumped frame to: ${filename}`);
        }
        return true;
      } else if (keyMatchers["app.startRecording" /* START_RECORDING */](key)) {
        const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
        const filename = `recording-${timestamp}.json`;
        if (startRecording) {
          startRecording(filename);
          recordingFilenameRef.current = filename;
          debugLogger.log(`Started recording to: ${filename}`);
        }
        return true;
      } else if (keyMatchers["app.stopRecording" /* STOP_RECORDING */](key)) {
        if (stopRecording) {
          stopRecording();
          debugLogger.log(
            `Stopped recording, saved to: ${recordingFilenameRef.current ?? "unknown"}`
          );
          recordingFilenameRef.current = null;
        }
        return true;
      } else if (keyMatchers["app.toggleCopyMode" /* TOGGLE_COPY_MODE */](key) && !isAlternateBuffer) {
        showTransientMessage({
          text: "Use Ctrl+O to expand and collapse blocks of content.",
          type: "warning" /* Warning */
        });
        return true;
      }
      const toggleLastTurnTools = () => {
        triggerExpandHint(true);
        const targetToolCallIds = getLastTurnToolCallIds(
          historyManager.history,
          pendingHistoryItems
        );
        if (targetToolCallIds.length > 0) {
          toggleAllExpansion(targetToolCallIds);
        }
      };
      let enteringConstrainHeightMode = false;
      if (!constrainHeight) {
        enteringConstrainHeightMode = true;
        setConstrainHeight(true);
        if (keyMatchers["app.showMoreLines" /* SHOW_MORE_LINES */](key)) {
          toggleLastTurnTools();
        }
        if (!isAlternateBuffer) {
          refreshStatic();
        }
      }
      if (keyMatchers["app.showErrorDetails" /* SHOW_ERROR_DETAILS */](key)) {
        if (settings.merged.general.devtools) {
          void (async () => {
            const { toggleDevToolsPanel } = await import("./devtoolsService-2KNLVOTR.js");
            await toggleDevToolsPanel(
              config,
              showErrorDetails,
              () => setShowErrorDetails((prev) => !prev),
              () => setShowErrorDetails(true)
            );
          })();
        } else {
          setShowErrorDetails((prev) => !prev);
        }
        return true;
      } else if (keyMatchers["app.showFullTodos" /* SHOW_FULL_TODOS */](key)) {
        setShowFullTodos((prev) => !prev);
        return true;
      } else if (keyMatchers["app.toggleMarkdown" /* TOGGLE_MARKDOWN */](key)) {
        setRenderMarkdown((prev) => {
          const newValue = !prev;
          refreshStatic();
          return newValue;
        });
        return true;
      } else if (keyMatchers["app.showIdeContextDetail" /* SHOW_IDE_CONTEXT_DETAIL */](key) && config.getIdeMode() && ideContextState) {
        handleSlashCommand("/ide status");
        return true;
      } else if (keyMatchers["app.showMoreLines" /* SHOW_MORE_LINES */](key) && !enteringConstrainHeightMode) {
        setConstrainHeight(false);
        toggleLastTurnTools();
        refreshStatic();
        return true;
      } else if ((keyMatchers["app.focusShellInput" /* FOCUS_SHELL_INPUT */](key) || keyMatchers["background.unfocusList" /* UNFOCUS_BACKGROUND_SHELL_LIST */](key)) && (activePtyId || isBackgroundTaskVisible && backgroundTasks.size > 0)) {
        if (embeddedShellFocused) {
          const capturedTime = lastOutputTimeRef.current;
          if (tabFocusTimeoutRef.current)
            clearTimeout(tabFocusTimeoutRef.current);
          tabFocusTimeoutRef.current = setTimeout(() => {
            if (lastOutputTimeRef.current === capturedTime) {
              setEmbeddedShellFocused(false);
            } else {
              showTransientMessage({
                text: "Use Shift+Tab to unfocus",
                type: "warning" /* Warning */
              });
            }
          }, 150);
          return false;
        }
        const isIdle = Date.now() - lastOutputTimeRef.current >= 100;
        if (isIdle && !activePtyId && !isBackgroundTaskVisible) {
          if (tabFocusTimeoutRef.current)
            clearTimeout(tabFocusTimeoutRef.current);
          toggleBackgroundTasks();
          setEmbeddedShellFocused(true);
          if (backgroundTasks.size > 1) setIsBackgroundTaskListOpen(true);
          return true;
        }
        setEmbeddedShellFocused(true);
        return true;
      } else if (keyMatchers["app.unfocusShellInput" /* UNFOCUS_SHELL_INPUT */](key) || keyMatchers["background.unfocus" /* UNFOCUS_BACKGROUND_SHELL */](key)) {
        if (embeddedShellFocused) {
          setEmbeddedShellFocused(false);
          return true;
        }
        return false;
      } else if (keyMatchers["background.toggle" /* TOGGLE_BACKGROUND_SHELL */](key)) {
        if (activePtyId) {
          backgroundCurrentExecution();
        } else {
          toggleBackgroundTasks();
          if (!isBackgroundTaskVisible && backgroundTasks.size > 0) {
            setEmbeddedShellFocused(true);
            if (backgroundTasks.size > 1) {
              setIsBackgroundTaskListOpen(true);
            }
          } else {
            setEmbeddedShellFocused(false);
          }
        }
        return true;
      } else if (keyMatchers["background.toggleList" /* TOGGLE_BACKGROUND_SHELL_LIST */](key)) {
        if (backgroundTasks.size > 0 && isBackgroundTaskVisible) {
          if (!embeddedShellFocused) {
            setEmbeddedShellFocused(true);
          }
          setIsBackgroundTaskListOpen(true);
        }
        return true;
      }
      return false;
    },
    [
      constrainHeight,
      setConstrainHeight,
      setShowErrorDetails,
      config,
      ideContextState,
      handleCtrlCPress,
      handleCtrlDPress,
      handleSlashCommand,
      cancelOngoingRequest,
      activePtyId,
      handleSuspend,
      embeddedShellFocused,
      settings.merged.general.debugKeystrokeLogging,
      refreshStatic,
      setCopyModeEnabled,
      tabFocusTimeoutRef,
      isAlternateBuffer,
      shortcutsHelpVisible,
      backgroundCurrentExecution,
      toggleBackgroundTasks,
      backgroundTasks,
      isBackgroundTaskVisible,
      setIsBackgroundTaskListOpen,
      lastOutputTimeRef,
      showTransientMessage,
      settings.merged.general.devtools,
      showErrorDetails,
      triggerExpandHint,
      keyMatchers,
      isHelpDismissKey,
      historyManager.history,
      pendingHistoryItems,
      toggleAllExpansion,
      dumpCurrentFrame,
      startRecording,
      stopRecording,
      mouseMode
    ]
  );
  useKeypress(handleGlobalKeypress, { isActive: true, priority: true });
  useKeypress(
    (key) => {
      if (keyMatchers["scroll.up" /* SCROLL_UP */](key) || keyMatchers["scroll.down" /* SCROLL_DOWN */](key) || keyMatchers["scroll.pageUp" /* PAGE_UP */](key) || keyMatchers["scroll.pageDown" /* PAGE_DOWN */](key) || keyMatchers["scroll.home" /* SCROLL_HOME */](key) || keyMatchers["scroll.end" /* SCROLL_END */](key)) {
        return false;
      }
      setCopyModeEnabled(false);
      if (mouseMode) {
        enableMouseEvents();
      }
      return true;
    },
    {
      isActive: copyModeEnabled,
      // We need to receive keypresses first so they do not bubble to other
      // handlers.
      priority: 200 /* Critical */
    }
  );
  (0, import_react129.useEffect)(() => {
    if (settings.merged.ui.hideWindowTitle) return;
    const paddedTitle = computeTerminalTitle({
      streamingState,
      thoughtSubject: thought?.subject,
      isConfirming: !!commandConfirmationRequest || shouldShowActionRequiredTitle,
      isSilentWorking: shouldShowSilentWorkingTitle,
      folderName: basename4(config.getTargetDir()),
      showThoughts: !!settings.merged.ui.showStatusInTitle,
      useDynamicTitle: settings.merged.ui.dynamicWindowTitle
    });
    if (lastTitleRef.current !== paddedTitle) {
      lastTitleRef.current = paddedTitle;
      stdout.write(`\x1B]0;${paddedTitle}\x07`);
    }
  }, [
    streamingState,
    thought,
    commandConfirmationRequest,
    shouldShowActionRequiredTitle,
    shouldShowSilentWorkingTitle,
    settings.merged.ui.showStatusInTitle,
    settings.merged.ui.dynamicWindowTitle,
    settings.merged.ui.hideWindowTitle,
    config,
    stdout
  ]);
  (0, import_react129.useEffect)(() => {
    const handleUserFeedback = (payload) => {
      let type;
      switch (payload.severity) {
        case "error":
          type = "error" /* ERROR */;
          break;
        case "warning":
          type = "warning" /* WARNING */;
          break;
        case "info":
          type = "info" /* INFO */;
          break;
        default:
          throw new Error(
            `Unexpected severity for user feedback: ${payload.severity}`
          );
      }
      historyManager.addItem(
        {
          type,
          text: payload.message
        },
        Date.now()
      );
      if (payload.error) {
        debugLogger.warn(
          `[Feedback Details for "${payload.message}"]`,
          payload.error
        );
      }
    };
    const handleHookSystemMessage = (payload) => {
      historyManager.addItem(
        {
          type: "info" /* INFO */,
          text: payload.message,
          source: payload.hookName
        },
        Date.now()
      );
    };
    coreEvents.on(CoreEvent.UserFeedback, handleUserFeedback);
    coreEvents.on(CoreEvent.HookSystemMessage, handleHookSystemMessage);
    coreEvents.drainBacklogs();
    return () => {
      coreEvents.off(CoreEvent.UserFeedback, handleUserFeedback);
      coreEvents.off(CoreEvent.HookSystemMessage, handleHookSystemMessage);
    };
  }, [historyManager]);
  const nightly = props.version.includes("nightly");
  const dialogsVisible = shouldShowIdePrompt || shouldShowIdePrompt || isFolderTrustDialogOpen || isPolicyUpdateDialogOpen || adminSettingsChanged || !!commandConfirmationRequest || !!authConsentRequest || !!permissionConfirmationRequest || !!customDialog || confirmUpdateExtensionRequests.length > 0 || !!loopDetectionConfirmationRequest || isThemeDialogOpen || isSettingsDialogOpen || isModelDialogOpen || isAgentConfigDialogOpen || isPermissionsDialogOpen || isAuthenticating || isAuthDialogOpen || isEditorDialogOpen || showPrivacyNotice || showIdeRestartPrompt || !!proQuotaRequest || !!validationRequest || !!overageMenuRequest || !!emptyWalletRequest || isSessionBrowserOpen || authState === "awaiting_api_key_input" /* AwaitingApiKeyInput */ || !!newAgents;
  const hasPendingToolConfirmation = (0, import_react129.useMemo)(
    () => isToolAwaitingConfirmation(pendingHistoryItems),
    [pendingHistoryItems]
  );
  const hasConfirmUpdateExtensionRequests = confirmUpdateExtensionRequests.length > 0;
  const hasLoopDetectionConfirmationRequest = !!loopDetectionConfirmationRequest;
  const hasPendingActionRequired = hasPendingToolConfirmation || !!commandConfirmationRequest || !!authConsentRequest || hasConfirmUpdateExtensionRequests || hasLoopDetectionConfirmationRequest || !!proQuotaRequest || !!validationRequest || !!overageMenuRequest || !!emptyWalletRequest || !!customDialog;
  const loadingPhrases = settings.merged.ui.loadingPhrases;
  const showStatusTips = loadingPhrases === "tips" || loadingPhrases === "all";
  const showStatusWit = loadingPhrases === "witty" || loadingPhrases === "all";
  const showLoadingIndicator = (!embeddedShellFocused || isBackgroundTaskVisible) && streamingState === "responding" /* Responding */ && !hasPendingActionRequired;
  let estimatedStatusLength = 0;
  if (activeHooks.length > 0 && settings.merged.hooksConfig.notifications) {
    const hookLabel = activeHooks.length > 1 ? "Executing Hooks" : "Executing Hook";
    const hookNames = activeHooks.map(
      (h) => h.name + (h.index && h.total && h.total > 1 ? ` (${h.index}/${h.total})` : "")
    ).join(", ");
    estimatedStatusLength = hookLabel.length + hookNames.length + 10;
  } else if (showLoadingIndicator) {
    const thoughtText = thought?.subject || "Waiting for model...";
    estimatedStatusLength = thoughtText.length + 25;
  } else if (hasPendingActionRequired) {
    estimatedStatusLength = 35;
  }
  const maxLength = terminalWidth - estimatedStatusLength - 5;
  const { elapsedTime, currentLoadingPhrase, currentTip, currentWittyPhrase } = useLoadingIndicator({
    streamingState,
    shouldShowFocusHint,
    retryStatus,
    showTips: showStatusTips,
    showWit: showStatusWit,
    customWittyPhrases: settings.merged.ui.customWittyPhrases,
    errorVerbosity: settings.merged.ui.errorVerbosity,
    maxLength
  });
  const allowPlanMode = config.isPlanEnabled() && streamingState === "idle" /* Idle */ && !hasPendingActionRequired;
  const showApprovalModeIndicator = useApprovalModeIndicator({
    config,
    addItem: historyManager.addItem,
    onApprovalModeChange: handleApprovalModeChangeWithUiReveal,
    isActive: !embeddedShellFocused,
    allowPlanMode
  });
  useRunEventNotifications({
    notificationsEnabled,
    isFocused,
    hasReceivedFocusEvent,
    streamingState,
    hasPendingActionRequired,
    pendingHistoryItems,
    commandConfirmationRequest,
    authConsentRequest,
    permissionConfirmationRequest,
    hasConfirmUpdateExtensionRequests,
    hasLoopDetectionConfirmationRequest
  });
  const isPassiveShortcutsHelpState = isInputActive && streamingState === "idle" /* Idle */ && !hasPendingActionRequired;
  (0, import_react129.useEffect)(() => {
    if (shortcutsHelpVisible && !isPassiveShortcutsHelpState) {
      setShortcutsHelpVisible(false);
    }
  }, [
    shortcutsHelpVisible,
    isPassiveShortcutsHelpState,
    setShortcutsHelpVisible
  ]);
  (0, import_react129.useEffect)(() => {
    if (!isConfigInitialized || !config.isModelSteeringEnabled() || streamingState !== "idle" /* Idle */ || !isMcpReady || isToolAwaitingConfirmation(pendingHistoryItems)) {
      return;
    }
    const pendingHint = consumePendingHints();
    if (!pendingHint) {
      return;
    }
    void submitQuery([{ text: buildUserSteeringHintPrompt(pendingHint) }]);
  }, [
    config,
    historyManager,
    isConfigInitialized,
    isMcpReady,
    streamingState,
    submitQuery,
    consumePendingHints,
    pendingHistoryItems,
    pendingHintCount
  ]);
  const allToolCalls = (0, import_react129.useMemo)(
    () => getAllToolCalls(pendingHistoryItems),
    [pendingHistoryItems]
  );
  const [geminiMdFileCount, setGeminiMdFileCount] = (0, import_react129.useState)(
    config.getGeminiMdFileCount()
  );
  (0, import_react129.useEffect)(() => {
    const handleMemoryChanged = (result) => {
      setGeminiMdFileCount(result.fileCount);
    };
    coreEvents.on(CoreEvent.MemoryChanged, handleMemoryChanged);
    return () => {
      coreEvents.off(CoreEvent.MemoryChanged, handleMemoryChanged);
    };
  }, []);
  (0, import_react129.useEffect)(() => {
    let isMounted = true;
    const fetchBannerTexts = async () => {
      const [defaultBanner, warningBanner] = await Promise.all([
        config.getBannerTextNoCapacityIssues(),
        config.getBannerTextCapacityIssues()
      ]);
      if (isMounted) {
        setDefaultBannerText(defaultBanner);
        setWarningBannerText(warningBanner);
        setBannerVisible(true);
      }
    };
    fetchBannerTexts();
    return () => {
      isMounted = false;
    };
  }, [config, refreshStatic]);
  const inputState = (0, import_react129.useMemo)(
    () => ({
      buffer,
      userMessages: inputHistory,
      shellModeActive,
      showEscapePrompt,
      copyModeEnabled,
      inputWidth,
      suggestionsWidth
    }),
    [
      buffer,
      inputHistory,
      shellModeActive,
      showEscapePrompt,
      copyModeEnabled,
      inputWidth,
      suggestionsWidth
    ]
  );
  const uiState = (0, import_react129.useMemo)(
    () => ({
      history: historyManager.history,
      historyManager,
      isThemeDialogOpen,
      themeError,
      isAuthenticating,
      isConfigInitialized,
      authError,
      accountSuspensionInfo,
      isAuthDialogOpen,
      isAwaitingApiKeyInput: authState === "awaiting_api_key_input" /* AwaitingApiKeyInput */,
      apiKeyDefaultValue,
      editorError,
      isEditorDialogOpen,
      showPrivacyNotice,
      mouseMode,
      corgiMode,
      debugMessage,
      quittingMessages,
      isSettingsDialogOpen,
      isSessionBrowserOpen,
      isModelDialogOpen,
      isAgentConfigDialogOpen,
      selectedAgentName,
      selectedAgentDisplayName,
      selectedAgentDefinition,
      isPermissionsDialogOpen,
      permissionsDialogProps,
      slashCommands,
      pendingSlashCommandHistoryItems,
      commandContext,
      commandConfirmationRequest,
      authConsentRequest,
      confirmUpdateExtensionRequests,
      loopDetectionConfirmationRequest,
      permissionConfirmationRequest,
      geminiMdFileCount,
      streamingState,
      initError,
      pendingGeminiHistoryItems,
      thought,
      isInputActive,
      isResuming,
      shouldShowIdePrompt,
      isFolderTrustDialogOpen: isFolderTrustDialogOpen ?? false,
      folderDiscoveryResults,
      isPolicyUpdateDialogOpen,
      policyUpdateConfirmationRequest,
      isTrustedFolder,
      constrainHeight,
      showErrorDetails,
      showFullTodos,
      ideContextState,
      renderMarkdown,
      ctrlCPressedOnce: ctrlCPressCount >= 1,
      ctrlDPressedOnce: ctrlDPressCount >= 1,
      shortcutsHelpVisible,
      cleanUiDetailsVisible,
      isFocused,
      elapsedTime,
      currentLoadingPhrase,
      currentTip,
      currentWittyPhrase,
      historyRemountKey,
      activeHooks,
      messageQueue: messageQueue2,
      queueErrorMessage,
      showApprovalModeIndicator,
      allowPlanMode,
      currentModel,
      quota: {
        userTier,
        stats: quotaStats,
        proQuotaRequest,
        validationRequest,
        // G1 AI Credits dialog state
        overageMenuRequest,
        emptyWalletRequest
      },
      contextFileNames,
      errorCount,
      availableTerminalHeight,
      stableControlsHeight,
      mainAreaWidth,
      staticAreaMaxItemHeight,
      staticExtraHeight,
      dialogsVisible,
      pendingHistoryItems,
      nightly,
      branchName,
      sessionStats,
      terminalWidth,
      terminalHeight,
      mainControlsRef,
      rootUiRef,
      currentIDE,
      updateInfo,
      showIdeRestartPrompt,
      ideTrustRestartReason,
      isRestarting,
      extensionsUpdateState,
      activePtyId,
      backgroundTaskCount,
      isBackgroundTaskVisible,
      embeddedShellFocused,
      showDebugProfiler,
      customDialog,
      transientMessage,
      bannerData,
      bannerVisible,
      terminalBackgroundColor: config.getTerminalBackground(),
      settingsNonce,
      backgroundTasks,
      activeBackgroundTaskPid,
      backgroundTaskHeight,
      isBackgroundTaskListOpen,
      adminSettingsChanged,
      newAgents,
      showIsExpandableHint,
      hintMode: config.isModelSteeringEnabled() && isToolExecuting(pendingHistoryItems),
      hintBuffer: ""
    }),
    [
      isThemeDialogOpen,
      themeError,
      isAuthenticating,
      isConfigInitialized,
      authError,
      accountSuspensionInfo,
      isAuthDialogOpen,
      editorError,
      isEditorDialogOpen,
      showPrivacyNotice,
      mouseMode,
      corgiMode,
      debugMessage,
      quittingMessages,
      isSettingsDialogOpen,
      isSessionBrowserOpen,
      isModelDialogOpen,
      isAgentConfigDialogOpen,
      selectedAgentName,
      selectedAgentDisplayName,
      selectedAgentDefinition,
      isPermissionsDialogOpen,
      permissionsDialogProps,
      slashCommands,
      pendingSlashCommandHistoryItems,
      commandContext,
      commandConfirmationRequest,
      authConsentRequest,
      confirmUpdateExtensionRequests,
      loopDetectionConfirmationRequest,
      permissionConfirmationRequest,
      geminiMdFileCount,
      streamingState,
      initError,
      pendingGeminiHistoryItems,
      thought,
      isInputActive,
      isResuming,
      shouldShowIdePrompt,
      isFolderTrustDialogOpen,
      folderDiscoveryResults,
      isPolicyUpdateDialogOpen,
      policyUpdateConfirmationRequest,
      isTrustedFolder,
      constrainHeight,
      showErrorDetails,
      showFullTodos,
      ideContextState,
      renderMarkdown,
      ctrlCPressCount,
      ctrlDPressCount,
      shortcutsHelpVisible,
      cleanUiDetailsVisible,
      isFocused,
      elapsedTime,
      currentLoadingPhrase,
      currentTip,
      currentWittyPhrase,
      historyRemountKey,
      activeHooks,
      messageQueue2,
      queueErrorMessage,
      showApprovalModeIndicator,
      allowPlanMode,
      userTier,
      quotaStats,
      proQuotaRequest,
      validationRequest,
      overageMenuRequest,
      emptyWalletRequest,
      contextFileNames,
      errorCount,
      availableTerminalHeight,
      stableControlsHeight,
      mainAreaWidth,
      staticAreaMaxItemHeight,
      staticExtraHeight,
      dialogsVisible,
      pendingHistoryItems,
      nightly,
      branchName,
      sessionStats,
      terminalWidth,
      terminalHeight,
      mainControlsRef,
      rootUiRef,
      currentIDE,
      updateInfo,
      showIdeRestartPrompt,
      ideTrustRestartReason,
      isRestarting,
      currentModel,
      extensionsUpdateState,
      activePtyId,
      backgroundTaskCount,
      isBackgroundTaskVisible,
      historyManager,
      embeddedShellFocused,
      showDebugProfiler,
      customDialog,
      apiKeyDefaultValue,
      authState,
      transientMessage,
      bannerData,
      bannerVisible,
      config,
      settingsNonce,
      backgroundTaskHeight,
      isBackgroundTaskListOpen,
      activeBackgroundTaskPid,
      backgroundTasks,
      adminSettingsChanged,
      newAgents,
      showIsExpandableHint
    ]
  );
  const exitPrivacyNotice = (0, import_react129.useCallback)(
    () => setShowPrivacyNotice(false),
    [setShowPrivacyNotice]
  );
  const uiActions = (0, import_react129.useMemo)(
    () => ({
      handleThemeSelect,
      closeThemeDialog,
      handleThemeHighlight,
      handleAuthSelect,
      setAuthState,
      onAuthError,
      handleEditorSelect,
      exitEditorDialog,
      exitPrivacyNotice,
      closeSettingsDialog,
      closeModelDialog,
      openAgentConfigDialog,
      closeAgentConfigDialog,
      openPermissionsDialog,
      closePermissionsDialog,
      setShellModeActive,
      vimHandleInput,
      handleIdePromptComplete,
      handleFolderTrustSelect,
      setIsPolicyUpdateDialogOpen,
      setConstrainHeight,
      onEscapePromptChange: handleEscapePromptChange,
      refreshStatic,
      handleFinalSubmit,
      handleClearScreen,
      handleProQuotaChoice,
      handleValidationChoice,
      // G1 AI Credits handlers
      handleOverageMenuChoice,
      handleEmptyWalletChoice,
      openSessionBrowser,
      closeSessionBrowser,
      handleResumeSession,
      handleDeleteSession,
      setQueueErrorMessage,
      addMessage,
      popAllMessages,
      handleApiKeySubmit,
      handleApiKeyCancel,
      setBannerVisible,
      setShortcutsHelpVisible,
      setCleanUiDetailsVisible,
      toggleCleanUiDetailsVisible,
      revealCleanUiDetailsTemporarily,
      handleWarning,
      setEmbeddedShellFocused,
      dismissBackgroundTask,
      setActiveBackgroundTaskPid,
      setIsBackgroundTaskListOpen,
      setAuthContext,
      onHintInput: () => {
      },
      onHintBackspace: () => {
      },
      onHintClear: () => {
      },
      onHintSubmit: () => {
      },
      handleRestart: async () => {
        if (process14.send) {
          const remoteSettings = config.getRemoteAdminSettings();
          if (remoteSettings) {
            process14.send({
              type: "admin-settings-update",
              settings: remoteSettings
            });
          }
        }
        await relaunchApp();
      },
      handleNewAgentsSelect: async (choice) => {
        if (newAgents && choice === "acknowledge" /* ACKNOWLEDGE */) {
          const registry = config.getAgentRegistry();
          try {
            await Promise.all(
              newAgents.map((agent) => registry.acknowledgeAgent(agent))
            );
          } catch (error) {
            debugLogger.error("Failed to acknowledge agents:", error);
            historyManager.addItem(
              {
                type: "error" /* ERROR */,
                text: `Failed to acknowledge agents: ${getErrorMessage(error)}`
              },
              Date.now()
            );
          }
        }
        setNewAgents(null);
      },
      getPreferredEditor,
      clearAccountSuspension: () => {
        setAccountSuspensionInfo(null);
        setAuthState("updating" /* Updating */);
      }
    }),
    [
      handleThemeSelect,
      closeThemeDialog,
      handleThemeHighlight,
      handleAuthSelect,
      setAuthState,
      onAuthError,
      handleEditorSelect,
      exitEditorDialog,
      exitPrivacyNotice,
      closeSettingsDialog,
      closeModelDialog,
      openAgentConfigDialog,
      closeAgentConfigDialog,
      openPermissionsDialog,
      closePermissionsDialog,
      setShellModeActive,
      vimHandleInput,
      handleIdePromptComplete,
      handleFolderTrustSelect,
      setIsPolicyUpdateDialogOpen,
      setConstrainHeight,
      handleEscapePromptChange,
      refreshStatic,
      handleFinalSubmit,
      handleClearScreen,
      handleProQuotaChoice,
      handleValidationChoice,
      handleOverageMenuChoice,
      handleEmptyWalletChoice,
      openSessionBrowser,
      closeSessionBrowser,
      handleResumeSession,
      handleDeleteSession,
      setQueueErrorMessage,
      addMessage,
      popAllMessages,
      handleApiKeySubmit,
      handleApiKeyCancel,
      setBannerVisible,
      setShortcutsHelpVisible,
      setCleanUiDetailsVisible,
      toggleCleanUiDetailsVisible,
      revealCleanUiDetailsTemporarily,
      handleWarning,
      setEmbeddedShellFocused,
      dismissBackgroundTask,
      setActiveBackgroundTaskPid,
      setIsBackgroundTaskListOpen,
      setAuthContext,
      setAccountSuspensionInfo,
      newAgents,
      config,
      historyManager,
      getPreferredEditor
    ]
  );
  if (authState === "awaiting_google_login_restart" /* AwaitingGoogleLoginRestart */) {
    return /* @__PURE__ */ (0, import_jsx_runtime142.jsx)(
      LoginWithGoogleRestartDialog,
      {
        onDismiss: () => {
          setAuthContext({});
          setAuthState("updating" /* Updating */);
        },
        config
      }
    );
  }
  return /* @__PURE__ */ (0, import_jsx_runtime142.jsx)(UIStateContext.Provider, { value: uiState, children: /* @__PURE__ */ (0, import_jsx_runtime142.jsx)(InputContext.Provider, { value: inputState, children: /* @__PURE__ */ (0, import_jsx_runtime142.jsx)(UIActionsContext.Provider, { value: uiActions, children: /* @__PURE__ */ (0, import_jsx_runtime142.jsx)(ConfigContext.Provider, { value: config, children: /* @__PURE__ */ (0, import_jsx_runtime142.jsx)(
    AppContext.Provider,
    {
      value: {
        version: props.version,
        startupWarnings: props.startupWarnings || []
      },
      children: /* @__PURE__ */ (0, import_jsx_runtime142.jsx)(
        ToolActionsProvider,
        {
          config,
          toolCalls: allToolCalls,
          isExpanded,
          toggleExpansion,
          toggleAllExpansion,
          children: /* @__PURE__ */ (0, import_jsx_runtime142.jsx)(ShellFocusContext.Provider, { value: isFocused, children: /* @__PURE__ */ (0, import_jsx_runtime142.jsx)(MouseProvider, { mouseEventsEnabled: mouseMode, children: /* @__PURE__ */ (0, import_jsx_runtime142.jsx)(ScrollProvider, { children: /* @__PURE__ */ (0, import_jsx_runtime142.jsx)(App, {}, `app-${forceRerenderKey}`) }) }) })
        }
      )
    }
  ) }) }) }) });
};

// packages/cli/src/interactiveCli.tsx
var import_jsx_runtime143 = __toESM(require_jsx_runtime(), 1);
var SLOW_RENDER_MS = 200;
async function startInteractiveUI(config, settings, startupWarnings, workspaceRoot = process.cwd(), resumedSessionData, initializationResult) {
  initializeConsoleStore();
  const useAlternateBuffer2 = shouldEnterAlternateScreen(
    config.getUseAlternateBuffer(),
    config.getScreenReader()
  );
  const mouseEventsEnabled = useAlternateBuffer2;
  if (mouseEventsEnabled) {
    enableMouseEvents();
    registerCleanup(() => {
      disableMouseEvents();
    });
  }
  const { matchers, errors } = await loadKeyMatchers();
  errors.forEach((error) => {
    coreEvents.emitFeedback("warning", error);
  });
  const version = await getVersion();
  setWindowTitle(basename5(workspaceRoot), settings);
  const consolePatcher = new ConsolePatcher({
    onNewMessage: (msg) => {
      coreEvents.emitConsoleLog(msg.type, msg.content);
    },
    debugMode: config.getDebugMode()
  });
  consolePatcher.patch();
  registerCleanup(consolePatcher.cleanup);
  const { stdout: inkStdout, stderr: inkStderr } = createWorkingStdio();
  const isShpool = !!process.env["SHPOOL_SESSION_NAME"];
  const AppWrapper = () => {
    useKittyKeyboardProtocol();
    return /* @__PURE__ */ (0, import_jsx_runtime143.jsx)(SettingsContext.Provider, { value: settings, children: /* @__PURE__ */ (0, import_jsx_runtime143.jsx)(KeyMatchersProvider, { value: matchers, children: /* @__PURE__ */ (0, import_jsx_runtime143.jsx)(KeypressProvider, { config, children: /* @__PURE__ */ (0, import_jsx_runtime143.jsx)(MouseProvider, { mouseEventsEnabled, children: /* @__PURE__ */ (0, import_jsx_runtime143.jsx)(TerminalProvider, { children: /* @__PURE__ */ (0, import_jsx_runtime143.jsx)(ScrollProvider, { children: /* @__PURE__ */ (0, import_jsx_runtime143.jsx)(OverflowProvider, { children: /* @__PURE__ */ (0, import_jsx_runtime143.jsx)(SessionStatsProvider, { children: /* @__PURE__ */ (0, import_jsx_runtime143.jsx)(VimModeProvider, { children: /* @__PURE__ */ (0, import_jsx_runtime143.jsx)(
      AppContainer,
      {
        config,
        startupWarnings,
        version,
        resumedSessionData,
        initializationResult
      }
    ) }) }) }) }) }) }) }) }) });
  };
  if (isShpool) {
    await new Promise((resolve3) => setTimeout(resolve3, 100));
  }
  const instance = render_default(
    process.env["DEBUG"] ? /* @__PURE__ */ (0, import_jsx_runtime143.jsx)(import_react130.default.StrictMode, { children: /* @__PURE__ */ (0, import_jsx_runtime143.jsx)(AppWrapper, {}) }) : /* @__PURE__ */ (0, import_jsx_runtime143.jsx)(AppWrapper, {}),
    {
      stdout: inkStdout,
      stderr: inkStderr,
      stdin: process.stdin,
      exitOnCtrlC: false,
      isScreenReaderEnabled: config.getScreenReader(),
      onRender: ({ renderTime }) => {
        if (renderTime > SLOW_RENDER_MS) {
          recordSlowRender(config, renderTime);
        }
        profiler.reportFrameRendered();
      },
      standardReactLayoutTiming: useAlternateBuffer2 || config.getUseTerminalBuffer(),
      patchConsole: false,
      alternateBuffer: useAlternateBuffer2,
      terminalBuffer: config.getUseTerminalBuffer(),
      renderProcess: config.getUseRenderProcess() && config.getUseTerminalBuffer(),
      incrementalRendering: settings.merged.ui.incrementalRendering !== false && useAlternateBuffer2 && !isShpool
    }
  );
  if (useAlternateBuffer2) {
    disableLineWrapping();
    registerCleanup(() => {
      enableLineWrapping();
    });
  }
  checkForUpdates(settings).then((info) => {
    handleAutoUpdate(info, settings, config.getProjectRoot());
  }).catch((err) => {
    if (config.getDebugMode()) {
      debugLogger.warn("Update check failed:", err);
    }
  });
  registerCleanup(() => instance.unmount());
  registerCleanup(setupTtyCheck());
}
function setWindowTitle(title, settings) {
  if (!settings.merged.ui.hideWindowTitle) {
    const windowTitle = computeTerminalTitle({
      streamingState: "idle" /* Idle */,
      isConfirming: false,
      isSilentWorking: false,
      folderName: title,
      showThoughts: !!settings.merged.ui.showStatusInTitle,
      useDynamicTitle: settings.merged.ui.dynamicWindowTitle
    });
    writeToStdout(`\x1B]0;${windowTitle}\x07`);
    process.on("exit", () => {
      writeToStdout(`\x1B]0;\x07`);
    });
  }
}
export {
  startInteractiveUI
};
/**
 * @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:

deep-extend/lib/deep-extend.js:
  (*!
   * @description Recursive object extending
   * @author Viacheslav Lotsmanov <lotsmanov89@gmail.com>
   * @license MIT
   *
   * The MIT License (MIT)
   *
   * Copyright (c) 2013-2018 Viacheslav Lotsmanov
   *
   * Permission is hereby granted, free of charge, to any person obtaining a copy of
   * this software and associated documentation files (the "Software"), to deal in
   * the Software without restriction, including without limitation the rights to
   * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
   * the Software, and to permit persons to whom the Software is furnished to do so,
   * subject to the following conditions:
   *
   * The above copyright notice and this permission notice shall be included in all
   * copies or substantial portions of the Software.
   *
   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
   * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
   * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
   * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
   * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
   *)

ky/distribution/index.js:
  (*! MIT License © Sindre Sorhus *)
*/
