// Force strict mode and setup for ESM
"use strict";
import {
  relaunchApp
} from "./chunk-43A7KWZN.js";
import {
  SHELL_COMMAND_NAME,
  SHELL_NAME,
  TOOL_STATUS,
  formatSupportedModes,
  getCommandDisplayName,
  getCommandSourceBadge,
  getCommandSourceGroup,
  getCommandSubcommandNames,
  useSessionStats
} from "./chunk-AR4VP4WD.js";
import {
  Colors,
  RowMouseController,
  SettingsContext,
  measureElementPosition,
  useMouseEvents,
  useSettings,
  useTerminalSize
} from "./chunk-6OOS3TNP.js";
import {
  buildResumedHistoryItems,
  calculateAverageLatency,
  calculateCacheHitRate,
  calculateCost,
  calculateErrorRate,
  computeDiffColumnWidths,
  computeSessionStats,
  getSystemInfoFields,
  levelLabel,
  useKeypress,
  wrapForMultiplexer
} from "./chunk-RMXPR6HS.js";
import {
  isTerminalGoalStatusKind
} from "./chunk-KSPVDFE4.js";
import {
  MINIMUM_MAX_HEIGHT,
  MaxSizedBox
} from "./chunk-QZTJVXI3.js";
import {
  theme
} from "./chunk-VXGPYF7U.js";
import {
  Box_default,
  Static,
  Text,
  Transform,
  require_jsx_runtime,
  use_is_screen_reader_enabled_default,
  use_stdin_default
} from "./chunk-4FRUXVSE.js";
import {
  require_react
} from "./chunk-KYMBIKIW.js";
import {
  resolveColor,
  themeManager
} from "./chunk-HTWHAN44.js";
import {
  require_has_flag,
  require_source
} from "./chunk-3GONHQOA.js";
import {
  cpLen,
  cpSlice,
  eastAsianWidth,
  escapeAnsiCtrlCodes,
  getCachedStringWidth,
  sanitizeSensitiveText,
  stringWidth,
  stripUnsafeCharacters,
  toCodePoints,
  wrapToVisualLines
} from "./chunk-UVNBI7NN.js";
import {
  formatDuration,
  formatMemoryUsage,
  formatRelativeTime,
  formatTokenCount
} from "./chunk-KHDZHZMH.js";
import {
  createLoadedSettingsAdapter
} from "./chunk-4GWFOP6B.js";
import {
  getPersistScopeForModelSelection
} from "./chunk-AFPB2TZB.js";
import {
  getCurrentLanguage,
  localizeToolDisplayName,
  t
} from "./chunk-RYT2ET4O.js";
import {
  isWorkspaceTrusted
} from "./chunk-CJSSVQAR.js";
import {
  ALL_PROVIDERS,
  IdeClient,
  PROVIDER_METADATA_NS,
  ShellExecutionService,
  allowEditorTypeInSandbox,
  applyProviderInstallPlan,
  buildHumanReadableRuleLabel,
  buildInstallPlan,
  buildProviderTemplate,
  computeModelListVersion,
  getDefaultModelIds,
  getExtensionDisplayName,
  getExternalEditorCommand,
  ideContextStore,
  isValidEditorType,
  resolveBaseUrl,
  resolveMetadataKey,
  resolveOwnsModel,
  stripAnsi
} from "./chunk-IQ7FOOIH.js";
import {
  MAIN_SOURCE,
  getMCPServerStatus
} from "./chunk-4IUH45NF.js";
import {
  ToolDisplayNames,
  ToolNames,
  ToolNamesMigration
} from "./chunk-MJKMIQMK.js";
import {
  createDebugLogger,
  escapePath,
  unescapePath
} from "./chunk-AVQDCKNF.js";
import {
  init_esbuild_shims
} from "./chunk-A4BMJM77.js";
import {
  __commonJS,
  __name,
  __require,
  __toESM
} from "./chunk-J2S4EL5Y.js";

// node_modules/cli-spinners/spinners.json
var require_spinners = __commonJS({
  "node_modules/cli-spinners/spinners.json"(exports, module) {
    module.exports = {
      dots: {
        interval: 80,
        frames: [
          "\u280B",
          "\u2819",
          "\u2839",
          "\u2838",
          "\u283C",
          "\u2834",
          "\u2826",
          "\u2827",
          "\u2807",
          "\u280F"
        ]
      },
      dots2: {
        interval: 80,
        frames: [
          "\u28FE",
          "\u28FD",
          "\u28FB",
          "\u28BF",
          "\u287F",
          "\u28DF",
          "\u28EF",
          "\u28F7"
        ]
      },
      dots3: {
        interval: 80,
        frames: [
          "\u280B",
          "\u2819",
          "\u281A",
          "\u281E",
          "\u2816",
          "\u2826",
          "\u2834",
          "\u2832",
          "\u2833",
          "\u2813"
        ]
      },
      dots4: {
        interval: 80,
        frames: [
          "\u2804",
          "\u2806",
          "\u2807",
          "\u280B",
          "\u2819",
          "\u2838",
          "\u2830",
          "\u2820",
          "\u2830",
          "\u2838",
          "\u2819",
          "\u280B",
          "\u2807",
          "\u2806"
        ]
      },
      dots5: {
        interval: 80,
        frames: [
          "\u280B",
          "\u2819",
          "\u281A",
          "\u2812",
          "\u2802",
          "\u2802",
          "\u2812",
          "\u2832",
          "\u2834",
          "\u2826",
          "\u2816",
          "\u2812",
          "\u2810",
          "\u2810",
          "\u2812",
          "\u2813",
          "\u280B"
        ]
      },
      dots6: {
        interval: 80,
        frames: [
          "\u2801",
          "\u2809",
          "\u2819",
          "\u281A",
          "\u2812",
          "\u2802",
          "\u2802",
          "\u2812",
          "\u2832",
          "\u2834",
          "\u2824",
          "\u2804",
          "\u2804",
          "\u2824",
          "\u2834",
          "\u2832",
          "\u2812",
          "\u2802",
          "\u2802",
          "\u2812",
          "\u281A",
          "\u2819",
          "\u2809",
          "\u2801"
        ]
      },
      dots7: {
        interval: 80,
        frames: [
          "\u2808",
          "\u2809",
          "\u280B",
          "\u2813",
          "\u2812",
          "\u2810",
          "\u2810",
          "\u2812",
          "\u2816",
          "\u2826",
          "\u2824",
          "\u2820",
          "\u2820",
          "\u2824",
          "\u2826",
          "\u2816",
          "\u2812",
          "\u2810",
          "\u2810",
          "\u2812",
          "\u2813",
          "\u280B",
          "\u2809",
          "\u2808"
        ]
      },
      dots8: {
        interval: 80,
        frames: [
          "\u2801",
          "\u2801",
          "\u2809",
          "\u2819",
          "\u281A",
          "\u2812",
          "\u2802",
          "\u2802",
          "\u2812",
          "\u2832",
          "\u2834",
          "\u2824",
          "\u2804",
          "\u2804",
          "\u2824",
          "\u2820",
          "\u2820",
          "\u2824",
          "\u2826",
          "\u2816",
          "\u2812",
          "\u2810",
          "\u2810",
          "\u2812",
          "\u2813",
          "\u280B",
          "\u2809",
          "\u2808",
          "\u2808"
        ]
      },
      dots9: {
        interval: 80,
        frames: [
          "\u28B9",
          "\u28BA",
          "\u28BC",
          "\u28F8",
          "\u28C7",
          "\u2867",
          "\u2857",
          "\u284F"
        ]
      },
      dots10: {
        interval: 80,
        frames: [
          "\u2884",
          "\u2882",
          "\u2881",
          "\u2841",
          "\u2848",
          "\u2850",
          "\u2860"
        ]
      },
      dots11: {
        interval: 100,
        frames: [
          "\u2801",
          "\u2802",
          "\u2804",
          "\u2840",
          "\u2880",
          "\u2820",
          "\u2810",
          "\u2808"
        ]
      },
      dots12: {
        interval: 80,
        frames: [
          "\u2880\u2800",
          "\u2840\u2800",
          "\u2804\u2800",
          "\u2882\u2800",
          "\u2842\u2800",
          "\u2805\u2800",
          "\u2883\u2800",
          "\u2843\u2800",
          "\u280D\u2800",
          "\u288B\u2800",
          "\u284B\u2800",
          "\u280D\u2801",
          "\u288B\u2801",
          "\u284B\u2801",
          "\u280D\u2809",
          "\u280B\u2809",
          "\u280B\u2809",
          "\u2809\u2819",
          "\u2809\u2819",
          "\u2809\u2829",
          "\u2808\u2899",
          "\u2808\u2859",
          "\u2888\u2829",
          "\u2840\u2899",
          "\u2804\u2859",
          "\u2882\u2829",
          "\u2842\u2898",
          "\u2805\u2858",
          "\u2883\u2828",
          "\u2843\u2890",
          "\u280D\u2850",
          "\u288B\u2820",
          "\u284B\u2880",
          "\u280D\u2841",
          "\u288B\u2801",
          "\u284B\u2801",
          "\u280D\u2809",
          "\u280B\u2809",
          "\u280B\u2809",
          "\u2809\u2819",
          "\u2809\u2819",
          "\u2809\u2829",
          "\u2808\u2899",
          "\u2808\u2859",
          "\u2808\u2829",
          "\u2800\u2899",
          "\u2800\u2859",
          "\u2800\u2829",
          "\u2800\u2898",
          "\u2800\u2858",
          "\u2800\u2828",
          "\u2800\u2890",
          "\u2800\u2850",
          "\u2800\u2820",
          "\u2800\u2880",
          "\u2800\u2840"
        ]
      },
      dots13: {
        interval: 80,
        frames: [
          "\u28FC",
          "\u28F9",
          "\u28BB",
          "\u283F",
          "\u285F",
          "\u28CF",
          "\u28E7",
          "\u28F6"
        ]
      },
      dots8Bit: {
        interval: 80,
        frames: [
          "\u2800",
          "\u2801",
          "\u2802",
          "\u2803",
          "\u2804",
          "\u2805",
          "\u2806",
          "\u2807",
          "\u2840",
          "\u2841",
          "\u2842",
          "\u2843",
          "\u2844",
          "\u2845",
          "\u2846",
          "\u2847",
          "\u2808",
          "\u2809",
          "\u280A",
          "\u280B",
          "\u280C",
          "\u280D",
          "\u280E",
          "\u280F",
          "\u2848",
          "\u2849",
          "\u284A",
          "\u284B",
          "\u284C",
          "\u284D",
          "\u284E",
          "\u284F",
          "\u2810",
          "\u2811",
          "\u2812",
          "\u2813",
          "\u2814",
          "\u2815",
          "\u2816",
          "\u2817",
          "\u2850",
          "\u2851",
          "\u2852",
          "\u2853",
          "\u2854",
          "\u2855",
          "\u2856",
          "\u2857",
          "\u2818",
          "\u2819",
          "\u281A",
          "\u281B",
          "\u281C",
          "\u281D",
          "\u281E",
          "\u281F",
          "\u2858",
          "\u2859",
          "\u285A",
          "\u285B",
          "\u285C",
          "\u285D",
          "\u285E",
          "\u285F",
          "\u2820",
          "\u2821",
          "\u2822",
          "\u2823",
          "\u2824",
          "\u2825",
          "\u2826",
          "\u2827",
          "\u2860",
          "\u2861",
          "\u2862",
          "\u2863",
          "\u2864",
          "\u2865",
          "\u2866",
          "\u2867",
          "\u2828",
          "\u2829",
          "\u282A",
          "\u282B",
          "\u282C",
          "\u282D",
          "\u282E",
          "\u282F",
          "\u2868",
          "\u2869",
          "\u286A",
          "\u286B",
          "\u286C",
          "\u286D",
          "\u286E",
          "\u286F",
          "\u2830",
          "\u2831",
          "\u2832",
          "\u2833",
          "\u2834",
          "\u2835",
          "\u2836",
          "\u2837",
          "\u2870",
          "\u2871",
          "\u2872",
          "\u2873",
          "\u2874",
          "\u2875",
          "\u2876",
          "\u2877",
          "\u2838",
          "\u2839",
          "\u283A",
          "\u283B",
          "\u283C",
          "\u283D",
          "\u283E",
          "\u283F",
          "\u2878",
          "\u2879",
          "\u287A",
          "\u287B",
          "\u287C",
          "\u287D",
          "\u287E",
          "\u287F",
          "\u2880",
          "\u2881",
          "\u2882",
          "\u2883",
          "\u2884",
          "\u2885",
          "\u2886",
          "\u2887",
          "\u28C0",
          "\u28C1",
          "\u28C2",
          "\u28C3",
          "\u28C4",
          "\u28C5",
          "\u28C6",
          "\u28C7",
          "\u2888",
          "\u2889",
          "\u288A",
          "\u288B",
          "\u288C",
          "\u288D",
          "\u288E",
          "\u288F",
          "\u28C8",
          "\u28C9",
          "\u28CA",
          "\u28CB",
          "\u28CC",
          "\u28CD",
          "\u28CE",
          "\u28CF",
          "\u2890",
          "\u2891",
          "\u2892",
          "\u2893",
          "\u2894",
          "\u2895",
          "\u2896",
          "\u2897",
          "\u28D0",
          "\u28D1",
          "\u28D2",
          "\u28D3",
          "\u28D4",
          "\u28D5",
          "\u28D6",
          "\u28D7",
          "\u2898",
          "\u2899",
          "\u289A",
          "\u289B",
          "\u289C",
          "\u289D",
          "\u289E",
          "\u289F",
          "\u28D8",
          "\u28D9",
          "\u28DA",
          "\u28DB",
          "\u28DC",
          "\u28DD",
          "\u28DE",
          "\u28DF",
          "\u28A0",
          "\u28A1",
          "\u28A2",
          "\u28A3",
          "\u28A4",
          "\u28A5",
          "\u28A6",
          "\u28A7",
          "\u28E0",
          "\u28E1",
          "\u28E2",
          "\u28E3",
          "\u28E4",
          "\u28E5",
          "\u28E6",
          "\u28E7",
          "\u28A8",
          "\u28A9",
          "\u28AA",
          "\u28AB",
          "\u28AC",
          "\u28AD",
          "\u28AE",
          "\u28AF",
          "\u28E8",
          "\u28E9",
          "\u28EA",
          "\u28EB",
          "\u28EC",
          "\u28ED",
          "\u28EE",
          "\u28EF",
          "\u28B0",
          "\u28B1",
          "\u28B2",
          "\u28B3",
          "\u28B4",
          "\u28B5",
          "\u28B6",
          "\u28B7",
          "\u28F0",
          "\u28F1",
          "\u28F2",
          "\u28F3",
          "\u28F4",
          "\u28F5",
          "\u28F6",
          "\u28F7",
          "\u28B8",
          "\u28B9",
          "\u28BA",
          "\u28BB",
          "\u28BC",
          "\u28BD",
          "\u28BE",
          "\u28BF",
          "\u28F8",
          "\u28F9",
          "\u28FA",
          "\u28FB",
          "\u28FC",
          "\u28FD",
          "\u28FE",
          "\u28FF"
        ]
      },
      sand: {
        interval: 80,
        frames: [
          "\u2801",
          "\u2802",
          "\u2804",
          "\u2840",
          "\u2848",
          "\u2850",
          "\u2860",
          "\u28C0",
          "\u28C1",
          "\u28C2",
          "\u28C4",
          "\u28CC",
          "\u28D4",
          "\u28E4",
          "\u28E5",
          "\u28E6",
          "\u28EE",
          "\u28F6",
          "\u28F7",
          "\u28FF",
          "\u287F",
          "\u283F",
          "\u289F",
          "\u281F",
          "\u285B",
          "\u281B",
          "\u282B",
          "\u288B",
          "\u280B",
          "\u280D",
          "\u2849",
          "\u2809",
          "\u2811",
          "\u2821",
          "\u2881"
        ]
      },
      line: {
        interval: 130,
        frames: [
          "-",
          "\\",
          "|",
          "/"
        ]
      },
      line2: {
        interval: 100,
        frames: [
          "\u2802",
          "-",
          "\u2013",
          "\u2014",
          "\u2013",
          "-"
        ]
      },
      pipe: {
        interval: 100,
        frames: [
          "\u2524",
          "\u2518",
          "\u2534",
          "\u2514",
          "\u251C",
          "\u250C",
          "\u252C",
          "\u2510"
        ]
      },
      simpleDots: {
        interval: 400,
        frames: [
          ".  ",
          ".. ",
          "...",
          "   "
        ]
      },
      simpleDotsScrolling: {
        interval: 200,
        frames: [
          ".  ",
          ".. ",
          "...",
          " ..",
          "  .",
          "   "
        ]
      },
      star: {
        interval: 70,
        frames: [
          "\u2736",
          "\u2738",
          "\u2739",
          "\u273A",
          "\u2739",
          "\u2737"
        ]
      },
      star2: {
        interval: 80,
        frames: [
          "+",
          "x",
          "*"
        ]
      },
      flip: {
        interval: 70,
        frames: [
          "_",
          "_",
          "_",
          "-",
          "`",
          "`",
          "'",
          "\xB4",
          "-",
          "_",
          "_",
          "_"
        ]
      },
      hamburger: {
        interval: 100,
        frames: [
          "\u2631",
          "\u2632",
          "\u2634"
        ]
      },
      growVertical: {
        interval: 120,
        frames: [
          "\u2581",
          "\u2583",
          "\u2584",
          "\u2585",
          "\u2586",
          "\u2587",
          "\u2586",
          "\u2585",
          "\u2584",
          "\u2583"
        ]
      },
      growHorizontal: {
        interval: 120,
        frames: [
          "\u258F",
          "\u258E",
          "\u258D",
          "\u258C",
          "\u258B",
          "\u258A",
          "\u2589",
          "\u258A",
          "\u258B",
          "\u258C",
          "\u258D",
          "\u258E"
        ]
      },
      balloon: {
        interval: 140,
        frames: [
          " ",
          ".",
          "o",
          "O",
          "@",
          "*",
          " "
        ]
      },
      balloon2: {
        interval: 120,
        frames: [
          ".",
          "o",
          "O",
          "\xB0",
          "O",
          "o",
          "."
        ]
      },
      noise: {
        interval: 100,
        frames: [
          "\u2593",
          "\u2592",
          "\u2591"
        ]
      },
      bounce: {
        interval: 120,
        frames: [
          "\u2801",
          "\u2802",
          "\u2804",
          "\u2802"
        ]
      },
      boxBounce: {
        interval: 120,
        frames: [
          "\u2596",
          "\u2598",
          "\u259D",
          "\u2597"
        ]
      },
      boxBounce2: {
        interval: 100,
        frames: [
          "\u258C",
          "\u2580",
          "\u2590",
          "\u2584"
        ]
      },
      triangle: {
        interval: 50,
        frames: [
          "\u25E2",
          "\u25E3",
          "\u25E4",
          "\u25E5"
        ]
      },
      binary: {
        interval: 80,
        frames: [
          "010010",
          "001100",
          "100101",
          "111010",
          "111101",
          "010111",
          "101011",
          "111000",
          "110011",
          "110101"
        ]
      },
      arc: {
        interval: 100,
        frames: [
          "\u25DC",
          "\u25E0",
          "\u25DD",
          "\u25DE",
          "\u25E1",
          "\u25DF"
        ]
      },
      circle: {
        interval: 120,
        frames: [
          "\u25E1",
          "\u2299",
          "\u25E0"
        ]
      },
      squareCorners: {
        interval: 180,
        frames: [
          "\u25F0",
          "\u25F3",
          "\u25F2",
          "\u25F1"
        ]
      },
      circleQuarters: {
        interval: 120,
        frames: [
          "\u25F4",
          "\u25F7",
          "\u25F6",
          "\u25F5"
        ]
      },
      circleHalves: {
        interval: 50,
        frames: [
          "\u25D0",
          "\u25D3",
          "\u25D1",
          "\u25D2"
        ]
      },
      squish: {
        interval: 100,
        frames: [
          "\u256B",
          "\u256A"
        ]
      },
      toggle: {
        interval: 250,
        frames: [
          "\u22B6",
          "\u22B7"
        ]
      },
      toggle2: {
        interval: 80,
        frames: [
          "\u25AB",
          "\u25AA"
        ]
      },
      toggle3: {
        interval: 120,
        frames: [
          "\u25A1",
          "\u25A0"
        ]
      },
      toggle4: {
        interval: 100,
        frames: [
          "\u25A0",
          "\u25A1",
          "\u25AA",
          "\u25AB"
        ]
      },
      toggle5: {
        interval: 100,
        frames: [
          "\u25AE",
          "\u25AF"
        ]
      },
      toggle6: {
        interval: 300,
        frames: [
          "\u101D",
          "\u1040"
        ]
      },
      toggle7: {
        interval: 80,
        frames: [
          "\u29BE",
          "\u29BF"
        ]
      },
      toggle8: {
        interval: 100,
        frames: [
          "\u25CD",
          "\u25CC"
        ]
      },
      toggle9: {
        interval: 100,
        frames: [
          "\u25C9",
          "\u25CE"
        ]
      },
      toggle10: {
        interval: 100,
        frames: [
          "\u3282",
          "\u3280",
          "\u3281"
        ]
      },
      toggle11: {
        interval: 50,
        frames: [
          "\u29C7",
          "\u29C6"
        ]
      },
      toggle12: {
        interval: 120,
        frames: [
          "\u2617",
          "\u2616"
        ]
      },
      toggle13: {
        interval: 80,
        frames: [
          "=",
          "*",
          "-"
        ]
      },
      arrow: {
        interval: 100,
        frames: [
          "\u2190",
          "\u2196",
          "\u2191",
          "\u2197",
          "\u2192",
          "\u2198",
          "\u2193",
          "\u2199"
        ]
      },
      arrow2: {
        interval: 80,
        frames: [
          "\u2B06\uFE0F ",
          "\u2197\uFE0F ",
          "\u27A1\uFE0F ",
          "\u2198\uFE0F ",
          "\u2B07\uFE0F ",
          "\u2199\uFE0F ",
          "\u2B05\uFE0F ",
          "\u2196\uFE0F "
        ]
      },
      arrow3: {
        interval: 120,
        frames: [
          "\u25B9\u25B9\u25B9\u25B9\u25B9",
          "\u25B8\u25B9\u25B9\u25B9\u25B9",
          "\u25B9\u25B8\u25B9\u25B9\u25B9",
          "\u25B9\u25B9\u25B8\u25B9\u25B9",
          "\u25B9\u25B9\u25B9\u25B8\u25B9",
          "\u25B9\u25B9\u25B9\u25B9\u25B8"
        ]
      },
      bouncingBar: {
        interval: 80,
        frames: [
          "[    ]",
          "[=   ]",
          "[==  ]",
          "[=== ]",
          "[====]",
          "[ ===]",
          "[  ==]",
          "[   =]",
          "[    ]",
          "[   =]",
          "[  ==]",
          "[ ===]",
          "[====]",
          "[=== ]",
          "[==  ]",
          "[=   ]"
        ]
      },
      bouncingBall: {
        interval: 80,
        frames: [
          "( \u25CF    )",
          "(  \u25CF   )",
          "(   \u25CF  )",
          "(    \u25CF )",
          "(     \u25CF)",
          "(    \u25CF )",
          "(   \u25CF  )",
          "(  \u25CF   )",
          "( \u25CF    )",
          "(\u25CF     )"
        ]
      },
      smiley: {
        interval: 200,
        frames: [
          "\u{1F604} ",
          "\u{1F61D} "
        ]
      },
      monkey: {
        interval: 300,
        frames: [
          "\u{1F648} ",
          "\u{1F648} ",
          "\u{1F649} ",
          "\u{1F64A} "
        ]
      },
      hearts: {
        interval: 100,
        frames: [
          "\u{1F49B} ",
          "\u{1F499} ",
          "\u{1F49C} ",
          "\u{1F49A} ",
          "\u2764\uFE0F "
        ]
      },
      clock: {
        interval: 100,
        frames: [
          "\u{1F55B} ",
          "\u{1F550} ",
          "\u{1F551} ",
          "\u{1F552} ",
          "\u{1F553} ",
          "\u{1F554} ",
          "\u{1F555} ",
          "\u{1F556} ",
          "\u{1F557} ",
          "\u{1F558} ",
          "\u{1F559} ",
          "\u{1F55A} "
        ]
      },
      earth: {
        interval: 180,
        frames: [
          "\u{1F30D} ",
          "\u{1F30E} ",
          "\u{1F30F} "
        ]
      },
      material: {
        interval: 17,
        frames: [
          "\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
          "\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
          "\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
          "\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
          "\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
          "\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
          "\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
          "\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
          "\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
          "\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
          "\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
          "\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
          "\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
          "\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581",
          "\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581",
          "\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581",
          "\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581",
          "\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581",
          "\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581",
          "\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581",
          "\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581",
          "\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581",
          "\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581",
          "\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581",
          "\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581",
          "\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588",
          "\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588",
          "\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588",
          "\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588",
          "\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588",
          "\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588",
          "\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588",
          "\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588",
          "\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588",
          "\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
          "\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
          "\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
          "\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
          "\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
          "\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
          "\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
          "\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
          "\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581",
          "\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581",
          "\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581",
          "\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581",
          "\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581",
          "\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581",
          "\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
          "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581"
        ]
      },
      moon: {
        interval: 80,
        frames: [
          "\u{1F311} ",
          "\u{1F312} ",
          "\u{1F313} ",
          "\u{1F314} ",
          "\u{1F315} ",
          "\u{1F316} ",
          "\u{1F317} ",
          "\u{1F318} "
        ]
      },
      runner: {
        interval: 140,
        frames: [
          "\u{1F6B6} ",
          "\u{1F3C3} "
        ]
      },
      pong: {
        interval: 80,
        frames: [
          "\u2590\u2802       \u258C",
          "\u2590\u2808       \u258C",
          "\u2590 \u2802      \u258C",
          "\u2590 \u2820      \u258C",
          "\u2590  \u2840     \u258C",
          "\u2590  \u2820     \u258C",
          "\u2590   \u2802    \u258C",
          "\u2590   \u2808    \u258C",
          "\u2590    \u2802   \u258C",
          "\u2590    \u2820   \u258C",
          "\u2590     \u2840  \u258C",
          "\u2590     \u2820  \u258C",
          "\u2590      \u2802 \u258C",
          "\u2590      \u2808 \u258C",
          "\u2590       \u2802\u258C",
          "\u2590       \u2820\u258C",
          "\u2590       \u2840\u258C",
          "\u2590      \u2820 \u258C",
          "\u2590      \u2802 \u258C",
          "\u2590     \u2808  \u258C",
          "\u2590     \u2802  \u258C",
          "\u2590    \u2820   \u258C",
          "\u2590    \u2840   \u258C",
          "\u2590   \u2820    \u258C",
          "\u2590   \u2802    \u258C",
          "\u2590  \u2808     \u258C",
          "\u2590  \u2802     \u258C",
          "\u2590 \u2820      \u258C",
          "\u2590 \u2840      \u258C",
          "\u2590\u2820       \u258C"
        ]
      },
      shark: {
        interval: 120,
        frames: [
          "\u2590|\\____________\u258C",
          "\u2590_|\\___________\u258C",
          "\u2590__|\\__________\u258C",
          "\u2590___|\\_________\u258C",
          "\u2590____|\\________\u258C",
          "\u2590_____|\\_______\u258C",
          "\u2590______|\\______\u258C",
          "\u2590_______|\\_____\u258C",
          "\u2590________|\\____\u258C",
          "\u2590_________|\\___\u258C",
          "\u2590__________|\\__\u258C",
          "\u2590___________|\\_\u258C",
          "\u2590____________|\\\u258C",
          "\u2590____________/|\u258C",
          "\u2590___________/|_\u258C",
          "\u2590__________/|__\u258C",
          "\u2590_________/|___\u258C",
          "\u2590________/|____\u258C",
          "\u2590_______/|_____\u258C",
          "\u2590______/|______\u258C",
          "\u2590_____/|_______\u258C",
          "\u2590____/|________\u258C",
          "\u2590___/|_________\u258C",
          "\u2590__/|__________\u258C",
          "\u2590_/|___________\u258C",
          "\u2590/|____________\u258C"
        ]
      },
      dqpb: {
        interval: 100,
        frames: [
          "d",
          "q",
          "p",
          "b"
        ]
      },
      weather: {
        interval: 100,
        frames: [
          "\u2600\uFE0F ",
          "\u2600\uFE0F ",
          "\u2600\uFE0F ",
          "\u{1F324} ",
          "\u26C5\uFE0F ",
          "\u{1F325} ",
          "\u2601\uFE0F ",
          "\u{1F327} ",
          "\u{1F328} ",
          "\u{1F327} ",
          "\u{1F328} ",
          "\u{1F327} ",
          "\u{1F328} ",
          "\u26C8 ",
          "\u{1F328} ",
          "\u{1F327} ",
          "\u{1F328} ",
          "\u2601\uFE0F ",
          "\u{1F325} ",
          "\u26C5\uFE0F ",
          "\u{1F324} ",
          "\u2600\uFE0F ",
          "\u2600\uFE0F "
        ]
      },
      christmas: {
        interval: 400,
        frames: [
          "\u{1F332}",
          "\u{1F384}"
        ]
      },
      grenade: {
        interval: 80,
        frames: [
          "\u060C  ",
          "\u2032  ",
          " \xB4 ",
          " \u203E ",
          "  \u2E0C",
          "  \u2E0A",
          "  |",
          "  \u204E",
          "  \u2055",
          " \u0DF4 ",
          "  \u2053",
          "   ",
          "   ",
          "   "
        ]
      },
      point: {
        interval: 125,
        frames: [
          "\u2219\u2219\u2219",
          "\u25CF\u2219\u2219",
          "\u2219\u25CF\u2219",
          "\u2219\u2219\u25CF",
          "\u2219\u2219\u2219"
        ]
      },
      layer: {
        interval: 150,
        frames: [
          "-",
          "=",
          "\u2261"
        ]
      },
      betaWave: {
        interval: 80,
        frames: [
          "\u03C1\u03B2\u03B2\u03B2\u03B2\u03B2\u03B2",
          "\u03B2\u03C1\u03B2\u03B2\u03B2\u03B2\u03B2",
          "\u03B2\u03B2\u03C1\u03B2\u03B2\u03B2\u03B2",
          "\u03B2\u03B2\u03B2\u03C1\u03B2\u03B2\u03B2",
          "\u03B2\u03B2\u03B2\u03B2\u03C1\u03B2\u03B2",
          "\u03B2\u03B2\u03B2\u03B2\u03B2\u03C1\u03B2",
          "\u03B2\u03B2\u03B2\u03B2\u03B2\u03B2\u03C1"
        ]
      },
      fingerDance: {
        interval: 160,
        frames: [
          "\u{1F918} ",
          "\u{1F91F} ",
          "\u{1F596} ",
          "\u270B ",
          "\u{1F91A} ",
          "\u{1F446} "
        ]
      },
      fistBump: {
        interval: 80,
        frames: [
          "\u{1F91C}\u3000\u3000\u3000\u3000\u{1F91B} ",
          "\u{1F91C}\u3000\u3000\u3000\u3000\u{1F91B} ",
          "\u{1F91C}\u3000\u3000\u3000\u3000\u{1F91B} ",
          "\u3000\u{1F91C}\u3000\u3000\u{1F91B}\u3000 ",
          "\u3000\u3000\u{1F91C}\u{1F91B}\u3000\u3000 ",
          "\u3000\u{1F91C}\u2728\u{1F91B}\u3000\u3000 ",
          "\u{1F91C}\u3000\u2728\u3000\u{1F91B}\u3000 "
        ]
      },
      soccerHeader: {
        interval: 80,
        frames: [
          " \u{1F9D1}\u26BD\uFE0F       \u{1F9D1} ",
          "\u{1F9D1}  \u26BD\uFE0F      \u{1F9D1} ",
          "\u{1F9D1}   \u26BD\uFE0F     \u{1F9D1} ",
          "\u{1F9D1}    \u26BD\uFE0F    \u{1F9D1} ",
          "\u{1F9D1}     \u26BD\uFE0F   \u{1F9D1} ",
          "\u{1F9D1}      \u26BD\uFE0F  \u{1F9D1} ",
          "\u{1F9D1}       \u26BD\uFE0F\u{1F9D1}  ",
          "\u{1F9D1}      \u26BD\uFE0F  \u{1F9D1} ",
          "\u{1F9D1}     \u26BD\uFE0F   \u{1F9D1} ",
          "\u{1F9D1}    \u26BD\uFE0F    \u{1F9D1} ",
          "\u{1F9D1}   \u26BD\uFE0F     \u{1F9D1} ",
          "\u{1F9D1}  \u26BD\uFE0F      \u{1F9D1} "
        ]
      },
      mindblown: {
        interval: 160,
        frames: [
          "\u{1F610} ",
          "\u{1F610} ",
          "\u{1F62E} ",
          "\u{1F62E} ",
          "\u{1F626} ",
          "\u{1F626} ",
          "\u{1F627} ",
          "\u{1F627} ",
          "\u{1F92F} ",
          "\u{1F4A5} ",
          "\u2728 ",
          "\u3000 ",
          "\u3000 ",
          "\u3000 "
        ]
      },
      speaker: {
        interval: 160,
        frames: [
          "\u{1F508} ",
          "\u{1F509} ",
          "\u{1F50A} ",
          "\u{1F509} "
        ]
      },
      orangePulse: {
        interval: 100,
        frames: [
          "\u{1F538} ",
          "\u{1F536} ",
          "\u{1F7E0} ",
          "\u{1F7E0} ",
          "\u{1F536} "
        ]
      },
      bluePulse: {
        interval: 100,
        frames: [
          "\u{1F539} ",
          "\u{1F537} ",
          "\u{1F535} ",
          "\u{1F535} ",
          "\u{1F537} "
        ]
      },
      orangeBluePulse: {
        interval: 100,
        frames: [
          "\u{1F538} ",
          "\u{1F536} ",
          "\u{1F7E0} ",
          "\u{1F7E0} ",
          "\u{1F536} ",
          "\u{1F539} ",
          "\u{1F537} ",
          "\u{1F535} ",
          "\u{1F535} ",
          "\u{1F537} "
        ]
      },
      timeTravel: {
        interval: 100,
        frames: [
          "\u{1F55B} ",
          "\u{1F55A} ",
          "\u{1F559} ",
          "\u{1F558} ",
          "\u{1F557} ",
          "\u{1F556} ",
          "\u{1F555} ",
          "\u{1F554} ",
          "\u{1F553} ",
          "\u{1F552} ",
          "\u{1F551} ",
          "\u{1F550} "
        ]
      },
      aesthetic: {
        interval: 80,
        frames: [
          "\u25B0\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1",
          "\u25B0\u25B0\u25B1\u25B1\u25B1\u25B1\u25B1",
          "\u25B0\u25B0\u25B0\u25B1\u25B1\u25B1\u25B1",
          "\u25B0\u25B0\u25B0\u25B0\u25B1\u25B1\u25B1",
          "\u25B0\u25B0\u25B0\u25B0\u25B0\u25B1\u25B1",
          "\u25B0\u25B0\u25B0\u25B0\u25B0\u25B0\u25B1",
          "\u25B0\u25B0\u25B0\u25B0\u25B0\u25B0\u25B0",
          "\u25B0\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1"
        ]
      },
      dwarfFortress: {
        interval: 80,
        frames: [
          " \u2588\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3  ",
          "\u263A\u2588\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3  ",
          "\u263A\u2588\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3  ",
          "\u263A\u2593\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3  ",
          "\u263A\u2593\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3  ",
          "\u263A\u2592\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3  ",
          "\u263A\u2592\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3  ",
          "\u263A\u2591\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3  ",
          "\u263A\u2591\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3  ",
          "\u263A \u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3  ",
          " \u263A\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3  ",
          " \u263A\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3  ",
          " \u263A\u2593\u2588\u2588\u2588\u2588\xA3\xA3\xA3  ",
          " \u263A\u2593\u2588\u2588\u2588\u2588\xA3\xA3\xA3  ",
          " \u263A\u2592\u2588\u2588\u2588\u2588\xA3\xA3\xA3  ",
          " \u263A\u2592\u2588\u2588\u2588\u2588\xA3\xA3\xA3  ",
          " \u263A\u2591\u2588\u2588\u2588\u2588\xA3\xA3\xA3  ",
          " \u263A\u2591\u2588\u2588\u2588\u2588\xA3\xA3\xA3  ",
          " \u263A \u2588\u2588\u2588\u2588\xA3\xA3\xA3  ",
          "  \u263A\u2588\u2588\u2588\u2588\xA3\xA3\xA3  ",
          "  \u263A\u2588\u2588\u2588\u2588\xA3\xA3\xA3  ",
          "  \u263A\u2593\u2588\u2588\u2588\xA3\xA3\xA3  ",
          "  \u263A\u2593\u2588\u2588\u2588\xA3\xA3\xA3  ",
          "  \u263A\u2592\u2588\u2588\u2588\xA3\xA3\xA3  ",
          "  \u263A\u2592\u2588\u2588\u2588\xA3\xA3\xA3  ",
          "  \u263A\u2591\u2588\u2588\u2588\xA3\xA3\xA3  ",
          "  \u263A\u2591\u2588\u2588\u2588\xA3\xA3\xA3  ",
          "  \u263A \u2588\u2588\u2588\xA3\xA3\xA3  ",
          "   \u263A\u2588\u2588\u2588\xA3\xA3\xA3  ",
          "   \u263A\u2588\u2588\u2588\xA3\xA3\xA3  ",
          "   \u263A\u2593\u2588\u2588\xA3\xA3\xA3  ",
          "   \u263A\u2593\u2588\u2588\xA3\xA3\xA3  ",
          "   \u263A\u2592\u2588\u2588\xA3\xA3\xA3  ",
          "   \u263A\u2592\u2588\u2588\xA3\xA3\xA3  ",
          "   \u263A\u2591\u2588\u2588\xA3\xA3\xA3  ",
          "   \u263A\u2591\u2588\u2588\xA3\xA3\xA3  ",
          "   \u263A \u2588\u2588\xA3\xA3\xA3  ",
          "    \u263A\u2588\u2588\xA3\xA3\xA3  ",
          "    \u263A\u2588\u2588\xA3\xA3\xA3  ",
          "    \u263A\u2593\u2588\xA3\xA3\xA3  ",
          "    \u263A\u2593\u2588\xA3\xA3\xA3  ",
          "    \u263A\u2592\u2588\xA3\xA3\xA3  ",
          "    \u263A\u2592\u2588\xA3\xA3\xA3  ",
          "    \u263A\u2591\u2588\xA3\xA3\xA3  ",
          "    \u263A\u2591\u2588\xA3\xA3\xA3  ",
          "    \u263A \u2588\xA3\xA3\xA3  ",
          "     \u263A\u2588\xA3\xA3\xA3  ",
          "     \u263A\u2588\xA3\xA3\xA3  ",
          "     \u263A\u2593\xA3\xA3\xA3  ",
          "     \u263A\u2593\xA3\xA3\xA3  ",
          "     \u263A\u2592\xA3\xA3\xA3  ",
          "     \u263A\u2592\xA3\xA3\xA3  ",
          "     \u263A\u2591\xA3\xA3\xA3  ",
          "     \u263A\u2591\xA3\xA3\xA3  ",
          "     \u263A \xA3\xA3\xA3  ",
          "      \u263A\xA3\xA3\xA3  ",
          "      \u263A\xA3\xA3\xA3  ",
          "      \u263A\u2593\xA3\xA3  ",
          "      \u263A\u2593\xA3\xA3  ",
          "      \u263A\u2592\xA3\xA3  ",
          "      \u263A\u2592\xA3\xA3  ",
          "      \u263A\u2591\xA3\xA3  ",
          "      \u263A\u2591\xA3\xA3  ",
          "      \u263A \xA3\xA3  ",
          "       \u263A\xA3\xA3  ",
          "       \u263A\xA3\xA3  ",
          "       \u263A\u2593\xA3  ",
          "       \u263A\u2593\xA3  ",
          "       \u263A\u2592\xA3  ",
          "       \u263A\u2592\xA3  ",
          "       \u263A\u2591\xA3  ",
          "       \u263A\u2591\xA3  ",
          "       \u263A \xA3  ",
          "        \u263A\xA3  ",
          "        \u263A\xA3  ",
          "        \u263A\u2593  ",
          "        \u263A\u2593  ",
          "        \u263A\u2592  ",
          "        \u263A\u2592  ",
          "        \u263A\u2591  ",
          "        \u263A\u2591  ",
          "        \u263A   ",
          "        \u263A  &",
          "        \u263A \u263C&",
          "       \u263A \u263C &",
          "       \u263A\u263C  &",
          "      \u263A\u263C  & ",
          "      \u203C   & ",
          "     \u263A   &  ",
          "    \u203C    &  ",
          "   \u263A    &   ",
          "  \u203C     &   ",
          " \u263A     &    ",
          "\u203C      &    ",
          "      &     ",
          "      &     ",
          "     &   \u2591  ",
          "     &   \u2592  ",
          "    &    \u2593  ",
          "    &    \xA3  ",
          "   &    \u2591\xA3  ",
          "   &    \u2592\xA3  ",
          "  &     \u2593\xA3  ",
          "  &     \xA3\xA3  ",
          " &     \u2591\xA3\xA3  ",
          " &     \u2592\xA3\xA3  ",
          "&      \u2593\xA3\xA3  ",
          "&      \xA3\xA3\xA3  ",
          "      \u2591\xA3\xA3\xA3  ",
          "      \u2592\xA3\xA3\xA3  ",
          "      \u2593\xA3\xA3\xA3  ",
          "      \u2588\xA3\xA3\xA3  ",
          "     \u2591\u2588\xA3\xA3\xA3  ",
          "     \u2592\u2588\xA3\xA3\xA3  ",
          "     \u2593\u2588\xA3\xA3\xA3  ",
          "     \u2588\u2588\xA3\xA3\xA3  ",
          "    \u2591\u2588\u2588\xA3\xA3\xA3  ",
          "    \u2592\u2588\u2588\xA3\xA3\xA3  ",
          "    \u2593\u2588\u2588\xA3\xA3\xA3  ",
          "    \u2588\u2588\u2588\xA3\xA3\xA3  ",
          "   \u2591\u2588\u2588\u2588\xA3\xA3\xA3  ",
          "   \u2592\u2588\u2588\u2588\xA3\xA3\xA3  ",
          "   \u2593\u2588\u2588\u2588\xA3\xA3\xA3  ",
          "   \u2588\u2588\u2588\u2588\xA3\xA3\xA3  ",
          "  \u2591\u2588\u2588\u2588\u2588\xA3\xA3\xA3  ",
          "  \u2592\u2588\u2588\u2588\u2588\xA3\xA3\xA3  ",
          "  \u2593\u2588\u2588\u2588\u2588\xA3\xA3\xA3  ",
          "  \u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3  ",
          " \u2591\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3  ",
          " \u2592\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3  ",
          " \u2593\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3  ",
          " \u2588\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3  ",
          " \u2588\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3  "
        ]
      }
    };
  }
});

// node_modules/cli-spinners/index.js
var require_cli_spinners = __commonJS({
  "node_modules/cli-spinners/index.js"(exports, module) {
    "use strict";
    init_esbuild_shims();
    var spinners2 = Object.assign({}, require_spinners());
    var spinnersList = Object.keys(spinners2);
    Object.defineProperty(spinners2, "random", {
      get() {
        const randomIndex = Math.floor(Math.random() * spinnersList.length);
        const spinnerName = spinnersList[randomIndex];
        return spinners2[spinnerName];
      }
    });
    module.exports = spinners2;
  }
});

// node_modules/prop-types/lib/ReactPropTypesSecret.js
var require_ReactPropTypesSecret = __commonJS({
  "node_modules/prop-types/lib/ReactPropTypesSecret.js"(exports, module) {
    "use strict";
    init_esbuild_shims();
    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";
    init_esbuild_shims();
    var ReactPropTypesSecret = require_ReactPropTypesSecret();
    function emptyFunction() {
    }
    __name(emptyFunction, "emptyFunction");
    function emptyFunctionWithReset() {
    }
    __name(emptyFunctionWithReset, "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;
      }
      __name(shim, "shim");
      ;
      shim.isRequired = shim;
      function getShim() {
        return shim;
      }
      __name(getShim, "getShim");
      ;
      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) {
    init_esbuild_shims();
    if (false) {
      ReactIs = null;
      throwOnDirectAccess = true;
      module.exports = null(ReactIs.isElement, throwOnDirectAccess);
    } else {
      module.exports = require_factoryWithThrowingShims()();
    }
    var ReactIs;
    var throwOnDirectAccess;
  }
});

// node_modules/ink-link/node_modules/supports-color/index.js
var require_supports_color = __commonJS({
  "node_modules/ink-link/node_modules/supports-color/index.js"(exports, module) {
    "use strict";
    init_esbuild_shims();
    var os3 = __require("os");
    var tty = __require("tty");
    var hasFlag = require_has_flag();
    var { env } = process;
    var forceColor;
    if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) {
      forceColor = 0;
    } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) {
      forceColor = 1;
    }
    if ("FORCE_COLOR" in env) {
      if (env.FORCE_COLOR === "true") {
        forceColor = 1;
      } else if (env.FORCE_COLOR === "false") {
        forceColor = 0;
      } else {
        forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3);
      }
    }
    function translateLevel(level) {
      if (level === 0) {
        return false;
      }
      return {
        level,
        hasBasic: true,
        has256: level >= 2,
        has16m: level >= 3
      };
    }
    __name(translateLevel, "translateLevel");
    function supportsColor(haveStream, streamIsTTY) {
      if (forceColor === 0) {
        return 0;
      }
      if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) {
        return 3;
      }
      if (hasFlag("color=256")) {
        return 2;
      }
      if (haveStream && !streamIsTTY && forceColor === void 0) {
        return 0;
      }
      const min = forceColor || 0;
      if (env.TERM === "dumb") {
        return min;
      }
      if (process.platform === "win32") {
        const osRelease = os3.release().split(".");
        if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
          return Number(osRelease[2]) >= 14931 ? 3 : 2;
        }
        return 1;
      }
      if ("CI" in env) {
        if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "GITHUB_ACTIONS", "BUILDKITE"].some((sign) => sign in env) || env.CI_NAME === "codeship") {
          return 1;
        }
        return min;
      }
      if ("TEAMCITY_VERSION" in env) {
        return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
      }
      if (env.COLORTERM === "truecolor") {
        return 3;
      }
      if ("TERM_PROGRAM" in env) {
        const version = parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
        switch (env.TERM_PROGRAM) {
          case "iTerm.app":
            return version >= 3 ? 3 : 2;
          case "Apple_Terminal":
            return 2;
        }
      }
      if (/-256(color)?$/i.test(env.TERM)) {
        return 2;
      }
      if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
        return 1;
      }
      if ("COLORTERM" in env) {
        return 1;
      }
      return min;
    }
    __name(supportsColor, "supportsColor");
    function getSupportLevel(stream) {
      const level = supportsColor(stream, stream && stream.isTTY);
      return translateLevel(level);
    }
    __name(getSupportLevel, "getSupportLevel");
    module.exports = {
      supportsColor: getSupportLevel,
      stdout: translateLevel(supportsColor(true, tty.isatty(1))),
      stderr: translateLevel(supportsColor(true, tty.isatty(2)))
    };
  }
});

// node_modules/ink-link/node_modules/supports-hyperlinks/index.js
var require_supports_hyperlinks = __commonJS({
  "node_modules/ink-link/node_modules/supports-hyperlinks/index.js"(exports, module) {
    "use strict";
    init_esbuild_shims();
    var supportsColor = require_supports_color();
    var hasFlag = require_has_flag();
    function parseVersion2(versionString) {
      if (/^\d{3,4}$/.test(versionString)) {
        const m = /(\d{1,2})(\d{2})/.exec(versionString);
        return {
          major: 0,
          minor: parseInt(m[1], 10),
          patch: parseInt(m[2], 10)
        };
      }
      const versions = (versionString || "").split(".").map((n) => parseInt(n, 10));
      return {
        major: versions[0],
        minor: versions[1],
        patch: versions[2]
      };
    }
    __name(parseVersion2, "parseVersion");
    function supportsHyperlink(stream) {
      const { env } = process;
      if ("FORCE_HYPERLINK" in env) {
        return !(env.FORCE_HYPERLINK.length > 0 && parseInt(env.FORCE_HYPERLINK, 10) === 0);
      }
      if (hasFlag("no-hyperlink") || hasFlag("no-hyperlinks") || hasFlag("hyperlink=false") || hasFlag("hyperlink=never")) {
        return false;
      }
      if (hasFlag("hyperlink=true") || hasFlag("hyperlink=always")) {
        return true;
      }
      if ("NETLIFY" in env) {
        return true;
      }
      if (!supportsColor.supportsColor(stream)) {
        return false;
      }
      if (stream && !stream.isTTY) {
        return false;
      }
      if (process.platform === "win32") {
        return false;
      }
      if ("CI" in env) {
        return false;
      }
      if ("TEAMCITY_VERSION" in env) {
        return false;
      }
      if ("TERM_PROGRAM" in env) {
        const version = parseVersion2(env.TERM_PROGRAM_VERSION);
        switch (env.TERM_PROGRAM) {
          case "iTerm.app":
            if (version.major === 3) {
              return version.minor >= 1;
            }
            return version.major > 3;
          case "WezTerm":
            return version.major >= 20200620;
          case "vscode":
            return version.major > 1 || version.major === 1 && version.minor >= 72;
        }
      }
      if ("VTE_VERSION" in env) {
        if (env.VTE_VERSION === "0.50.0") {
          return false;
        }
        const version = parseVersion2(env.VTE_VERSION);
        return version.major > 0 || version.minor >= 50;
      }
      return false;
    }
    __name(supportsHyperlink, "supportsHyperlink");
    module.exports = {
      supportsHyperlink,
      stdout: supportsHyperlink(process.stdout),
      stderr: supportsHyperlink(process.stderr)
    };
  }
});

// node_modules/tinycolor2/cjs/tinycolor.js
var require_tinycolor = __commonJS({
  "node_modules/tinycolor2/cjs/tinycolor.js"(exports, module) {
    init_esbuild_shims();
    (function(global, factory) {
      typeof exports === "object" && typeof module !== "undefined" ? module.exports = factory() : typeof define === "function" && define.amd ? define(factory) : (global = typeof globalThis !== "undefined" ? globalThis : global || self, global.tinycolor = factory());
    })(exports, function() {
      "use strict";
      function _typeof(obj) {
        "@babel/helpers - typeof";
        return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(obj2) {
          return typeof obj2;
        } : function(obj2) {
          return obj2 && "function" == typeof Symbol && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2;
        }, _typeof(obj);
      }
      __name(_typeof, "_typeof");
      var trimLeft = /^\s+/;
      var trimRight = /\s+$/;
      function tinycolor(color, opts) {
        color = color ? color : "";
        opts = opts || {};
        if (color instanceof tinycolor) {
          return color;
        }
        if (!(this instanceof tinycolor)) {
          return new tinycolor(color, opts);
        }
        var rgb = inputToRGB(color);
        this._originalInput = color, this._r = rgb.r, this._g = rgb.g, this._b = rgb.b, this._a = rgb.a, this._roundA = Math.round(100 * this._a) / 100, this._format = opts.format || rgb.format;
        this._gradientType = opts.gradientType;
        if (this._r < 1) this._r = Math.round(this._r);
        if (this._g < 1) this._g = Math.round(this._g);
        if (this._b < 1) this._b = Math.round(this._b);
        this._ok = rgb.ok;
      }
      __name(tinycolor, "tinycolor");
      tinycolor.prototype = {
        isDark: /* @__PURE__ */ __name(function isDark() {
          return this.getBrightness() < 128;
        }, "isDark"),
        isLight: /* @__PURE__ */ __name(function isLight() {
          return !this.isDark();
        }, "isLight"),
        isValid: /* @__PURE__ */ __name(function isValid() {
          return this._ok;
        }, "isValid"),
        getOriginalInput: /* @__PURE__ */ __name(function getOriginalInput() {
          return this._originalInput;
        }, "getOriginalInput"),
        getFormat: /* @__PURE__ */ __name(function getFormat() {
          return this._format;
        }, "getFormat"),
        getAlpha: /* @__PURE__ */ __name(function getAlpha() {
          return this._a;
        }, "getAlpha"),
        getBrightness: /* @__PURE__ */ __name(function getBrightness() {
          var rgb = this.toRgb();
          return (rgb.r * 299 + rgb.g * 587 + rgb.b * 114) / 1e3;
        }, "getBrightness"),
        getLuminance: /* @__PURE__ */ __name(function getLuminance() {
          var rgb = this.toRgb();
          var RsRGB, GsRGB, BsRGB, R, G, B;
          RsRGB = rgb.r / 255;
          GsRGB = rgb.g / 255;
          BsRGB = rgb.b / 255;
          if (RsRGB <= 0.03928) R = RsRGB / 12.92;
          else R = Math.pow((RsRGB + 0.055) / 1.055, 2.4);
          if (GsRGB <= 0.03928) G = GsRGB / 12.92;
          else G = Math.pow((GsRGB + 0.055) / 1.055, 2.4);
          if (BsRGB <= 0.03928) B = BsRGB / 12.92;
          else B = Math.pow((BsRGB + 0.055) / 1.055, 2.4);
          return 0.2126 * R + 0.7152 * G + 0.0722 * B;
        }, "getLuminance"),
        setAlpha: /* @__PURE__ */ __name(function setAlpha(value) {
          this._a = boundAlpha(value);
          this._roundA = Math.round(100 * this._a) / 100;
          return this;
        }, "setAlpha"),
        toHsv: /* @__PURE__ */ __name(function toHsv() {
          var hsv = rgbToHsv(this._r, this._g, this._b);
          return {
            h: hsv.h * 360,
            s: hsv.s,
            v: hsv.v,
            a: this._a
          };
        }, "toHsv"),
        toHsvString: /* @__PURE__ */ __name(function toHsvString() {
          var hsv = rgbToHsv(this._r, this._g, this._b);
          var h = Math.round(hsv.h * 360), s = Math.round(hsv.s * 100), v = Math.round(hsv.v * 100);
          return this._a == 1 ? "hsv(" + h + ", " + s + "%, " + v + "%)" : "hsva(" + h + ", " + s + "%, " + v + "%, " + this._roundA + ")";
        }, "toHsvString"),
        toHsl: /* @__PURE__ */ __name(function toHsl() {
          var hsl = rgbToHsl(this._r, this._g, this._b);
          return {
            h: hsl.h * 360,
            s: hsl.s,
            l: hsl.l,
            a: this._a
          };
        }, "toHsl"),
        toHslString: /* @__PURE__ */ __name(function toHslString() {
          var hsl = rgbToHsl(this._r, this._g, this._b);
          var h = Math.round(hsl.h * 360), s = Math.round(hsl.s * 100), l = Math.round(hsl.l * 100);
          return this._a == 1 ? "hsl(" + h + ", " + s + "%, " + l + "%)" : "hsla(" + h + ", " + s + "%, " + l + "%, " + this._roundA + ")";
        }, "toHslString"),
        toHex: /* @__PURE__ */ __name(function toHex2(allow3Char) {
          return rgbToHex(this._r, this._g, this._b, allow3Char);
        }, "toHex"),
        toHexString: /* @__PURE__ */ __name(function toHexString(allow3Char) {
          return "#" + this.toHex(allow3Char);
        }, "toHexString"),
        toHex8: /* @__PURE__ */ __name(function toHex8(allow4Char) {
          return rgbaToHex(this._r, this._g, this._b, this._a, allow4Char);
        }, "toHex8"),
        toHex8String: /* @__PURE__ */ __name(function toHex8String(allow4Char) {
          return "#" + this.toHex8(allow4Char);
        }, "toHex8String"),
        toRgb: /* @__PURE__ */ __name(function toRgb() {
          return {
            r: Math.round(this._r),
            g: Math.round(this._g),
            b: Math.round(this._b),
            a: this._a
          };
        }, "toRgb"),
        toRgbString: /* @__PURE__ */ __name(function toRgbString() {
          return this._a == 1 ? "rgb(" + Math.round(this._r) + ", " + Math.round(this._g) + ", " + Math.round(this._b) + ")" : "rgba(" + Math.round(this._r) + ", " + Math.round(this._g) + ", " + Math.round(this._b) + ", " + this._roundA + ")";
        }, "toRgbString"),
        toPercentageRgb: /* @__PURE__ */ __name(function toPercentageRgb() {
          return {
            r: Math.round(bound01(this._r, 255) * 100) + "%",
            g: Math.round(bound01(this._g, 255) * 100) + "%",
            b: Math.round(bound01(this._b, 255) * 100) + "%",
            a: this._a
          };
        }, "toPercentageRgb"),
        toPercentageRgbString: /* @__PURE__ */ __name(function toPercentageRgbString() {
          return this._a == 1 ? "rgb(" + Math.round(bound01(this._r, 255) * 100) + "%, " + Math.round(bound01(this._g, 255) * 100) + "%, " + Math.round(bound01(this._b, 255) * 100) + "%)" : "rgba(" + Math.round(bound01(this._r, 255) * 100) + "%, " + Math.round(bound01(this._g, 255) * 100) + "%, " + Math.round(bound01(this._b, 255) * 100) + "%, " + this._roundA + ")";
        }, "toPercentageRgbString"),
        toName: /* @__PURE__ */ __name(function toName() {
          if (this._a === 0) {
            return "transparent";
          }
          if (this._a < 1) {
            return false;
          }
          return hexNames[rgbToHex(this._r, this._g, this._b, true)] || false;
        }, "toName"),
        toFilter: /* @__PURE__ */ __name(function toFilter(secondColor) {
          var hex8String = "#" + rgbaToArgbHex(this._r, this._g, this._b, this._a);
          var secondHex8String = hex8String;
          var gradientType = this._gradientType ? "GradientType = 1, " : "";
          if (secondColor) {
            var s = tinycolor(secondColor);
            secondHex8String = "#" + rgbaToArgbHex(s._r, s._g, s._b, s._a);
          }
          return "progid:DXImageTransform.Microsoft.gradient(" + gradientType + "startColorstr=" + hex8String + ",endColorstr=" + secondHex8String + ")";
        }, "toFilter"),
        toString: /* @__PURE__ */ __name(function toString(format) {
          var formatSet = !!format;
          format = format || this._format;
          var formattedString = false;
          var hasAlpha = this._a < 1 && this._a >= 0;
          var needsAlphaFormat = !formatSet && hasAlpha && (format === "hex" || format === "hex6" || format === "hex3" || format === "hex4" || format === "hex8" || format === "name");
          if (needsAlphaFormat) {
            if (format === "name" && this._a === 0) {
              return this.toName();
            }
            return this.toRgbString();
          }
          if (format === "rgb") {
            formattedString = this.toRgbString();
          }
          if (format === "prgb") {
            formattedString = this.toPercentageRgbString();
          }
          if (format === "hex" || format === "hex6") {
            formattedString = this.toHexString();
          }
          if (format === "hex3") {
            formattedString = this.toHexString(true);
          }
          if (format === "hex4") {
            formattedString = this.toHex8String(true);
          }
          if (format === "hex8") {
            formattedString = this.toHex8String();
          }
          if (format === "name") {
            formattedString = this.toName();
          }
          if (format === "hsl") {
            formattedString = this.toHslString();
          }
          if (format === "hsv") {
            formattedString = this.toHsvString();
          }
          return formattedString || this.toHexString();
        }, "toString"),
        clone: /* @__PURE__ */ __name(function clone() {
          return tinycolor(this.toString());
        }, "clone"),
        _applyModification: /* @__PURE__ */ __name(function _applyModification(fn, args) {
          var color = fn.apply(null, [this].concat([].slice.call(args)));
          this._r = color._r;
          this._g = color._g;
          this._b = color._b;
          this.setAlpha(color._a);
          return this;
        }, "_applyModification"),
        lighten: /* @__PURE__ */ __name(function lighten() {
          return this._applyModification(_lighten, arguments);
        }, "lighten"),
        brighten: /* @__PURE__ */ __name(function brighten() {
          return this._applyModification(_brighten, arguments);
        }, "brighten"),
        darken: /* @__PURE__ */ __name(function darken() {
          return this._applyModification(_darken, arguments);
        }, "darken"),
        desaturate: /* @__PURE__ */ __name(function desaturate() {
          return this._applyModification(_desaturate, arguments);
        }, "desaturate"),
        saturate: /* @__PURE__ */ __name(function saturate() {
          return this._applyModification(_saturate, arguments);
        }, "saturate"),
        greyscale: /* @__PURE__ */ __name(function greyscale() {
          return this._applyModification(_greyscale, arguments);
        }, "greyscale"),
        spin: /* @__PURE__ */ __name(function spin() {
          return this._applyModification(_spin, arguments);
        }, "spin"),
        _applyCombination: /* @__PURE__ */ __name(function _applyCombination(fn, args) {
          return fn.apply(null, [this].concat([].slice.call(args)));
        }, "_applyCombination"),
        analogous: /* @__PURE__ */ __name(function analogous() {
          return this._applyCombination(_analogous, arguments);
        }, "analogous"),
        complement: /* @__PURE__ */ __name(function complement() {
          return this._applyCombination(_complement, arguments);
        }, "complement"),
        monochromatic: /* @__PURE__ */ __name(function monochromatic() {
          return this._applyCombination(_monochromatic, arguments);
        }, "monochromatic"),
        splitcomplement: /* @__PURE__ */ __name(function splitcomplement() {
          return this._applyCombination(_splitcomplement, arguments);
        }, "splitcomplement"),
        // Disabled until https://github.com/bgrins/TinyColor/issues/254
        // polyad: function (number) {
        //   return this._applyCombination(polyad, [number]);
        // },
        triad: /* @__PURE__ */ __name(function triad() {
          return this._applyCombination(polyad, [3]);
        }, "triad"),
        tetrad: /* @__PURE__ */ __name(function tetrad() {
          return this._applyCombination(polyad, [4]);
        }, "tetrad")
      };
      tinycolor.fromRatio = function(color, opts) {
        if (_typeof(color) == "object") {
          var newColor = {};
          for (var i in color) {
            if (color.hasOwnProperty(i)) {
              if (i === "a") {
                newColor[i] = color[i];
              } else {
                newColor[i] = convertToPercentage(color[i]);
              }
            }
          }
          color = newColor;
        }
        return tinycolor(color, opts);
      };
      function inputToRGB(color) {
        var rgb = {
          r: 0,
          g: 0,
          b: 0
        };
        var a = 1;
        var s = null;
        var v = null;
        var l = null;
        var ok = false;
        var format = false;
        if (typeof color == "string") {
          color = stringInputToObject(color);
        }
        if (_typeof(color) == "object") {
          if (isValidCSSUnit(color.r) && isValidCSSUnit(color.g) && isValidCSSUnit(color.b)) {
            rgb = rgbToRgb(color.r, color.g, color.b);
            ok = true;
            format = String(color.r).substr(-1) === "%" ? "prgb" : "rgb";
          } else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.v)) {
            s = convertToPercentage(color.s);
            v = convertToPercentage(color.v);
            rgb = hsvToRgb(color.h, s, v);
            ok = true;
            format = "hsv";
          } else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.l)) {
            s = convertToPercentage(color.s);
            l = convertToPercentage(color.l);
            rgb = hslToRgb(color.h, s, l);
            ok = true;
            format = "hsl";
          }
          if (color.hasOwnProperty("a")) {
            a = color.a;
          }
        }
        a = boundAlpha(a);
        return {
          ok,
          format: color.format || format,
          r: Math.min(255, Math.max(rgb.r, 0)),
          g: Math.min(255, Math.max(rgb.g, 0)),
          b: Math.min(255, Math.max(rgb.b, 0)),
          a
        };
      }
      __name(inputToRGB, "inputToRGB");
      function rgbToRgb(r, g, b) {
        return {
          r: bound01(r, 255) * 255,
          g: bound01(g, 255) * 255,
          b: bound01(b, 255) * 255
        };
      }
      __name(rgbToRgb, "rgbToRgb");
      function rgbToHsl(r, g, b) {
        r = bound01(r, 255);
        g = bound01(g, 255);
        b = bound01(b, 255);
        var max = Math.max(r, g, b), min = Math.min(r, g, b);
        var h, s, l = (max + min) / 2;
        if (max == min) {
          h = s = 0;
        } else {
          var d = max - min;
          s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
          switch (max) {
            case r:
              h = (g - b) / d + (g < b ? 6 : 0);
              break;
            case g:
              h = (b - r) / d + 2;
              break;
            case b:
              h = (r - g) / d + 4;
              break;
          }
          h /= 6;
        }
        return {
          h,
          s,
          l
        };
      }
      __name(rgbToHsl, "rgbToHsl");
      function hslToRgb(h, s, l) {
        var r, g, b;
        h = bound01(h, 360);
        s = bound01(s, 100);
        l = bound01(l, 100);
        function hue2rgb(p2, q2, t2) {
          if (t2 < 0) t2 += 1;
          if (t2 > 1) t2 -= 1;
          if (t2 < 1 / 6) return p2 + (q2 - p2) * 6 * t2;
          if (t2 < 1 / 2) return q2;
          if (t2 < 2 / 3) return p2 + (q2 - p2) * (2 / 3 - t2) * 6;
          return p2;
        }
        __name(hue2rgb, "hue2rgb");
        if (s === 0) {
          r = g = b = l;
        } else {
          var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
          var p = 2 * l - q;
          r = hue2rgb(p, q, h + 1 / 3);
          g = hue2rgb(p, q, h);
          b = hue2rgb(p, q, h - 1 / 3);
        }
        return {
          r: r * 255,
          g: g * 255,
          b: b * 255
        };
      }
      __name(hslToRgb, "hslToRgb");
      function rgbToHsv(r, g, b) {
        r = bound01(r, 255);
        g = bound01(g, 255);
        b = bound01(b, 255);
        var max = Math.max(r, g, b), min = Math.min(r, g, b);
        var h, s, v = max;
        var d = max - min;
        s = max === 0 ? 0 : d / max;
        if (max == min) {
          h = 0;
        } else {
          switch (max) {
            case r:
              h = (g - b) / d + (g < b ? 6 : 0);
              break;
            case g:
              h = (b - r) / d + 2;
              break;
            case b:
              h = (r - g) / d + 4;
              break;
          }
          h /= 6;
        }
        return {
          h,
          s,
          v
        };
      }
      __name(rgbToHsv, "rgbToHsv");
      function hsvToRgb(h, s, v) {
        h = bound01(h, 360) * 6;
        s = bound01(s, 100);
        v = bound01(v, 100);
        var i = Math.floor(h), f = h - i, p = v * (1 - s), q = v * (1 - f * s), t2 = v * (1 - (1 - f) * s), mod = i % 6, r = [v, q, p, p, t2, v][mod], g = [t2, v, v, q, p, p][mod], b = [p, p, t2, v, v, q][mod];
        return {
          r: r * 255,
          g: g * 255,
          b: b * 255
        };
      }
      __name(hsvToRgb, "hsvToRgb");
      function rgbToHex(r, g, b, allow3Char) {
        var hex = [pad2(Math.round(r).toString(16)), pad2(Math.round(g).toString(16)), pad2(Math.round(b).toString(16))];
        if (allow3Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1)) {
          return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0);
        }
        return hex.join("");
      }
      __name(rgbToHex, "rgbToHex");
      function rgbaToHex(r, g, b, a, allow4Char) {
        var hex = [pad2(Math.round(r).toString(16)), pad2(Math.round(g).toString(16)), pad2(Math.round(b).toString(16)), pad2(convertDecimalToHex(a))];
        if (allow4Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1) && hex[3].charAt(0) == hex[3].charAt(1)) {
          return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0) + hex[3].charAt(0);
        }
        return hex.join("");
      }
      __name(rgbaToHex, "rgbaToHex");
      function rgbaToArgbHex(r, g, b, a) {
        var hex = [pad2(convertDecimalToHex(a)), pad2(Math.round(r).toString(16)), pad2(Math.round(g).toString(16)), pad2(Math.round(b).toString(16))];
        return hex.join("");
      }
      __name(rgbaToArgbHex, "rgbaToArgbHex");
      tinycolor.equals = function(color1, color2) {
        if (!color1 || !color2) return false;
        return tinycolor(color1).toRgbString() == tinycolor(color2).toRgbString();
      };
      tinycolor.random = function() {
        return tinycolor.fromRatio({
          r: Math.random(),
          g: Math.random(),
          b: Math.random()
        });
      };
      function _desaturate(color, amount) {
        amount = amount === 0 ? 0 : amount || 10;
        var hsl = tinycolor(color).toHsl();
        hsl.s -= amount / 100;
        hsl.s = clamp01(hsl.s);
        return tinycolor(hsl);
      }
      __name(_desaturate, "_desaturate");
      function _saturate(color, amount) {
        amount = amount === 0 ? 0 : amount || 10;
        var hsl = tinycolor(color).toHsl();
        hsl.s += amount / 100;
        hsl.s = clamp01(hsl.s);
        return tinycolor(hsl);
      }
      __name(_saturate, "_saturate");
      function _greyscale(color) {
        return tinycolor(color).desaturate(100);
      }
      __name(_greyscale, "_greyscale");
      function _lighten(color, amount) {
        amount = amount === 0 ? 0 : amount || 10;
        var hsl = tinycolor(color).toHsl();
        hsl.l += amount / 100;
        hsl.l = clamp01(hsl.l);
        return tinycolor(hsl);
      }
      __name(_lighten, "_lighten");
      function _brighten(color, amount) {
        amount = amount === 0 ? 0 : amount || 10;
        var rgb = tinycolor(color).toRgb();
        rgb.r = Math.max(0, Math.min(255, rgb.r - Math.round(255 * -(amount / 100))));
        rgb.g = Math.max(0, Math.min(255, rgb.g - Math.round(255 * -(amount / 100))));
        rgb.b = Math.max(0, Math.min(255, rgb.b - Math.round(255 * -(amount / 100))));
        return tinycolor(rgb);
      }
      __name(_brighten, "_brighten");
      function _darken(color, amount) {
        amount = amount === 0 ? 0 : amount || 10;
        var hsl = tinycolor(color).toHsl();
        hsl.l -= amount / 100;
        hsl.l = clamp01(hsl.l);
        return tinycolor(hsl);
      }
      __name(_darken, "_darken");
      function _spin(color, amount) {
        var hsl = tinycolor(color).toHsl();
        var hue = (hsl.h + amount) % 360;
        hsl.h = hue < 0 ? 360 + hue : hue;
        return tinycolor(hsl);
      }
      __name(_spin, "_spin");
      function _complement(color) {
        var hsl = tinycolor(color).toHsl();
        hsl.h = (hsl.h + 180) % 360;
        return tinycolor(hsl);
      }
      __name(_complement, "_complement");
      function polyad(color, number) {
        if (isNaN(number) || number <= 0) {
          throw new Error("Argument to polyad must be a positive number");
        }
        var hsl = tinycolor(color).toHsl();
        var result = [tinycolor(color)];
        var step = 360 / number;
        for (var i = 1; i < number; i++) {
          result.push(tinycolor({
            h: (hsl.h + i * step) % 360,
            s: hsl.s,
            l: hsl.l
          }));
        }
        return result;
      }
      __name(polyad, "polyad");
      function _splitcomplement(color) {
        var hsl = tinycolor(color).toHsl();
        var h = hsl.h;
        return [tinycolor(color), tinycolor({
          h: (h + 72) % 360,
          s: hsl.s,
          l: hsl.l
        }), tinycolor({
          h: (h + 216) % 360,
          s: hsl.s,
          l: hsl.l
        })];
      }
      __name(_splitcomplement, "_splitcomplement");
      function _analogous(color, results, slices) {
        results = results || 6;
        slices = slices || 30;
        var hsl = tinycolor(color).toHsl();
        var part = 360 / slices;
        var ret = [tinycolor(color)];
        for (hsl.h = (hsl.h - (part * results >> 1) + 720) % 360; --results; ) {
          hsl.h = (hsl.h + part) % 360;
          ret.push(tinycolor(hsl));
        }
        return ret;
      }
      __name(_analogous, "_analogous");
      function _monochromatic(color, results) {
        results = results || 6;
        var hsv = tinycolor(color).toHsv();
        var h = hsv.h, s = hsv.s, v = hsv.v;
        var ret = [];
        var modification = 1 / results;
        while (results--) {
          ret.push(tinycolor({
            h,
            s,
            v
          }));
          v = (v + modification) % 1;
        }
        return ret;
      }
      __name(_monochromatic, "_monochromatic");
      tinycolor.mix = function(color1, color2, amount) {
        amount = amount === 0 ? 0 : amount || 50;
        var rgb1 = tinycolor(color1).toRgb();
        var rgb2 = tinycolor(color2).toRgb();
        var p = amount / 100;
        var rgba = {
          r: (rgb2.r - rgb1.r) * p + rgb1.r,
          g: (rgb2.g - rgb1.g) * p + rgb1.g,
          b: (rgb2.b - rgb1.b) * p + rgb1.b,
          a: (rgb2.a - rgb1.a) * p + rgb1.a
        };
        return tinycolor(rgba);
      };
      tinycolor.readability = function(color1, color2) {
        var c1 = tinycolor(color1);
        var c2 = tinycolor(color2);
        return (Math.max(c1.getLuminance(), c2.getLuminance()) + 0.05) / (Math.min(c1.getLuminance(), c2.getLuminance()) + 0.05);
      };
      tinycolor.isReadable = function(color1, color2, wcag2) {
        var readability = tinycolor.readability(color1, color2);
        var wcag2Parms, out;
        out = false;
        wcag2Parms = validateWCAG2Parms(wcag2);
        switch (wcag2Parms.level + wcag2Parms.size) {
          case "AAsmall":
          case "AAAlarge":
            out = readability >= 4.5;
            break;
          case "AAlarge":
            out = readability >= 3;
            break;
          case "AAAsmall":
            out = readability >= 7;
            break;
        }
        return out;
      };
      tinycolor.mostReadable = function(baseColor, colorList, args) {
        var bestColor = null;
        var bestScore = 0;
        var readability;
        var includeFallbackColors, level, size;
        args = args || {};
        includeFallbackColors = args.includeFallbackColors;
        level = args.level;
        size = args.size;
        for (var i = 0; i < colorList.length; i++) {
          readability = tinycolor.readability(baseColor, colorList[i]);
          if (readability > bestScore) {
            bestScore = readability;
            bestColor = tinycolor(colorList[i]);
          }
        }
        if (tinycolor.isReadable(baseColor, bestColor, {
          level,
          size
        }) || !includeFallbackColors) {
          return bestColor;
        } else {
          args.includeFallbackColors = false;
          return tinycolor.mostReadable(baseColor, ["#fff", "#000"], args);
        }
      };
      var names = tinycolor.names = {
        aliceblue: "f0f8ff",
        antiquewhite: "faebd7",
        aqua: "0ff",
        aquamarine: "7fffd4",
        azure: "f0ffff",
        beige: "f5f5dc",
        bisque: "ffe4c4",
        black: "000",
        blanchedalmond: "ffebcd",
        blue: "00f",
        blueviolet: "8a2be2",
        brown: "a52a2a",
        burlywood: "deb887",
        burntsienna: "ea7e5d",
        cadetblue: "5f9ea0",
        chartreuse: "7fff00",
        chocolate: "d2691e",
        coral: "ff7f50",
        cornflowerblue: "6495ed",
        cornsilk: "fff8dc",
        crimson: "dc143c",
        cyan: "0ff",
        darkblue: "00008b",
        darkcyan: "008b8b",
        darkgoldenrod: "b8860b",
        darkgray: "a9a9a9",
        darkgreen: "006400",
        darkgrey: "a9a9a9",
        darkkhaki: "bdb76b",
        darkmagenta: "8b008b",
        darkolivegreen: "556b2f",
        darkorange: "ff8c00",
        darkorchid: "9932cc",
        darkred: "8b0000",
        darksalmon: "e9967a",
        darkseagreen: "8fbc8f",
        darkslateblue: "483d8b",
        darkslategray: "2f4f4f",
        darkslategrey: "2f4f4f",
        darkturquoise: "00ced1",
        darkviolet: "9400d3",
        deeppink: "ff1493",
        deepskyblue: "00bfff",
        dimgray: "696969",
        dimgrey: "696969",
        dodgerblue: "1e90ff",
        firebrick: "b22222",
        floralwhite: "fffaf0",
        forestgreen: "228b22",
        fuchsia: "f0f",
        gainsboro: "dcdcdc",
        ghostwhite: "f8f8ff",
        gold: "ffd700",
        goldenrod: "daa520",
        gray: "808080",
        green: "008000",
        greenyellow: "adff2f",
        grey: "808080",
        honeydew: "f0fff0",
        hotpink: "ff69b4",
        indianred: "cd5c5c",
        indigo: "4b0082",
        ivory: "fffff0",
        khaki: "f0e68c",
        lavender: "e6e6fa",
        lavenderblush: "fff0f5",
        lawngreen: "7cfc00",
        lemonchiffon: "fffacd",
        lightblue: "add8e6",
        lightcoral: "f08080",
        lightcyan: "e0ffff",
        lightgoldenrodyellow: "fafad2",
        lightgray: "d3d3d3",
        lightgreen: "90ee90",
        lightgrey: "d3d3d3",
        lightpink: "ffb6c1",
        lightsalmon: "ffa07a",
        lightseagreen: "20b2aa",
        lightskyblue: "87cefa",
        lightslategray: "789",
        lightslategrey: "789",
        lightsteelblue: "b0c4de",
        lightyellow: "ffffe0",
        lime: "0f0",
        limegreen: "32cd32",
        linen: "faf0e6",
        magenta: "f0f",
        maroon: "800000",
        mediumaquamarine: "66cdaa",
        mediumblue: "0000cd",
        mediumorchid: "ba55d3",
        mediumpurple: "9370db",
        mediumseagreen: "3cb371",
        mediumslateblue: "7b68ee",
        mediumspringgreen: "00fa9a",
        mediumturquoise: "48d1cc",
        mediumvioletred: "c71585",
        midnightblue: "191970",
        mintcream: "f5fffa",
        mistyrose: "ffe4e1",
        moccasin: "ffe4b5",
        navajowhite: "ffdead",
        navy: "000080",
        oldlace: "fdf5e6",
        olive: "808000",
        olivedrab: "6b8e23",
        orange: "ffa500",
        orangered: "ff4500",
        orchid: "da70d6",
        palegoldenrod: "eee8aa",
        palegreen: "98fb98",
        paleturquoise: "afeeee",
        palevioletred: "db7093",
        papayawhip: "ffefd5",
        peachpuff: "ffdab9",
        peru: "cd853f",
        pink: "ffc0cb",
        plum: "dda0dd",
        powderblue: "b0e0e6",
        purple: "800080",
        rebeccapurple: "663399",
        red: "f00",
        rosybrown: "bc8f8f",
        royalblue: "4169e1",
        saddlebrown: "8b4513",
        salmon: "fa8072",
        sandybrown: "f4a460",
        seagreen: "2e8b57",
        seashell: "fff5ee",
        sienna: "a0522d",
        silver: "c0c0c0",
        skyblue: "87ceeb",
        slateblue: "6a5acd",
        slategray: "708090",
        slategrey: "708090",
        snow: "fffafa",
        springgreen: "00ff7f",
        steelblue: "4682b4",
        tan: "d2b48c",
        teal: "008080",
        thistle: "d8bfd8",
        tomato: "ff6347",
        turquoise: "40e0d0",
        violet: "ee82ee",
        wheat: "f5deb3",
        white: "fff",
        whitesmoke: "f5f5f5",
        yellow: "ff0",
        yellowgreen: "9acd32"
      };
      var hexNames = tinycolor.hexNames = flip(names);
      function flip(o) {
        var flipped = {};
        for (var i in o) {
          if (o.hasOwnProperty(i)) {
            flipped[o[i]] = i;
          }
        }
        return flipped;
      }
      __name(flip, "flip");
      function boundAlpha(a) {
        a = parseFloat(a);
        if (isNaN(a) || a < 0 || a > 1) {
          a = 1;
        }
        return a;
      }
      __name(boundAlpha, "boundAlpha");
      function bound01(n, max) {
        if (isOnePointZero(n)) n = "100%";
        var processPercent = isPercentage(n);
        n = Math.min(max, Math.max(0, parseFloat(n)));
        if (processPercent) {
          n = parseInt(n * max, 10) / 100;
        }
        if (Math.abs(n - max) < 1e-6) {
          return 1;
        }
        return n % max / parseFloat(max);
      }
      __name(bound01, "bound01");
      function clamp01(val) {
        return Math.min(1, Math.max(0, val));
      }
      __name(clamp01, "clamp01");
      function parseIntFromHex(val) {
        return parseInt(val, 16);
      }
      __name(parseIntFromHex, "parseIntFromHex");
      function isOnePointZero(n) {
        return typeof n == "string" && n.indexOf(".") != -1 && parseFloat(n) === 1;
      }
      __name(isOnePointZero, "isOnePointZero");
      function isPercentage(n) {
        return typeof n === "string" && n.indexOf("%") != -1;
      }
      __name(isPercentage, "isPercentage");
      function pad2(c) {
        return c.length == 1 ? "0" + c : "" + c;
      }
      __name(pad2, "pad2");
      function convertToPercentage(n) {
        if (n <= 1) {
          n = n * 100 + "%";
        }
        return n;
      }
      __name(convertToPercentage, "convertToPercentage");
      function convertDecimalToHex(d) {
        return Math.round(parseFloat(d) * 255).toString(16);
      }
      __name(convertDecimalToHex, "convertDecimalToHex");
      function convertHexToDecimal(h) {
        return parseIntFromHex(h) / 255;
      }
      __name(convertHexToDecimal, "convertHexToDecimal");
      var matchers = function() {
        var CSS_INTEGER = "[-\\+]?\\d+%?";
        var CSS_NUMBER = "[-\\+]?\\d*\\.\\d+%?";
        var CSS_UNIT = "(?:" + CSS_NUMBER + ")|(?:" + CSS_INTEGER + ")";
        var PERMISSIVE_MATCH3 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?";
        var PERMISSIVE_MATCH4 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?";
        return {
          CSS_UNIT: new RegExp(CSS_UNIT),
          rgb: new RegExp("rgb" + PERMISSIVE_MATCH3),
          rgba: new RegExp("rgba" + PERMISSIVE_MATCH4),
          hsl: new RegExp("hsl" + PERMISSIVE_MATCH3),
          hsla: new RegExp("hsla" + PERMISSIVE_MATCH4),
          hsv: new RegExp("hsv" + PERMISSIVE_MATCH3),
          hsva: new RegExp("hsva" + PERMISSIVE_MATCH4),
          hex3: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,
          hex6: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,
          hex4: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,
          hex8: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/
        };
      }();
      function isValidCSSUnit(color) {
        return !!matchers.CSS_UNIT.exec(color);
      }
      __name(isValidCSSUnit, "isValidCSSUnit");
      function stringInputToObject(color) {
        color = color.replace(trimLeft, "").replace(trimRight, "").toLowerCase();
        var named = false;
        if (names[color]) {
          color = names[color];
          named = true;
        } else if (color == "transparent") {
          return {
            r: 0,
            g: 0,
            b: 0,
            a: 0,
            format: "name"
          };
        }
        var match;
        if (match = matchers.rgb.exec(color)) {
          return {
            r: match[1],
            g: match[2],
            b: match[3]
          };
        }
        if (match = matchers.rgba.exec(color)) {
          return {
            r: match[1],
            g: match[2],
            b: match[3],
            a: match[4]
          };
        }
        if (match = matchers.hsl.exec(color)) {
          return {
            h: match[1],
            s: match[2],
            l: match[3]
          };
        }
        if (match = matchers.hsla.exec(color)) {
          return {
            h: match[1],
            s: match[2],
            l: match[3],
            a: match[4]
          };
        }
        if (match = matchers.hsv.exec(color)) {
          return {
            h: match[1],
            s: match[2],
            v: match[3]
          };
        }
        if (match = matchers.hsva.exec(color)) {
          return {
            h: match[1],
            s: match[2],
            v: match[3],
            a: match[4]
          };
        }
        if (match = matchers.hex8.exec(color)) {
          return {
            r: parseIntFromHex(match[1]),
            g: parseIntFromHex(match[2]),
            b: parseIntFromHex(match[3]),
            a: convertHexToDecimal(match[4]),
            format: named ? "name" : "hex8"
          };
        }
        if (match = matchers.hex6.exec(color)) {
          return {
            r: parseIntFromHex(match[1]),
            g: parseIntFromHex(match[2]),
            b: parseIntFromHex(match[3]),
            format: named ? "name" : "hex"
          };
        }
        if (match = matchers.hex4.exec(color)) {
          return {
            r: parseIntFromHex(match[1] + "" + match[1]),
            g: parseIntFromHex(match[2] + "" + match[2]),
            b: parseIntFromHex(match[3] + "" + match[3]),
            a: convertHexToDecimal(match[4] + "" + match[4]),
            format: named ? "name" : "hex8"
          };
        }
        if (match = matchers.hex3.exec(color)) {
          return {
            r: parseIntFromHex(match[1] + "" + match[1]),
            g: parseIntFromHex(match[2] + "" + match[2]),
            b: parseIntFromHex(match[3] + "" + match[3]),
            format: named ? "name" : "hex"
          };
        }
        return false;
      }
      __name(stringInputToObject, "stringInputToObject");
      function validateWCAG2Parms(parms) {
        var level, size;
        parms = parms || {
          level: "AA",
          size: "small"
        };
        level = (parms.level || "AA").toUpperCase();
        size = (parms.size || "small").toLowerCase();
        if (level !== "AA" && level !== "AAA") {
          level = "AA";
        }
        if (size !== "small" && size !== "large") {
          size = "small";
        }
        return {
          level,
          size
        };
      }
      __name(validateWCAG2Parms, "validateWCAG2Parms");
      return tinycolor;
    });
  }
});

// node_modules/tinygradient/index.js
var require_tinygradient = __commonJS({
  "node_modules/tinygradient/index.js"(exports, module) {
    init_esbuild_shims();
    var tinycolor = require_tinycolor();
    var RGBA_MAX = { r: 256, g: 256, b: 256, a: 1 };
    var HSVA_MAX = { h: 360, s: 1, v: 1, a: 1 };
    function stepize(start, end, steps) {
      let step = {};
      for (let k in start) {
        if (start.hasOwnProperty(k)) {
          step[k] = steps === 0 ? 0 : (end[k] - start[k]) / steps;
        }
      }
      return step;
    }
    __name(stepize, "stepize");
    function interpolate(step, start, i, max) {
      let color = {};
      for (let k in start) {
        if (start.hasOwnProperty(k)) {
          color[k] = step[k] * i + start[k];
          color[k] = color[k] < 0 ? color[k] + max[k] : max[k] !== 1 ? color[k] % max[k] : color[k];
        }
      }
      return color;
    }
    __name(interpolate, "interpolate");
    function interpolateRgb(stop1, stop2, steps) {
      const start = stop1.color.toRgb();
      const end = stop2.color.toRgb();
      const step = stepize(start, end, steps);
      let gradient = [stop1.color];
      for (let i = 1; i < steps; i++) {
        const color = interpolate(step, start, i, RGBA_MAX);
        gradient.push(tinycolor(color));
      }
      return gradient;
    }
    __name(interpolateRgb, "interpolateRgb");
    function interpolateHsv(stop1, stop2, steps, mode) {
      const start = stop1.color.toHsv();
      const end = stop2.color.toHsv();
      if (start.s === 0 || end.s === 0) {
        return interpolateRgb(stop1, stop2, steps);
      }
      let trigonometric;
      if (typeof mode === "boolean") {
        trigonometric = mode;
      } else {
        const trigShortest = start.h < end.h && end.h - start.h < 180 || start.h > end.h && start.h - end.h > 180;
        trigonometric = mode === "long" && trigShortest || mode === "short" && !trigShortest;
      }
      const step = stepize(start, end, steps);
      let gradient = [stop1.color];
      let diff;
      if (start.h <= end.h && !trigonometric || start.h >= end.h && trigonometric) {
        diff = end.h - start.h;
      } else if (trigonometric) {
        diff = 360 - end.h + start.h;
      } else {
        diff = 360 - start.h + end.h;
      }
      step.h = Math.pow(-1, trigonometric ? 1 : 0) * Math.abs(diff) / steps;
      for (let i = 1; i < steps; i++) {
        const color = interpolate(step, start, i, HSVA_MAX);
        gradient.push(tinycolor(color));
      }
      return gradient;
    }
    __name(interpolateHsv, "interpolateHsv");
    function computeSubsteps(stops, steps) {
      const l = stops.length;
      steps = parseInt(steps, 10);
      if (isNaN(steps) || steps < 2) {
        throw new Error("Invalid number of steps (< 2)");
      }
      if (steps < l) {
        throw new Error("Number of steps cannot be inferior to number of stops");
      }
      let substeps = [];
      for (let i = 1; i < l; i++) {
        const step = (steps - 1) * (stops[i].pos - stops[i - 1].pos);
        substeps.push(Math.max(1, Math.round(step)));
      }
      let totalSubsteps = 1;
      for (let n = l - 1; n--; ) totalSubsteps += substeps[n];
      while (totalSubsteps !== steps) {
        if (totalSubsteps < steps) {
          const min = Math.min.apply(null, substeps);
          substeps[substeps.indexOf(min)]++;
          totalSubsteps++;
        } else {
          const max = Math.max.apply(null, substeps);
          substeps[substeps.indexOf(max)]--;
          totalSubsteps--;
        }
      }
      return substeps;
    }
    __name(computeSubsteps, "computeSubsteps");
    function computeAt(stops, pos, method, max) {
      if (pos < 0 || pos > 1) {
        throw new Error("Position must be between 0 and 1");
      }
      let start, end;
      for (let i = 0, l = stops.length; i < l - 1; i++) {
        if (pos >= stops[i].pos && pos < stops[i + 1].pos) {
          start = stops[i];
          end = stops[i + 1];
          break;
        }
      }
      if (!start) {
        start = end = stops[stops.length - 1];
      }
      const step = stepize(start.color[method](), end.color[method](), (end.pos - start.pos) * 100);
      const color = interpolate(step, start.color[method](), (pos - start.pos) * 100, max);
      return tinycolor(color);
    }
    __name(computeAt, "computeAt");
    var TinyGradient = class _TinyGradient {
      static {
        __name(this, "TinyGradient");
      }
      /**
       * @param {StopInput[]|ColorInput[]} stops
       * @returns {TinyGradient}
       */
      constructor(stops) {
        if (stops.length < 2) {
          throw new Error("Invalid number of stops (< 2)");
        }
        const havingPositions = stops[0].pos !== void 0;
        let l = stops.length;
        let p = -1;
        let lastColorLess = false;
        this.stops = stops.map((stop, i) => {
          const hasPosition = stop.pos !== void 0;
          if (havingPositions ^ hasPosition) {
            throw new Error("Cannot mix positionned and not posionned color stops");
          }
          if (hasPosition) {
            const hasColor = stop.color !== void 0;
            if (!hasColor && (lastColorLess || i === 0 || i === l - 1)) {
              throw new Error("Cannot define two consecutive position-only stops");
            }
            lastColorLess = !hasColor;
            stop = {
              color: hasColor ? tinycolor(stop.color) : null,
              colorLess: !hasColor,
              pos: stop.pos
            };
            if (stop.pos < 0 || stop.pos > 1) {
              throw new Error("Color stops positions must be between 0 and 1");
            } else if (stop.pos < p) {
              throw new Error("Color stops positions are not ordered");
            }
            p = stop.pos;
          } else {
            stop = {
              color: tinycolor(stop.color !== void 0 ? stop.color : stop),
              pos: i / (l - 1)
            };
          }
          return stop;
        });
        if (this.stops[0].pos !== 0) {
          this.stops.unshift({
            color: this.stops[0].color,
            pos: 0
          });
          l++;
        }
        if (this.stops[l - 1].pos !== 1) {
          this.stops.push({
            color: this.stops[l - 1].color,
            pos: 1
          });
        }
      }
      /**
       * Return new instance with reversed stops
       * @return {TinyGradient}
       */
      reverse() {
        let stops = [];
        this.stops.forEach(function(stop) {
          stops.push({
            color: stop.color,
            pos: 1 - stop.pos
          });
        });
        return new _TinyGradient(stops.reverse());
      }
      /**
       * Return new instance with looped stops
       * @return {TinyGradient}
       */
      loop() {
        let stops1 = [];
        let stops2 = [];
        this.stops.forEach((stop) => {
          stops1.push({
            color: stop.color,
            pos: stop.pos / 2
          });
        });
        this.stops.slice(0, -1).forEach((stop) => {
          stops2.push({
            color: stop.color,
            pos: 1 - stop.pos / 2
          });
        });
        return new _TinyGradient(stops1.concat(stops2.reverse()));
      }
      /**
       * Generate gradient with RGBa interpolation
       * @param {number} steps
       * @return {tinycolor[]}
       */
      rgb(steps) {
        const substeps = computeSubsteps(this.stops, steps);
        let gradient = [];
        this.stops.forEach((stop, i) => {
          if (stop.colorLess) {
            stop.color = interpolateRgb(this.stops[i - 1], this.stops[i + 1], 2)[1];
          }
        });
        for (let i = 0, l = this.stops.length; i < l - 1; i++) {
          const rgb = interpolateRgb(this.stops[i], this.stops[i + 1], substeps[i]);
          gradient.splice(gradient.length, 0, ...rgb);
        }
        gradient.push(this.stops[this.stops.length - 1].color);
        return gradient;
      }
      /**
       * Generate gradient with HSVa interpolation
       * @param {number} steps
       * @param {boolean|'long'|'short'} [mode=false]
       *    - false to step in clockwise
       *    - true to step in trigonometric order
       *    - 'short' to use the shortest way
       *    - 'long' to use the longest way
       * @return {tinycolor[]}
       */
      hsv(steps, mode) {
        const substeps = computeSubsteps(this.stops, steps);
        let gradient = [];
        this.stops.forEach((stop, i) => {
          if (stop.colorLess) {
            stop.color = interpolateHsv(this.stops[i - 1], this.stops[i + 1], 2, mode)[1];
          }
        });
        for (let i = 0, l = this.stops.length; i < l - 1; i++) {
          const hsv = interpolateHsv(this.stops[i], this.stops[i + 1], substeps[i], mode);
          gradient.splice(gradient.length, 0, ...hsv);
        }
        gradient.push(this.stops[this.stops.length - 1].color);
        return gradient;
      }
      /**
       * Generate CSS3 command (no prefix) for this gradient
       * @param {String} [mode=linear] - 'linear' or 'radial'
       * @param {String} [direction] - default is 'to right' or 'ellipse at center'
       * @return {String}
       */
      css(mode, direction) {
        mode = mode || "linear";
        direction = direction || (mode === "linear" ? "to right" : "ellipse at center");
        let css = mode + "-gradient(" + direction;
        this.stops.forEach(function(stop) {
          css += ", " + (stop.colorLess ? "" : stop.color.toRgbString() + " ") + stop.pos * 100 + "%";
        });
        css += ")";
        return css;
      }
      /**
       * Returns the color at specific position with RGBa interpolation
       * @param {number} pos, between 0 and 1
       * @return {tinycolor}
       */
      rgbAt(pos) {
        return computeAt(this.stops, pos, "toRgb", RGBA_MAX);
      }
      /**
       * Returns the color at specific position with HSVa interpolation
       * @param {number} pos, between 0 and 1
       * @return {tinycolor}
       */
      hsvAt(pos) {
        return computeAt(this.stops, pos, "toHsv", HSVA_MAX);
      }
    };
    module.exports = function(stops) {
      if (arguments.length === 1) {
        if (!Array.isArray(arguments[0])) {
          throw new Error('"stops" is not an array');
        }
        stops = arguments[0];
      } else {
        stops = Array.prototype.slice.call(arguments);
      }
      return new TinyGradient(stops);
    };
  }
});

// node_modules/gradient-string/index.js
var require_gradient_string = __commonJS({
  "node_modules/gradient-string/index.js"(exports, module) {
    "use strict";
    init_esbuild_shims();
    var chalk2 = require_source();
    var tinygradient = require_tinygradient();
    var forbiddenChars = /\s/g;
    function InitGradient(...args) {
      const grad = tinygradient.apply(this, args);
      const ret = /* @__PURE__ */ __name((str, opts) => applyGradient(str ? str.toString() : "", grad, opts), "ret");
      ret.multiline = (str, opts) => multilineGradient(str ? str.toString() : "", grad, opts);
      return ret;
    }
    __name(InitGradient, "InitGradient");
    var getColors = /* @__PURE__ */ __name((gradient, options, count) => options.interpolation.toLowerCase() === "hsv" ? gradient.hsv(count, options.hsvSpin.toLowerCase()) : gradient.rgb(count), "getColors");
    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 : chalk2.hex(colors.shift().toHex())(s);
      }
      return result;
    }
    __name(applyGradient, "applyGradient");
    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 += chalk2.hex(lineColors.shift().toHex())(l);
        }
        results.push(lineResult);
      }
      return results.join("\n");
    }
    __name(multilineGradient, "multilineGradient");
    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;
    }
    __name(validateOptions, "validateOptions");
    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);
    }
  }
});

// packages/cli/src/ui/contexts/ConfigContext.tsx
init_esbuild_shims();
var import_react = __toESM(require_react(), 1);
var ConfigContext = import_react.default.createContext(void 0);
var useConfig = /* @__PURE__ */ __name(() => {
  const context = (0, import_react.useContext)(ConfigContext);
  if (context === void 0) {
    throw new Error("useConfig must be used within a ConfigProvider");
  }
  return context;
}, "useConfig");

// packages/cli/src/ui/components/SessionPicker.tsx
init_esbuild_shims();

// packages/cli/src/ui/hooks/useSessionPicker.ts
init_esbuild_shims();
var import_react3 = __toESM(require_react(), 1);

// packages/cli/src/ui/utils/sessionPickerUtils.ts
init_esbuild_shims();
var graphemeSegmenter = new Intl.Segmenter(void 0, {
  granularity: "grapheme"
});
var SESSION_PAGE_SIZE = 20;
function truncateText(text, maxWidth) {
  const widthLimit = Math.max(0, Math.floor(maxWidth));
  if (widthLimit === 0) {
    return "";
  }
  const firstLine = text.split(/\r?\n/, 1)[0];
  if (getCachedStringWidth(firstLine) <= widthLimit) {
    return firstLine;
  }
  if (widthLimit <= 3) {
    return truncateToDisplayWidth(firstLine, widthLimit);
  }
  return `${truncateToDisplayWidth(firstLine, widthLimit - 3)}...`;
}
__name(truncateText, "truncateText");
function truncateToDisplayWidth(text, maxWidth) {
  let width = 0;
  let result = "";
  for (const { segment } of graphemeSegmenter.segment(text)) {
    const segmentWidth = getCachedStringWidth(segment);
    if (width + segmentWidth > maxWidth) {
      break;
    }
    result += segment;
    width += segmentWidth;
  }
  return result;
}
__name(truncateToDisplayWidth, "truncateToDisplayWidth");
function matchesQuery(session, normalizedQuery) {
  if (!normalizedQuery) return true;
  const haystacks = [
    session.customTitle,
    session.prompt,
    session.gitBranch
  ];
  for (const h of haystacks) {
    if (h && h.toLowerCase().includes(normalizedQuery)) return true;
  }
  return false;
}
__name(matchesQuery, "matchesQuery");
function filterSessions(sessions, filterByBranch, currentBranch, query) {
  const normalizedQuery = query?.toLowerCase().trim() ?? "";
  return sessions.filter((session) => {
    if (filterByBranch && currentBranch) {
      if (session.gitBranch !== currentBranch) return false;
    }
    return matchesQuery(session, normalizedQuery);
  });
}
__name(filterSessions, "filterSessions");
function formatMessageCount(count) {
  return count === 1 ? "1 message" : `${count} messages`;
}
__name(formatMessageCount, "formatMessageCount");

// packages/cli/src/ui/hooks/useSessionSearchInput.ts
init_esbuild_shims();
var import_react2 = __toESM(require_react(), 1);
var DELETION_KEY_NAMES = /* @__PURE__ */ new Set(["backspace", "delete"]);
var graphemeSegmenter2 = new Intl.Segmenter(void 0, {
  granularity: "grapheme"
});
function splitGraphemes(value) {
  return Array.from(graphemeSegmenter2.segment(value), ({ segment }) => segment);
}
__name(splitGraphemes, "splitGraphemes");
function removeLastGrapheme(value) {
  const graphemes = splitGraphemes(value);
  graphemes.pop();
  return graphemes.join("");
}
__name(removeLastGrapheme, "removeLastGrapheme");
var isDeletionKey = /* @__PURE__ */ __name((key) => DELETION_KEY_NAMES.has(key.name) || !key.ctrl && !key.meta && (key.sequence === "\x7F" || key.sequence === "\b"), "isDeletionKey");
function isPrintableSearchChar(key) {
  if (key.ctrl || key.meta || key.paste) return false;
  const graphemes = splitGraphemes(key.sequence);
  if (graphemes.length !== 1) return false;
  const code = graphemes[0].codePointAt(0);
  if (code === void 0) return false;
  return code >= 32 && code !== 127 && (code < 128 || code > 159);
}
__name(isPrintableSearchChar, "isPrintableSearchChar");
function useSessionSearchInput(options) {
  const { onExitToList } = options;
  const [searchQuery, rawSetSearchQuery] = (0, import_react2.useState)("");
  const searchQueryRef = (0, import_react2.useRef)("");
  const onExitToListRef = (0, import_react2.useRef)(onExitToList);
  onExitToListRef.current = onExitToList;
  const setSearchQuery = (0, import_react2.useCallback)(
    (nextValue) => {
      const prev = searchQueryRef.current;
      const next = typeof nextValue === "function" ? nextValue(prev) : nextValue;
      searchQueryRef.current = next;
      rawSetSearchQuery(next);
      if (prev !== "" && next === "") {
        onExitToListRef.current();
      }
    },
    []
  );
  const handleSearchKey = (0, import_react2.useCallback)(
    (key) => {
      const { name, sequence, ctrl } = key;
      if (name === "escape") {
        setSearchQuery("");
        return;
      }
      if (isDeletionKey(key)) {
        setSearchQuery(removeLastGrapheme);
        return;
      }
      if (ctrl && (name === "u" || name === "l")) {
        setSearchQuery("");
        return;
      }
      if (isPrintableSearchChar(key)) {
        setSearchQuery((q) => q + sequence);
        return;
      }
    },
    [setSearchQuery]
  );
  return { searchQuery, setSearchQuery, handleSearchKey };
}
__name(useSessionSearchInput, "useSessionSearchInput");

// packages/cli/src/ui/hooks/useSessionPicker.ts
function useSessionPicker({
  sessionService,
  currentBranch,
  onSelect,
  onCancel,
  maxVisibleItems,
  centerSelection = false,
  initialSessions,
  isActive = true,
  enablePreview = false,
  enableMultiSelect = false,
  onConfirmMulti,
  disabledIds
}) {
  if (enableMultiSelect && enablePreview) {
    throw new Error(
      "useSessionPicker: enableMultiSelect and enablePreview both bind Space; pick one or wire a different chord."
    );
  }
  if (enableMultiSelect && !onConfirmMulti) {
    throw new Error(
      "useSessionPicker: enableMultiSelect requires onConfirmMulti."
    );
  }
  const hasInitialSessions = initialSessions !== void 0;
  const [selectedIndex, setSelectedIndex] = (0, import_react3.useState)(0);
  const [sessionState, setSessionState] = (0, import_react3.useState)(
    hasInitialSessions ? { sessions: initialSessions, hasMore: false, nextCursor: void 0 } : { sessions: [], hasMore: true, nextCursor: void 0 }
  );
  const [filterByBranch, setFilterByBranch] = (0, import_react3.useState)(false);
  const [isLoading, setIsLoading] = (0, import_react3.useState)(!hasInitialSessions);
  const [followScrollOffset, setFollowScrollOffset] = (0, import_react3.useState)(0);
  const [viewMode, setViewMode] = (0, import_react3.useState)(
    "list"
  );
  const [previewSessionId, setPreviewSessionId] = (0, import_react3.useState)(null);
  const [checkedIds, setCheckedIds] = (0, import_react3.useState)(
    () => /* @__PURE__ */ new Set()
  );
  const disabledIdSet = (0, import_react3.useMemo)(
    () => new Set(disabledIds ?? []),
    [disabledIds]
  );
  const toggleChecked = (0, import_react3.useCallback)(
    (sessionId) => {
      if (disabledIdSet.has(sessionId)) return;
      setCheckedIds((prev) => {
        const next = new Set(prev);
        if (next.has(sessionId)) {
          next.delete(sessionId);
        } else {
          next.add(sessionId);
        }
        return next;
      });
    },
    [disabledIdSet]
  );
  const exitPreview = (0, import_react3.useCallback)(() => {
    setViewMode("list");
    setPreviewSessionId(null);
  }, []);
  const onExitToList = (0, import_react3.useCallback)(() => {
    setViewMode("list");
  }, []);
  const { searchQuery, setSearchQuery, handleSearchKey } = useSessionSearchInput({ onExitToList });
  const isLoadingMoreRef = (0, import_react3.useRef)(false);
  const filteredSessions = (0, import_react3.useMemo)(
    () => filterSessions(
      sessionState.sessions,
      filterByBranch,
      currentBranch,
      searchQuery
    ),
    [sessionState.sessions, filterByBranch, currentBranch, searchQuery]
  );
  const scrollOffset = (0, import_react3.useMemo)(() => {
    if (centerSelection) {
      if (filteredSessions.length <= maxVisibleItems) {
        return 0;
      }
      const halfVisible = Math.floor(maxVisibleItems / 2);
      let offset = selectedIndex - halfVisible;
      offset = Math.max(0, offset);
      offset = Math.min(filteredSessions.length - maxVisibleItems, offset);
      return offset;
    }
    return followScrollOffset;
  }, [
    centerSelection,
    filteredSessions.length,
    followScrollOffset,
    maxVisibleItems,
    selectedIndex
  ]);
  const visibleSessions = (0, import_react3.useMemo)(
    () => filteredSessions.slice(scrollOffset, scrollOffset + maxVisibleItems),
    [filteredSessions, maxVisibleItems, scrollOffset]
  );
  const showScrollUp = scrollOffset > 0;
  const showScrollDown = scrollOffset + maxVisibleItems < filteredSessions.length;
  (0, import_react3.useEffect)(() => {
    if (!sessionService || hasInitialSessions) {
      return;
    }
    const loadInitialSessions = /* @__PURE__ */ __name(async () => {
      try {
        const result = await sessionService.listSessions({
          size: SESSION_PAGE_SIZE
        });
        setSessionState({
          sessions: result.items,
          hasMore: result.hasMore,
          nextCursor: result.nextCursor
        });
      } finally {
        setIsLoading(false);
      }
    }, "loadInitialSessions");
    void loadInitialSessions();
  }, [sessionService, hasInitialSessions]);
  const loadMoreSessions = (0, import_react3.useCallback)(async () => {
    if (!sessionService || !sessionState.hasMore || isLoadingMoreRef.current) {
      return;
    }
    isLoadingMoreRef.current = true;
    try {
      const result = await sessionService.listSessions({
        size: SESSION_PAGE_SIZE,
        cursor: sessionState.nextCursor
      });
      setSessionState((prev) => ({
        sessions: [...prev.sessions, ...result.items],
        hasMore: result.hasMore && result.nextCursor !== void 0,
        nextCursor: result.nextCursor
      }));
    } finally {
      isLoadingMoreRef.current = false;
    }
  }, [sessionService, sessionState.hasMore, sessionState.nextCursor]);
  (0, import_react3.useEffect)(() => {
    setSelectedIndex(0);
    setFollowScrollOffset(0);
  }, [filterByBranch, searchQuery]);
  (0, import_react3.useEffect)(() => {
    if (selectedIndex >= filteredSessions.length && filteredSessions.length > 0) {
      setSelectedIndex(filteredSessions.length - 1);
    }
  }, [filteredSessions.length, selectedIndex]);
  (0, import_react3.useEffect)(() => {
    if (isLoading || !sessionState.hasMore || isLoadingMoreRef.current || !centerSelection) {
      return;
    }
    const sentinelVisible = scrollOffset + maxVisibleItems >= filteredSessions.length;
    const shouldLoadMore = filteredSessions.length === 0 || sentinelVisible;
    if (shouldLoadMore) {
      void loadMoreSessions();
    }
  }, [
    centerSelection,
    filteredSessions.length,
    isLoading,
    loadMoreSessions,
    maxVisibleItems,
    scrollOffset,
    sessionState.hasMore
  ]);
  const moveSelection = (0, import_react3.useCallback)(
    (delta) => {
      if (filteredSessions.length === 0) return;
      if (delta === -1) {
        setSelectedIndex((prev) => {
          const newIndex = Math.max(0, prev - 1);
          if (!centerSelection && newIndex < followScrollOffset) {
            setFollowScrollOffset(newIndex);
          }
          return newIndex;
        });
        return;
      }
      setSelectedIndex((prev) => {
        const newIndex = Math.min(filteredSessions.length - 1, prev + 1);
        if (!centerSelection && newIndex >= followScrollOffset + maxVisibleItems) {
          setFollowScrollOffset(newIndex - maxVisibleItems + 1);
        }
        if (!centerSelection && newIndex >= filteredSessions.length - 3) {
          void loadMoreSessions();
        }
        return newIndex;
      });
    },
    [
      centerSelection,
      filteredSessions.length,
      followScrollOffset,
      loadMoreSessions,
      maxVisibleItems
    ]
  );
  useKeypress(
    (key) => {
      const { name, sequence, ctrl } = key;
      if (ctrl && name === "c") {
        onCancel();
        return;
      }
      if (name === "return") {
        if (viewMode === "search") {
          if (filteredSessions.length === 0) {
            return;
          }
          setViewMode("list");
          return;
        }
        if (enableMultiSelect && checkedIds.size > 0 && onConfirmMulti) {
          const orderedIds = sessionState.sessions.map((s) => s.sessionId).filter((id) => checkedIds.has(id) && !disabledIdSet.has(id));
          if (orderedIds.length > 0) {
            onConfirmMulti(orderedIds);
            return;
          }
          return;
        }
        const session = filteredSessions[selectedIndex];
        if (session && !disabledIdSet.has(session.sessionId)) {
          onSelect(session.sessionId);
        }
        return;
      }
      const isNavUp = name === "up" || ctrl && name === "p";
      const isNavDown = name === "down" || ctrl && name === "n";
      if (isNavUp || isNavDown) {
        const delta = isNavUp ? -1 : 1;
        const inSearch = viewMode === "search";
        if (inSearch) {
          if (filteredSessions.length === 0) return;
          setViewMode("list");
          return;
        }
        if (delta === -1 && filteredSessions.length > 0 && selectedIndex === 0) {
          setViewMode("search");
          return;
        }
        moveSelection(delta);
        return;
      }
      if (viewMode === "search") {
        handleSearchKey(key);
        return;
      }
      if (name === "escape") {
        if (searchQuery !== "") {
          setSearchQuery("");
        } else {
          onCancel();
        }
        return;
      }
      if (name === "k") {
        moveSelection(-1);
        return;
      }
      if (name === "j") {
        moveSelection(1);
        return;
      }
      if (name === "space") {
        if (enableMultiSelect) {
          const session = filteredSessions[selectedIndex];
          if (session) {
            toggleChecked(session.sessionId);
          }
          return;
        }
        if (enablePreview) {
          const session = filteredSessions[selectedIndex];
          if (session) {
            setPreviewSessionId(session.sessionId);
            setViewMode("preview");
          }
          return;
        }
      }
      if (ctrl && (name === "b" || name === "B")) {
        if (currentBranch) {
          setFilterByBranch((prev) => !prev);
        }
        return;
      }
      if (sequence === "/") {
        setViewMode("search");
        return;
      }
      if (isPrintableSearchChar(key)) {
        if (sequence === " ") {
          return;
        }
        setViewMode("search");
        setSearchQuery((q) => q + sequence);
      }
    },
    { isActive: isActive && viewMode !== "preview" }
  );
  return {
    selectedIndex,
    sessionState,
    filteredSessions,
    filterByBranch,
    isLoading,
    scrollOffset,
    visibleSessions,
    showScrollUp,
    showScrollDown,
    loadMoreSessions,
    viewMode,
    previewSessionId,
    exitPreview,
    checkedIds,
    toggleChecked,
    disabledIdSet,
    searchQuery,
    isSearchActive: viewMode === "search"
  };
}
__name(useSessionPicker, "useSessionPicker");

// packages/cli/src/ui/components/SessionPreview.tsx
init_esbuild_shims();
var import_react40 = __toESM(require_react(), 1);

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

// packages/cli/src/ui/components/messages/ConversationMessages.tsx
init_esbuild_shims();

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

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

// packages/cli/src/ui/utils/lowlightLoader.ts
init_esbuild_shims();
var lowlightInstance = null;
var lowlightLoad = null;
var LOWLIGHT_RETRY_COOLDOWN_MS = 3e4;
var lowlightLastFailureAt = 0;
var lowlightError = null;
function getLowlightInstance() {
  return lowlightInstance;
}
__name(getLowlightInstance, "getLowlightInstance");
function isLowlightCoolingDown() {
  return lowlightLastFailureAt > 0 && Date.now() - lowlightLastFailureAt < LOWLIGHT_RETRY_COOLDOWN_MS;
}
__name(isLowlightCoolingDown, "isLowlightCoolingDown");
function loadLowlight() {
  if (lowlightInstance) return Promise.resolve(lowlightInstance);
  if (isLowlightCoolingDown()) {
    return Promise.reject(
      lowlightError ?? new Error("lowlight import previously failed")
    );
  }
  if (lowlightLoad) return lowlightLoad;
  lowlightLoad = import("./lowlight-FYAAUU5J.js").then((mod) => {
    const instance = mod.createLowlight(mod.common);
    if (typeof instance?.registered !== "function" || typeof instance?.highlight !== "function" || typeof instance?.highlightAuto !== "function") {
      throw new Error(
        "lowlight instance does not match expected API (registered/highlight/highlightAuto)"
      );
    }
    lowlightInstance = instance;
    lowlightLastFailureAt = 0;
    lowlightError = null;
    return lowlightInstance;
  }).catch((err) => {
    lowlightLastFailureAt = Date.now();
    lowlightError = err instanceof Error ? err : new Error(String(err));
    lowlightLoad = null;
    throw err;
  });
  return lowlightLoad;
}
__name(loadLowlight, "loadLowlight");

// packages/cli/src/ui/utils/CodeColorizer.tsx
var import_jsx_runtime = __toESM(require_jsx_runtime(), 1);
var debugLogger = createDebugLogger("CODE_COLORIZER");
var STRUCTURAL_BOX_RE = /[│├└┌┐┘┬┴┼]/;
var CJK_RE = /[\u4E00-\u9FFF\u3400-\u4DBF]/g;
function looksLikeDiagramOrArt(line) {
  const trimmed = line.trim();
  if (trimmed.length === 0) return false;
  if (STRUCTURAL_BOX_RE.test(trimmed)) {
    return true;
  }
  const cjkMatches = trimmed.match(CJK_RE) || [];
  const totalChars = trimmed.replace(/\s/g, "").length;
  if (totalChars > 0 && cjkMatches.length / totalChars > 0.3) {
    return true;
  }
  return false;
}
__name(looksLikeDiagramOrArt, "looksLikeDiagramOrArt");
function renderHastNode(node, theme2, inheritedColor) {
  if (node.type === "text") {
    const color = inheritedColor || theme2.defaultColor;
    return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Text, { color, children: node.value });
  }
  if (node.type === "element") {
    const nodeClasses = 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_runtime.jsx)(import_react4.default.Fragment, { children: renderHastNode(child, theme2, colorToPassDown) }, index)
    );
    return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react4.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_runtime.jsx)(import_react4.default.Fragment, { children: renderHastNode(child, theme2, inheritedColor) }, index));
  }
  return null;
}
__name(renderHastNode, "renderHastNode");
function ensureLowlightLoading() {
  const ll = getLowlightInstance();
  if (ll) return ll;
  if (!isLowlightCoolingDown()) {
    void loadLowlight().catch((err) => {
      debugLogger.error("[CodeColorizer] failed to load lowlight:", err);
    });
  }
  return null;
}
__name(ensureLowlightLoading, "ensureLowlightLoading");
function highlightAndRenderLine(line, language, theme2, lowlight) {
  if (!lowlight) {
    return line;
  }
  if (!language && looksLikeDiagramOrArt(line)) {
    return line;
  }
  try {
    const getHighlightedLine = /* @__PURE__ */ __name(() => !language || !lowlight.registered(language) ? lowlight.highlightAuto(line) : lowlight.highlight(language, line), "getHighlightedLine");
    const renderedNode = renderHastNode(getHighlightedLine(), theme2, void 0);
    return renderedNode !== null ? renderedNode : line;
  } catch (_error) {
    return line;
  }
}
__name(highlightAndRenderLine, "highlightAndRenderLine");
function colorizeLine(line, language, theme2) {
  const activeTheme = theme2 || themeManager.getActiveTheme();
  return highlightAndRenderLine(
    line,
    language,
    activeTheme,
    ensureLowlightLoading()
  );
}
__name(colorizeLine, "colorizeLine");
function colorizeCode(code, language, availableHeight, maxWidth, theme2, settings, tabWidth = 4) {
  const codeToHighlight = code.replace(/\n$/, "").replace(/\t/g, " ".repeat(tabWidth));
  const activeTheme = theme2 || themeManager.getActiveTheme();
  const showLineNumbers = settings?.merged.ui?.showLineNumbers ?? true;
  const lowlight = ensureLowlightLoading();
  try {
    let lines = codeToHighlight.split("\n");
    const padWidth = String(lines.length).length;
    let hiddenLinesCount = 0;
    if (availableHeight !== void 0) {
      availableHeight = Math.max(availableHeight, MINIMUM_MAX_HEIGHT);
      if (lines.length > availableHeight) {
        const sliceIndex = lines.length - availableHeight;
        hiddenLinesCount = sliceIndex;
        lines = lines.slice(sliceIndex);
      }
    }
    return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
      MaxSizedBox,
      {
        maxHeight: availableHeight,
        maxWidth,
        additionalHiddenLinesCount: hiddenLinesCount,
        overflowDirection: "top",
        children: lines.map((line, index) => {
          const contentToRender = highlightAndRenderLine(
            line,
            language,
            activeTheme,
            lowlight
          );
          return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Box_default, { children: [
            showLineNumbers && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Text, { color: activeTheme.colors.Gray, children: `${String(index + 1 + hiddenLinesCount).padStart(
              padWidth,
              " "
            )} ` }),
            /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Text, { color: activeTheme.defaultColor, wrap: "wrap", children: contentToRender })
          ] }, index);
        })
      }
    );
  } catch (error) {
    debugLogger.error(
      `[colorizeCode] Error highlighting code for language "${language}":`,
      error
    );
    const lines = codeToHighlight.split("\n");
    const padWidth = String(lines.length).length;
    return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
      MaxSizedBox,
      {
        maxHeight: availableHeight,
        maxWidth,
        overflowDirection: "top",
        children: lines.map((line, index) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Box_default, { children: [
          showLineNumbers && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Text, { color: activeTheme.defaultColor, children: `${String(index + 1).padStart(padWidth, " ")} ` }),
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Text, { color: activeTheme.colors.Gray, children: line })
        ] }, index))
      }
    );
  }
}
__name(colorizeCode, "colorizeCode");

// packages/cli/src/ui/utils/TableRenderer.tsx
init_esbuild_shims();

// packages/cli/node_modules/wrap-ansi/index.js
init_esbuild_shims();

// packages/cli/node_modules/wrap-ansi/node_modules/string-width/index.js
init_esbuild_shims();
var segmenter = new Intl.Segmenter();
var zeroWidthClusterRegex = new RegExp("^(?:\\p{Default_Ignorable_Code_Point}|\\p{Control}|\\p{Format}|\\p{Mark}|\\p{Surrogate})+$", "v");
var leadingNonPrintingRegex = new RegExp("^[\\p{Default_Ignorable_Code_Point}\\p{Control}\\p{Format}\\p{Mark}\\p{Surrogate}]+", "v");
var rgiEmojiRegex = new RegExp("^\\p{RGI_Emoji}$", "v");
var unqualifiedKeycapRegex = /^[\d#*]\u20E3$/;
var extendedPictographicRegex = new RegExp("\\p{Extended_Pictographic}", "gu");
function isDoubleWidthNonRgiEmojiSequence(segment) {
  if (segment.length > 50) {
    return false;
  }
  if (unqualifiedKeycapRegex.test(segment)) {
    return true;
  }
  if (segment.includes("\u200D")) {
    const pictographics = segment.match(extendedPictographicRegex);
    return pictographics !== null && pictographics.length >= 2;
  }
  return false;
}
__name(isDoubleWidthNonRgiEmojiSequence, "isDoubleWidthNonRgiEmojiSequence");
function baseVisible(segment) {
  return segment.replace(leadingNonPrintingRegex, "");
}
__name(baseVisible, "baseVisible");
function isZeroWidthCluster(segment) {
  return zeroWidthClusterRegex.test(segment);
}
__name(isZeroWidthCluster, "isZeroWidthCluster");
function isHangulLeadingJamo(codePoint) {
  return codePoint >= 4352 && codePoint <= 4447 || codePoint >= 43360 && codePoint <= 43388;
}
__name(isHangulLeadingJamo, "isHangulLeadingJamo");
function isHangulVowelJamo(codePoint) {
  return codePoint >= 4448 && codePoint <= 4519 || codePoint >= 55216 && codePoint <= 55238;
}
__name(isHangulVowelJamo, "isHangulVowelJamo");
function isHangulTrailingJamo(codePoint) {
  return codePoint >= 4520 && codePoint <= 4607 || codePoint >= 55243 && codePoint <= 55291;
}
__name(isHangulTrailingJamo, "isHangulTrailingJamo");
function isHangulJamo(codePoint) {
  return isHangulLeadingJamo(codePoint) || isHangulVowelJamo(codePoint) || isHangulTrailingJamo(codePoint);
}
__name(isHangulJamo, "isHangulJamo");
function hangulClusterWidth(visibleSegment, eastAsianWidthOptions) {
  const codePoints = [];
  for (const character of visibleSegment) {
    if (zeroWidthClusterRegex.test(character)) {
      continue;
    }
    codePoints.push(character.codePointAt(0));
  }
  if (codePoints.length === 0) {
    return void 0;
  }
  let width = 0;
  for (let index = 0; index < codePoints.length; index++) {
    const codePoint = codePoints[index];
    if (!isHangulJamo(codePoint)) {
      if (width === 0) {
        return void 0;
      }
      for (let remaining = index; remaining < codePoints.length; remaining++) {
        width += eastAsianWidth(codePoints[remaining], eastAsianWidthOptions);
      }
      return width;
    }
    if (isHangulLeadingJamo(codePoint) && isHangulVowelJamo(codePoints[index + 1])) {
      width += 2;
      index += isHangulTrailingJamo(codePoints[index + 2]) ? 2 : 1;
      continue;
    }
    width += eastAsianWidth(codePoint, eastAsianWidthOptions);
  }
  return width;
}
__name(hangulClusterWidth, "hangulClusterWidth");
function trailingHalfwidthWidth(visibleSegment, eastAsianWidthOptions) {
  let extra = 0;
  let first = true;
  for (const character of visibleSegment) {
    if (first) {
      first = false;
      continue;
    }
    if (character >= "\uFF00" && character <= "\uFFEF") {
      extra += eastAsianWidth(character.codePointAt(0), eastAsianWidthOptions);
    }
  }
  return extra;
}
__name(trailingHalfwidthWidth, "trailingHalfwidthWidth");
function stringWidth2(input, options = {}) {
  if (typeof input !== "string" || input.length === 0) {
    return 0;
  }
  const {
    ambiguousIsNarrow = true,
    countAnsiEscapeCodes = false
  } = options;
  let string = input;
  if (!countAnsiEscapeCodes && (string.includes("\x1B") || string.includes("\x9B"))) {
    string = stripAnsi(string);
  }
  if (string.length === 0) {
    return 0;
  }
  if (/^[\u0020-\u007E]*$/.test(string)) {
    return string.length;
  }
  let width = 0;
  const eastAsianWidthOptions = { ambiguousAsWide: !ambiguousIsNarrow };
  for (const { segment } of segmenter.segment(string)) {
    if (isZeroWidthCluster(segment)) {
      continue;
    }
    if (rgiEmojiRegex.test(segment) || isDoubleWidthNonRgiEmojiSequence(segment)) {
      width += 2;
      continue;
    }
    const visibleSegment = baseVisible(segment);
    const hangulWidth = hangulClusterWidth(visibleSegment, eastAsianWidthOptions);
    if (hangulWidth !== void 0) {
      width += hangulWidth;
      continue;
    }
    const codePoint = visibleSegment.codePointAt(0);
    width += eastAsianWidth(codePoint, eastAsianWidthOptions);
    width += trailingHalfwidthWidth(visibleSegment, eastAsianWidthOptions);
  }
  return width;
}
__name(stringWidth2, "stringWidth");

// packages/cli/node_modules/ansi-styles/index.js
init_esbuild_shims();
var ANSI_BACKGROUND_OFFSET = 10;
var wrapAnsi16 = /* @__PURE__ */ __name((offset = 0) => (code) => `\x1B[${code + offset}m`, "wrapAnsi16");
var wrapAnsi256 = /* @__PURE__ */ __name((offset = 0) => (code) => `\x1B[${38 + offset};5;${code}m`, "wrapAnsi256");
var wrapAnsi16m = /* @__PURE__ */ __name((offset = 0) => (red, green, blue) => `\x1B[${38 + offset};2;${red};${green};${blue}m`, "wrapAnsi16m");
var styles = {
  modifier: {
    reset: [0, 0],
    // 21 isn't widely supported and 22 does the same thing
    bold: [1, 22],
    dim: [2, 22],
    italic: [3, 23],
    underline: [4, 24],
    overline: [53, 55],
    inverse: [7, 27],
    hidden: [8, 28],
    strikethrough: [9, 29]
  },
  color: {
    black: [30, 39],
    red: [31, 39],
    green: [32, 39],
    yellow: [33, 39],
    blue: [34, 39],
    magenta: [35, 39],
    cyan: [36, 39],
    white: [37, 39],
    // Bright color
    blackBright: [90, 39],
    gray: [90, 39],
    // Alias of `blackBright`
    grey: [90, 39],
    // Alias of `blackBright`
    redBright: [91, 39],
    greenBright: [92, 39],
    yellowBright: [93, 39],
    blueBright: [94, 39],
    magentaBright: [95, 39],
    cyanBright: [96, 39],
    whiteBright: [97, 39]
  },
  bgColor: {
    bgBlack: [40, 49],
    bgRed: [41, 49],
    bgGreen: [42, 49],
    bgYellow: [43, 49],
    bgBlue: [44, 49],
    bgMagenta: [45, 49],
    bgCyan: [46, 49],
    bgWhite: [47, 49],
    // Bright color
    bgBlackBright: [100, 49],
    bgGray: [100, 49],
    // Alias of `bgBlackBright`
    bgGrey: [100, 49],
    // Alias of `bgBlackBright`
    bgRedBright: [101, 49],
    bgGreenBright: [102, 49],
    bgYellowBright: [103, 49],
    bgBlueBright: [104, 49],
    bgMagentaBright: [105, 49],
    bgCyanBright: [106, 49],
    bgWhiteBright: [107, 49]
  }
};
var modifierNames = Object.keys(styles.modifier);
var foregroundColorNames = Object.keys(styles.color);
var backgroundColorNames = Object.keys(styles.bgColor);
var colorNames = [...foregroundColorNames, ...backgroundColorNames];
function assembleStyles() {
  const codes = /* @__PURE__ */ new Map();
  for (const [groupName, group] of Object.entries(styles)) {
    for (const [styleName, style] of Object.entries(group)) {
      styles[styleName] = {
        open: `\x1B[${style[0]}m`,
        close: `\x1B[${style[1]}m`
      };
      group[styleName] = styles[styleName];
      codes.set(style[0], style[1]);
    }
    Object.defineProperty(styles, groupName, {
      value: group,
      enumerable: false
    });
  }
  Object.defineProperty(styles, "codes", {
    value: codes,
    enumerable: false
  });
  styles.color.close = "\x1B[39m";
  styles.bgColor.close = "\x1B[49m";
  styles.color.ansi = wrapAnsi16();
  styles.color.ansi256 = wrapAnsi256();
  styles.color.ansi16m = wrapAnsi16m();
  styles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);
  styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);
  styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);
  Object.defineProperties(styles, {
    rgbToAnsi256: {
      value(red, green, blue) {
        if (red === green && green === blue) {
          if (red < 8) {
            return 16;
          }
          if (red > 248) {
            return 231;
          }
          return Math.round((red - 8) / 247 * 24) + 232;
        }
        return 16 + 36 * Math.round(red / 255 * 5) + 6 * Math.round(green / 255 * 5) + Math.round(blue / 255 * 5);
      },
      enumerable: false
    },
    hexToRgb: {
      value(hex) {
        const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));
        if (!matches) {
          return [0, 0, 0];
        }
        let [colorString] = matches;
        if (colorString.length === 3) {
          colorString = [...colorString].map((character) => character + character).join("");
        }
        const integer = Number.parseInt(colorString, 16);
        return [
          /* eslint-disable no-bitwise */
          integer >> 16 & 255,
          integer >> 8 & 255,
          integer & 255
          /* eslint-enable no-bitwise */
        ];
      },
      enumerable: false
    },
    hexToAnsi256: {
      value: /* @__PURE__ */ __name((hex) => styles.rgbToAnsi256(...styles.hexToRgb(hex)), "value"),
      enumerable: false
    },
    ansi256ToAnsi: {
      value(code) {
        if (code < 8) {
          return 30 + code;
        }
        if (code < 16) {
          return 90 + (code - 8);
        }
        let red;
        let green;
        let blue;
        if (code >= 232) {
          red = ((code - 232) * 10 + 8) / 255;
          green = red;
          blue = red;
        } else {
          code -= 16;
          const remainder = code % 36;
          red = Math.floor(code / 36) / 5;
          green = Math.floor(remainder / 6) / 5;
          blue = remainder % 6 / 5;
        }
        const value = Math.max(red, green, blue) * 2;
        if (value === 0) {
          return 30;
        }
        let result = 30 + (Math.round(blue) << 2 | Math.round(green) << 1 | Math.round(red));
        if (value === 2) {
          result += 60;
        }
        return result;
      },
      enumerable: false
    },
    rgbToAnsi: {
      value: /* @__PURE__ */ __name((red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)), "value"),
      enumerable: false
    },
    hexToAnsi: {
      value: /* @__PURE__ */ __name((hex) => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)), "value"),
      enumerable: false
    }
  });
  return styles;
}
__name(assembleStyles, "assembleStyles");
var ansiStyles = assembleStyles();
var ansi_styles_default = ansiStyles;

// packages/cli/node_modules/wrap-ansi/index.js
var ANSI_ESCAPE = "\x1B";
var ANSI_ESCAPE_CSI = "\x9B";
var ESCAPES = /* @__PURE__ */ new Set([
  ANSI_ESCAPE,
  ANSI_ESCAPE_CSI
]);
var ANSI_ESCAPE_BELL = "\x07";
var ANSI_CSI = "[";
var ANSI_OSC = "]";
var ANSI_SGR_TERMINATOR = "m";
var ANSI_SGR_RESET = 0;
var ANSI_SGR_RESET_FOREGROUND = 39;
var ANSI_SGR_RESET_BACKGROUND = 49;
var ANSI_SGR_RESET_UNDERLINE_COLOR = 59;
var ANSI_SGR_FOREGROUND_EXTENDED = 38;
var ANSI_SGR_BACKGROUND_EXTENDED = 48;
var ANSI_SGR_UNDERLINE_COLOR_EXTENDED = 58;
var ANSI_SGR_COLOR_MODE_256 = 5;
var ANSI_SGR_COLOR_MODE_RGB = 2;
var ANSI_ESCAPE_LINK = `${ANSI_OSC}8;;`;
var ANSI_ESCAPE_REGEX = new RegExp(`^\\u001B(?:\\${ANSI_CSI}(?<sgr>[0-9;]*)${ANSI_SGR_TERMINATOR}|${ANSI_ESCAPE_LINK}(?<uri>[^\\u0007\\u001B]*)(?:\\u0007|\\u001B\\\\))`);
var ANSI_ESCAPE_CSI_REGEX = new RegExp(`^\\u009B(?<sgr>[0-9;]*)${ANSI_SGR_TERMINATOR}`);
var ANSI_SGR_MODIFIER_CLOSE_CODES = new Set(ansi_styles_default.codes.values());
ANSI_SGR_MODIFIER_CLOSE_CODES.delete(ANSI_SGR_RESET);
var segmenter2 = new Intl.Segmenter();
var getGraphemes = /* @__PURE__ */ __name((string) => Array.from(segmenter2.segment(string), ({ segment }) => segment), "getGraphemes");
var TAB_SIZE = 8;
var wrapAnsiCode = /* @__PURE__ */ __name((code) => `${ANSI_ESCAPE}${ANSI_CSI}${code}${ANSI_SGR_TERMINATOR}`, "wrapAnsiCode");
var wrapAnsiHyperlink = /* @__PURE__ */ __name((url) => `${ANSI_ESCAPE}${ANSI_ESCAPE_LINK}${url}${ANSI_ESCAPE_BELL}`, "wrapAnsiHyperlink");
var getSgrTokens = /* @__PURE__ */ __name((sgrParameters) => {
  const codes = sgrParameters.split(";").map((sgrParameter) => sgrParameter === "" ? ANSI_SGR_RESET : Number.parseInt(sgrParameter, 10));
  const sgrTokens = [];
  for (let index = 0; index < codes.length; index++) {
    const code = codes[index];
    if (!Number.isFinite(code)) {
      continue;
    }
    if (code === ANSI_SGR_FOREGROUND_EXTENDED || code === ANSI_SGR_BACKGROUND_EXTENDED || code === ANSI_SGR_UNDERLINE_COLOR_EXTENDED) {
      if (index + 1 >= codes.length) {
        break;
      }
      const mode = codes[index + 1];
      if (mode === ANSI_SGR_COLOR_MODE_256 && Number.isFinite(codes[index + 2])) {
        sgrTokens.push([code, mode, codes[index + 2]]);
        index += 2;
        continue;
      }
      const red = codes[index + 2];
      const green = codes[index + 3];
      const blue = codes[index + 4];
      if (mode === ANSI_SGR_COLOR_MODE_RGB && Number.isFinite(red) && Number.isFinite(green) && Number.isFinite(blue)) {
        sgrTokens.push([code, mode, red, green, blue]);
        index += 4;
        continue;
      }
      break;
    }
    sgrTokens.push([code]);
  }
  return sgrTokens;
}, "getSgrTokens");
var removeActiveStyle = /* @__PURE__ */ __name((activeStyles, family) => {
  const activeStyleIndex = activeStyles.findIndex((activeStyle) => activeStyle.family === family);
  if (activeStyleIndex !== -1) {
    activeStyles.splice(activeStyleIndex, 1);
  }
}, "removeActiveStyle");
var upsertActiveStyle = /* @__PURE__ */ __name((activeStyles, nextActiveStyle) => {
  removeActiveStyle(activeStyles, nextActiveStyle.family);
  activeStyles.push(nextActiveStyle);
}, "upsertActiveStyle");
var removeModifierStylesByClose = /* @__PURE__ */ __name((activeStyles, closeCode) => {
  for (let index = activeStyles.length - 1; index >= 0; index--) {
    const activeStyle = activeStyles[index];
    if (activeStyle.family.startsWith("modifier-") && activeStyle.close === closeCode) {
      activeStyles.splice(index, 1);
    }
  }
}, "removeModifierStylesByClose");
var getColorStyle = /* @__PURE__ */ __name((code, sgrToken) => {
  if (code >= 30 && code <= 37 || code >= 90 && code <= 97 || code === ANSI_SGR_FOREGROUND_EXTENDED && sgrToken.length > 1) {
    return {
      family: "foreground",
      open: sgrToken.join(";"),
      close: ANSI_SGR_RESET_FOREGROUND
    };
  }
  if (code >= 40 && code <= 47 || code >= 100 && code <= 107 || code === ANSI_SGR_BACKGROUND_EXTENDED && sgrToken.length > 1) {
    return {
      family: "background",
      open: sgrToken.join(";"),
      close: ANSI_SGR_RESET_BACKGROUND
    };
  }
  if (code === ANSI_SGR_UNDERLINE_COLOR_EXTENDED && sgrToken.length > 1) {
    return {
      family: "underlineColor",
      open: sgrToken.join(";"),
      close: ANSI_SGR_RESET_UNDERLINE_COLOR
    };
  }
}, "getColorStyle");
var applySgrResetCode = /* @__PURE__ */ __name((code, activeStyles) => {
  if (code === ANSI_SGR_RESET) {
    activeStyles.length = 0;
    return true;
  }
  if (code === ANSI_SGR_RESET_FOREGROUND) {
    removeActiveStyle(activeStyles, "foreground");
    return true;
  }
  if (code === ANSI_SGR_RESET_BACKGROUND) {
    removeActiveStyle(activeStyles, "background");
    return true;
  }
  if (code === ANSI_SGR_RESET_UNDERLINE_COLOR) {
    removeActiveStyle(activeStyles, "underlineColor");
    return true;
  }
  if (ANSI_SGR_MODIFIER_CLOSE_CODES.has(code)) {
    removeModifierStylesByClose(activeStyles, code);
    return true;
  }
  return false;
}, "applySgrResetCode");
var applySgrToken = /* @__PURE__ */ __name((sgrToken, activeStyles) => {
  const [code] = sgrToken;
  if (applySgrResetCode(code, activeStyles)) {
    return;
  }
  const colorStyle = getColorStyle(code, sgrToken);
  if (colorStyle) {
    upsertActiveStyle(activeStyles, colorStyle);
    return;
  }
  const close = ansi_styles_default.codes.get(code);
  if (close !== void 0 && close !== ANSI_SGR_RESET) {
    upsertActiveStyle(activeStyles, {
      family: `modifier-${code}`,
      open: sgrToken.join(";"),
      close
    });
  }
}, "applySgrToken");
var applySgrParameters = /* @__PURE__ */ __name((sgrParameters, activeStyles) => {
  for (const sgrToken of getSgrTokens(sgrParameters)) {
    applySgrToken(sgrToken, activeStyles);
  }
}, "applySgrParameters");
var applySgrResets = /* @__PURE__ */ __name((sgrParameters, activeStyles) => {
  for (const sgrToken of getSgrTokens(sgrParameters)) {
    const [code] = sgrToken;
    applySgrResetCode(code, activeStyles);
  }
}, "applySgrResets");
var applyLeadingSgrResets = /* @__PURE__ */ __name((string, activeStyles) => {
  let remainder = string;
  while (remainder.length > 0) {
    if (remainder.startsWith(ANSI_ESCAPE) && remainder[1] !== "\\") {
      const match = ANSI_ESCAPE_REGEX.exec(remainder);
      if (!match) {
        break;
      }
      if (match.groups.sgr !== void 0) {
        applySgrResets(match.groups.sgr, activeStyles);
      }
      remainder = remainder.slice(match[0].length);
      continue;
    }
    if (remainder.startsWith(ANSI_ESCAPE_CSI)) {
      const match = ANSI_ESCAPE_CSI_REGEX.exec(remainder);
      if (!match || match.groups.sgr === void 0) {
        break;
      }
      applySgrResets(match.groups.sgr, activeStyles);
      remainder = remainder.slice(match[0].length);
      continue;
    }
    break;
  }
}, "applyLeadingSgrResets");
var getClosingSgrSequence = /* @__PURE__ */ __name((activeStyles) => [...activeStyles].reverse().map((activeStyle) => wrapAnsiCode(activeStyle.close)).join(""), "getClosingSgrSequence");
var getOpeningSgrSequence = /* @__PURE__ */ __name((activeStyles) => activeStyles.map((activeStyle) => wrapAnsiCode(activeStyle.open)).join(""), "getOpeningSgrSequence");
var wordLengths = /* @__PURE__ */ __name((string) => string.split(" ").map((word) => stringWidth2(word)), "wordLengths");
var wrapWord = /* @__PURE__ */ __name((rows, word, columns) => {
  const characters = getGraphemes(word);
  let isInsideEscape = false;
  let isInsideLinkEscape = false;
  let visible = stringWidth2(stripAnsi(rows.at(-1)));
  for (const [index, character] of characters.entries()) {
    const characterLength = stringWidth2(character);
    if (visible + characterLength <= columns) {
      rows[rows.length - 1] += character;
    } else {
      rows.push(character);
      visible = 0;
    }
    if (ESCAPES.has(character) && !(isInsideLinkEscape && character === ANSI_ESCAPE && characters[index + 1] === "\\")) {
      isInsideEscape = true;
      const ansiEscapeLinkCandidate = characters.slice(index + 1, index + 1 + ANSI_ESCAPE_LINK.length).join("");
      isInsideLinkEscape = ansiEscapeLinkCandidate === ANSI_ESCAPE_LINK;
    }
    if (isInsideEscape) {
      if (isInsideLinkEscape) {
        if (character === ANSI_ESCAPE_BELL || character === "\\" && index > 0 && characters[index - 1] === ANSI_ESCAPE) {
          isInsideEscape = false;
          isInsideLinkEscape = false;
        }
      } else if (character === ANSI_SGR_TERMINATOR) {
        isInsideEscape = false;
      }
      continue;
    }
    visible += characterLength;
    if (visible === columns && index < characters.length - 1) {
      rows.push("");
      visible = 0;
    }
  }
  if (!visible && rows.at(-1).length > 0 && rows.length > 1) {
    rows[rows.length - 2] += rows.pop();
  }
}, "wrapWord");
var stringVisibleTrimSpacesRight = /* @__PURE__ */ __name((string) => {
  const words = string.split(" ");
  let last = words.length;
  while (last > 0) {
    if (stringWidth2(words[last - 1]) > 0) {
      break;
    }
    last--;
  }
  if (last === words.length) {
    return string;
  }
  return words.slice(0, last).join(" ") + words.slice(last).join("");
}, "stringVisibleTrimSpacesRight");
var expandTabs = /* @__PURE__ */ __name((line) => {
  if (!line.includes("	")) {
    return line;
  }
  const segments = line.split("	");
  let visible = 0;
  let expandedLine = "";
  for (const [index, segment] of segments.entries()) {
    expandedLine += segment;
    visible += stringWidth2(segment);
    if (index < segments.length - 1) {
      const spaces = TAB_SIZE - visible % TAB_SIZE;
      expandedLine += " ".repeat(spaces);
      visible += spaces;
    }
  }
  return expandedLine;
}, "expandTabs");
var exec = /* @__PURE__ */ __name((string, columns, options = {}) => {
  if (options.trim !== false && string.trim() === "") {
    return "";
  }
  let returnValue = "";
  let escapeUrl;
  const activeStyles = [];
  const lengths = wordLengths(string);
  let rows = [""];
  for (const [index, word] of string.split(" ").entries()) {
    if (options.trim !== false) {
      rows[rows.length - 1] = rows.at(-1).trimStart();
    }
    let rowLength = stringWidth2(rows.at(-1));
    if (index !== 0) {
      if (rowLength >= columns && (options.wordWrap === false || options.trim === false)) {
        rows.push("");
        rowLength = 0;
      }
      if (rowLength > 0 || options.trim === false) {
        rows[rows.length - 1] += " ";
        rowLength++;
      }
    }
    if (options.hard && options.wordWrap !== false && lengths[index] > columns) {
      const remainingColumns = columns - rowLength;
      const breaksStartingThisLine = 1 + Math.floor((lengths[index] - remainingColumns - 1) / columns);
      const breaksStartingNextLine = Math.floor((lengths[index] - 1) / columns);
      if (breaksStartingNextLine < breaksStartingThisLine) {
        rows.push("");
      }
      wrapWord(rows, word, columns);
      continue;
    }
    if (rowLength + lengths[index] > columns && rowLength > 0 && lengths[index] > 0) {
      if (options.wordWrap === false && rowLength < columns) {
        wrapWord(rows, word, columns);
        continue;
      }
      rows.push("");
    }
    if (rowLength + lengths[index] > columns && options.wordWrap === false) {
      wrapWord(rows, word, columns);
      continue;
    }
    rows[rows.length - 1] += word;
  }
  if (options.trim !== false) {
    rows = rows.map((row) => stringVisibleTrimSpacesRight(row));
  }
  const preString = rows.join("\n");
  const pre = getGraphemes(preString);
  let preStringIndex = 0;
  for (const [index, character] of pre.entries()) {
    returnValue += character;
    if (character === ANSI_ESCAPE && pre[index + 1] !== "\\") {
      const { groups } = ANSI_ESCAPE_REGEX.exec(preString.slice(preStringIndex)) || { groups: {} };
      if (groups.sgr !== void 0) {
        applySgrParameters(groups.sgr, activeStyles);
      } else if (groups.uri !== void 0) {
        escapeUrl = groups.uri.length === 0 ? void 0 : groups.uri;
      }
    } else if (character === ANSI_ESCAPE_CSI) {
      const { groups } = ANSI_ESCAPE_CSI_REGEX.exec(preString.slice(preStringIndex)) || { groups: {} };
      if (groups.sgr !== void 0) {
        applySgrParameters(groups.sgr, activeStyles);
      }
    }
    if (pre[index + 1] === "\n") {
      if (escapeUrl) {
        returnValue += wrapAnsiHyperlink("");
      }
      returnValue += getClosingSgrSequence(activeStyles);
    } else if (character === "\n") {
      const openingStyles = [...activeStyles];
      applyLeadingSgrResets(preString.slice(preStringIndex + 1), openingStyles);
      returnValue += getOpeningSgrSequence(openingStyles);
      if (escapeUrl) {
        returnValue += wrapAnsiHyperlink(escapeUrl);
      }
    }
    preStringIndex += character.length;
  }
  return returnValue;
}, "exec");
function wrapAnsi(string, columns, options) {
  return String(string).normalize().replaceAll("\r\n", "\n").split("\n").map((line) => exec(expandTabs(line), columns, options)).join("\n");
}
__name(wrapAnsi, "wrapAnsi");

// packages/cli/src/ui/utils/latexRenderer.ts
init_esbuild_shims();
var COMMAND_REPLACEMENTS = {
  "\\alpha": "\u03B1",
  "\\beta": "\u03B2",
  "\\gamma": "\u03B3",
  "\\delta": "\u03B4",
  "\\epsilon": "\u03B5",
  "\\varepsilon": "\u03B5",
  "\\theta": "\u03B8",
  "\\lambda": "\u03BB",
  "\\mu": "\u03BC",
  "\\pi": "\u03C0",
  "\\rho": "\u03C1",
  "\\sigma": "\u03C3",
  "\\tau": "\u03C4",
  "\\phi": "\u03C6",
  "\\varphi": "\u03C6",
  "\\omega": "\u03C9",
  "\\Gamma": "\u0393",
  "\\Delta": "\u0394",
  "\\Theta": "\u0398",
  "\\Lambda": "\u039B",
  "\\Pi": "\u03A0",
  "\\Sigma": "\u03A3",
  "\\Phi": "\u03A6",
  "\\Omega": "\u03A9",
  "\\sum": "\u03A3",
  "\\prod": "\u220F",
  "\\int": "\u222B",
  "\\infty": "\u221E",
  "\\partial": "\u2202",
  "\\sqrt": "\u221A",
  "\\times": "\xD7",
  "\\cdot": "\xB7",
  "\\pm": "\xB1",
  "\\leq": "\u2264",
  "\\geq": "\u2265",
  "\\neq": "\u2260",
  "\\approx": "\u2248",
  "\\rightarrow": "\u2192",
  "\\to": "\u2192",
  "\\leftarrow": "\u2190",
  "\\Rightarrow": "\u21D2",
  "\\Leftarrow": "\u21D0"
};
var COMMAND_REPLACEMENT_REGEX = new RegExp(
  Object.keys(COMMAND_REPLACEMENTS).sort((a, b) => b.length - a.length).map((command) => command.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|"),
  "g"
);
var MAX_RENDER_DEPTH = 10;
var SUPERSCRIPT = {
  "0": "\u2070",
  "1": "\xB9",
  "2": "\xB2",
  "3": "\xB3",
  "4": "\u2074",
  "5": "\u2075",
  "6": "\u2076",
  "7": "\u2077",
  "8": "\u2078",
  "9": "\u2079",
  "+": "\u207A",
  "-": "\u207B",
  "=": "\u207C",
  "(": "\u207D",
  ")": "\u207E",
  n: "\u207F",
  i: "\u2071"
};
var SUBSCRIPT = {
  "0": "\u2080",
  "1": "\u2081",
  "2": "\u2082",
  "3": "\u2083",
  "4": "\u2084",
  "5": "\u2085",
  "6": "\u2086",
  "7": "\u2087",
  "8": "\u2088",
  "9": "\u2089",
  "+": "\u208A",
  "-": "\u208B",
  "=": "\u208C",
  "(": "\u208D",
  ")": "\u208E",
  a: "\u2090",
  e: "\u2091",
  h: "\u2095",
  i: "\u1D62",
  j: "\u2C7C",
  k: "\u2096",
  l: "\u2097",
  m: "\u2098",
  n: "\u2099",
  o: "\u2092",
  p: "\u209A",
  r: "\u1D63",
  s: "\u209B",
  t: "\u209C",
  u: "\u1D64",
  v: "\u1D65",
  x: "\u2093"
};
function convertScript(value, map) {
  return [...value].map((char) => map[char] ?? char).join("");
}
__name(convertScript, "convertScript");
function findBalancedGroup(input, openBraceIndex) {
  if (input[openBraceIndex] !== "{") {
    return null;
  }
  let depth = 0;
  for (let index = openBraceIndex; index < input.length; index++) {
    const char = input[index];
    if (char === "\\") {
      index += 1;
      continue;
    }
    if (char === "{") {
      depth += 1;
      continue;
    }
    if (char !== "}") {
      continue;
    }
    depth -= 1;
    if (depth === 0) {
      return {
        value: input.slice(openBraceIndex + 1, index),
        end: index + 1
      };
    }
  }
  return null;
}
__name(findBalancedGroup, "findBalancedGroup");
function replaceBraceCommand(input, command, groupCount, render) {
  const marker = `\\${command}`;
  let output = "";
  let index = 0;
  while (index < input.length) {
    if (!input.startsWith(marker, index)) {
      output += input[index];
      index += 1;
      continue;
    }
    const groups = [];
    let cursor = index + marker.length;
    for (let groupIndex = 0; groupIndex < groupCount; groupIndex++) {
      const group = findBalancedGroup(input, cursor);
      if (!group) {
        groups.length = 0;
        break;
      }
      groups.push(group.value);
      cursor = group.end;
    }
    if (groups.length !== groupCount) {
      output += input[index];
      index += 1;
      continue;
    }
    output += render(groups);
    index = cursor;
  }
  return output;
}
__name(replaceBraceCommand, "replaceBraceCommand");
function renderInlineLatex(input, depth = 0) {
  let output = input.trim();
  if (depth > MAX_RENDER_DEPTH) {
    return output;
  }
  output = replaceBraceCommand(
    output,
    "frac",
    2,
    ([numerator, denominator]) => `${renderInlineLatex(numerator ?? "", depth + 1)}/${renderInlineLatex(
      denominator ?? "",
      depth + 1
    )}`
  );
  output = replaceBraceCommand(
    output,
    "sqrt",
    1,
    ([radicand]) => `\u221A(${renderInlineLatex(radicand ?? "", depth + 1)})`
  );
  output = output.replace(
    /\^\{([^{}]+)\}|\^([A-Za-z0-9+\-=()])/g,
    (_match, braced, single) => convertScript(braced ?? single ?? "", SUPERSCRIPT)
  );
  output = output.replace(
    /_\{([^{}]+)\}|_([A-Za-z0-9+\-=()])/g,
    (_match, braced, single) => convertScript(braced ?? single ?? "", SUBSCRIPT)
  );
  output = output.replace(
    COMMAND_REPLACEMENT_REGEX,
    (command) => COMMAND_REPLACEMENTS[command] ?? command
  );
  return output.replace(/\\(?:left|right)\./g, "").replace(/\\left|\\right/g, "").replace(/\\,/g, " ").replace(/\s+/g, " ").trim();
}
__name(renderInlineLatex, "renderInlineLatex");

// packages/cli/src/ui/utils/osc8.ts
init_esbuild_shims();
function sanitizeForOsc(s) {
  return s.replace(
    // eslint-disable-next-line no-control-regex
    /[\x00-\x1f\x7f\x80-\x9f\u200e\u200f\u202a-\u202e\u2066-\u2069\u2028\u2029]/g,
    ""
  );
}
__name(sanitizeForOsc, "sanitizeForOsc");
function osc8Hyperlink(url, label = url) {
  const safeUrl = sanitizeForOsc(url);
  const safeLabel = sanitizeForOsc(label);
  return wrapForMultiplexer(`\x1B]8;;${safeUrl}\x07${safeLabel}\x1B]8;;\x07`);
}
__name(osc8Hyperlink, "osc8Hyperlink");
function osc8Open(url) {
  return wrapForMultiplexer(`\x1B]8;;${sanitizeForOsc(url)}\x07`);
}
__name(osc8Open, "osc8Open");
function osc8Close() {
  return wrapForMultiplexer(`\x1B]8;;\x07`);
}
__name(osc8Close, "osc8Close");
var SAFE_OSC8_SCHEMES = /* @__PURE__ */ new Set([
  "http:",
  "https:",
  "mailto:",
  "ftp:",
  "ftps:",
  "sftp:",
  "ssh:"
]);
function isSafeOscScheme(url) {
  const match = url.match(/^([a-z][a-z0-9+.-]*:)/i);
  if (!match) return false;
  return SAFE_OSC8_SCHEMES.has(match[1].toLowerCase());
}
__name(isSafeOscScheme, "isSafeOscScheme");
function shouldForceHyperlinks(value) {
  if (value.length === 0) return true;
  const trimmed = value.trim();
  if (!/^[+-]?\d+$/.test(trimmed)) return false;
  return Number(trimmed) !== 0;
}
__name(shouldForceHyperlinks, "shouldForceHyperlinks");
function parseVersion(versionString) {
  if (!versionString) return { major: 0, minor: 0, patch: 0 };
  if (/^\d{3,4}$/.test(versionString)) {
    const m = /(\d{1,2})(\d{2})/.exec(versionString);
    return { major: 0, minor: parseInt(m[1], 10), patch: parseInt(m[2], 10) };
  }
  const parts = versionString.split(".").map((n) => parseInt(n, 10) || 0);
  return { major: parts[0] ?? 0, minor: parts[1] ?? 0, patch: parts[2] ?? 0 };
}
__name(parseVersion, "parseVersion");
function supportsHyperlinks(stream = process.stdout) {
  const env = process.env;
  if (env["QWEN_DISABLE_HYPERLINKS"] === "1") return false;
  if (env["NO_COLOR"] !== void 0 && env["NO_COLOR"] !== "") return false;
  if (env["FORCE_COLOR"] === "0" || env["FORCE_COLOR"] === "false") {
    return false;
  }
  if (!stream || !stream.isTTY) return false;
  const force = env["FORCE_HYPERLINK"];
  if (force !== void 0) {
    return shouldForceHyperlinks(force);
  }
  if (env["CI"]) return false;
  if (env["TEAMCITY_VERSION"]) return false;
  if (env["TMUX"] || env["STY"]) return false;
  if (env["WT_SESSION"]) return true;
  if (env["KITTY_WINDOW_ID"] || env["TERM"] === "xterm-kitty") return true;
  if (env["DOMTERM"]) return true;
  if (env["GHOSTTY_RESOURCES_DIR"] || env["TERM"] === "xterm-ghostty") {
    return true;
  }
  if (env["KONSOLE_VERSION"]) {
    const konsoleVersion = parseInt(env["KONSOLE_VERSION"], 10);
    if (Number.isFinite(konsoleVersion) && konsoleVersion >= 210400) {
      return true;
    }
  }
  if (env["TERM"] === "alacritty" || env["ALACRITTY_LOG"] !== void 0 || env["ALACRITTY_WINDOW_ID"] !== void 0 || env["ALACRITTY_SOCKET"] !== void 0) {
    return true;
  }
  if (env["TERMINAL_EMULATOR"] === "JetBrains-JediTerm") return true;
  if (env["TERM_PROGRAM"]) {
    const version = parseVersion(env["TERM_PROGRAM_VERSION"]);
    switch (env["TERM_PROGRAM"]) {
      case "iTerm.app":
        if (version.major === 3) return version.minor >= 1;
        return version.major > 3;
      case "WezTerm":
        return version.major >= 20200620;
      case "vscode":
        return version.major > 1 || version.major === 1 && version.minor >= 72;
      case "ghostty":
        return true;
      case "mintty":
        if (!env["TERM_PROGRAM_VERSION"]) return false;
        return version.major > 3 || version.major === 3 && version.minor >= 3;
      // Warp (TERM_PROGRAM=WarpTerminal) does NOT yet support OSC 8 — its
      // rendering engine ignores the envelope and prints visible garbage,
      // so we deliberately fall through to the legacy `label (url)` path.
      // Re-enable when Warp ships OSC 8 support.
      //
      // Hyper exposes OSC 8 in recent versions but plugin chains have a
      // history of breaking escape passthrough — gate on FORCE_HYPERLINK
      // so users who know their setup works can opt in explicitly.
      default:
        break;
    }
  }
  if (env["VTE_VERSION"]) {
    const version = parseVersion(env["VTE_VERSION"]);
    if (version.major === 0 && version.minor === 50 && version.patch === 0) {
      return false;
    }
    if (version.major > 0 || version.minor >= 50) return true;
    return false;
  }
  if (process.platform === "win32") return false;
  return false;
}
__name(supportsHyperlinks, "supportsHyperlinks");
function trimTrailingUrlPunctuation(url) {
  let openParen = 0;
  let openBracket = 0;
  let openBrace = 0;
  let closeParen = 0;
  let closeBracket = 0;
  let closeBrace = 0;
  for (let i = 0; i < url.length; i++) {
    const cc = url.charCodeAt(i);
    if (cc === 40) openParen++;
    else if (cc === 91) openBracket++;
    else if (cc === 123) openBrace++;
    else if (cc === 41) closeParen++;
    else if (cc === 93) closeBracket++;
    else if (cc === 125) closeBrace++;
  }
  let end = url.length;
  while (end > 0) {
    const c = url.charCodeAt(end - 1);
    if (c === 46 || c === 44 || c === 59 || c === 58 || c === 33 || c === 63 || c === 39 || c === 34 || c === 96 || c === 62) {
      end--;
      continue;
    }
    if (c === 41 && closeParen > openParen) {
      closeParen--;
      end--;
      continue;
    }
    if (c === 93 && closeBracket > openBracket) {
      closeBracket--;
      end--;
      continue;
    }
    if (c === 125 && closeBrace > openBrace) {
      closeBrace--;
      end--;
      continue;
    }
    break;
  }
  return url.slice(0, end);
}
__name(trimTrailingUrlPunctuation, "trimTrailingUrlPunctuation");
var MD_LINK_PATTERN = String.raw`\[.*?\]\((?:[^()]|\([^()]*\))*\)`;
var MD_LINK_CAPTURE = /^\[(.*?)\]\(((?:[^()]|\([^()]*\))*)\)$/;
function shouldWrapMarkdownLink(url, canHyperlink) {
  return canHyperlink && isSafeOscScheme(url) && !/\s/.test(url);
}
__name(shouldWrapMarkdownLink, "shouldWrapMarkdownLink");
var HOST_LIKE_RE = /\b[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?)*\.[a-z]{2,}\b/gi;
var IPV4_LIKE_RE = /\b(?:\d{1,3}\.){3}\d{1,3}\b/g;
function targetHostname(url) {
  try {
    const u = new URL(url);
    if (u.protocol === "mailto:") {
      const at = u.pathname.lastIndexOf("@");
      return at >= 0 ? u.pathname.slice(at + 1).toLowerCase() || void 0 : void 0;
    }
    return u.hostname.toLowerCase() || void 0;
  } catch {
    return void 0;
  }
}
__name(targetHostname, "targetHostname");
function labelMayDeceive(label, url) {
  if (label === url) return false;
  if (/:\/\//.test(label) || /^[a-z][a-z0-9+.-]*:/i.test(label.trim())) {
    return true;
  }
  const lower = label.toLowerCase();
  const labelHosts = [
    ...lower.match(HOST_LIKE_RE) ?? [],
    ...lower.match(IPV4_LIKE_RE) ?? []
  ];
  if (labelHosts.length === 0) return false;
  const target = targetHostname(url);
  if (!target) return true;
  return labelHosts.some((h) => h !== target);
}
__name(labelMayDeceive, "labelMayDeceive");

// packages/cli/src/ui/utils/TableRenderer.tsx
var import_jsx_runtime2 = __toESM(require_jsx_runtime(), 1);
var MIN_COLUMN_WIDTH = 3;
var MAX_ROW_LINES = 4;
var ABSOLUTE_MIN_HORIZONTAL_TABLE_WIDTH = 24;
var SAFETY_MARGIN = 4;
var INLINE_MATH_MAX_CHARS = 1024;
var INLINE_MATH_PATTERN = String.raw`(?<![\w$])\$(?![\s\d$])(?=[^$\n]{1,${INLINE_MATH_MAX_CHARS}}\S\$)[^$\n]{1,${INLINE_MATH_MAX_CHARS}}\$(?![\w$])`;
var INLINE_MARKDOWN_REGEX = new RegExp(
  String.raw`(\*\*.*?\*\*|\*.*?\*|_.*?_|~~.*?~~|${MD_LINK_PATTERN}|` + String.raw`\`+.+?\`+|<u>.*?<\/u>|https?:\/\/\S+)`,
  "g"
);
var INLINE_MARKDOWN_WITH_MATH_REGEX = new RegExp(
  String.raw`(\*\*.*?\*\*|\*.*?\*|_.*?_|~~.*?~~|${MD_LINK_PATTERN}|` + String.raw`\`+.+?\`+|${INLINE_MATH_PATTERN}|<u>.*?<\/u>|https?:\/\/\S+)`,
  "g"
);
var INK_COLOR_TO_ANSI = {
  black: 30,
  red: 31,
  green: 32,
  yellow: 33,
  blue: 34,
  magenta: 35,
  cyan: 36,
  white: 37,
  gray: 90,
  grey: 90,
  blackbright: 90,
  redbright: 91,
  greenbright: 92,
  yellowbright: 93,
  bluebright: 94,
  magentabright: 95,
  cyanbright: 96,
  whitebright: 97
};
var HEX_COLOR_RE = /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i;
var ESC = "\x1B";
function getColorCode(color) {
  if (!color) return "";
  if (color.startsWith("#")) {
    if (!HEX_COLOR_RE.test(color)) return "";
    const hex = color.length === 4 ? color[1] + color[1] + color[2] + color[2] + color[3] + color[3] : color.slice(1);
    const r = parseInt(hex.slice(0, 2), 16);
    const g = parseInt(hex.slice(2, 4), 16);
    const b = parseInt(hex.slice(4, 6), 16);
    return `\x1B[38;2;${r};${g};${b}m`;
  }
  const code = INK_COLOR_TO_ANSI[color.toLowerCase()];
  if (code !== void 0) return `\x1B[${code}m`;
  return "";
}
__name(getColorCode, "getColorCode");
function applyColor(text, color) {
  const code = getColorCode(color);
  if (!code) return text;
  return `${code}${text}\x1B[39m`;
}
__name(applyColor, "applyColor");
function recolorAfterResets(text, colorCode) {
  const fgReset = "\x1B[39m";
  const fullReset = "\x1B[0m";
  return text.split(fgReset).join(fgReset + colorCode).split(fullReset).join(fullReset + colorCode);
}
__name(recolorAfterResets, "recolorAfterResets");
function updateActiveForeground(activeForeground, paramsText) {
  const params = paramsText.length > 0 ? paramsText.split(";").map((param) => Number(param)) : [0];
  let foreground = activeForeground;
  for (let index = 0; index < params.length; index++) {
    const code = params[index];
    if (!Number.isFinite(code)) {
      continue;
    }
    if (code === 0 || code === 39) {
      foreground = "";
    } else if (code >= 30 && code <= 37 || code >= 90 && code <= 97) {
      foreground = `\x1B[${code}m`;
    } else if (code === 38) {
      const mode = params[index + 1];
      if (mode === 5 && Number.isFinite(params[index + 2])) {
        foreground = `\x1B[38;5;${params[index + 2]}m`;
        index += 2;
      } else if (mode === 2 && Number.isFinite(params[index + 2]) && Number.isFinite(params[index + 3]) && Number.isFinite(params[index + 4])) {
        foreground = `\x1B[38;2;${params[index + 2]};${params[index + 3]};${params[index + 4]}m`;
        index += 4;
      }
    }
  }
  return foreground;
}
__name(updateActiveForeground, "updateActiveForeground");
function readSgrSequence(text, index) {
  if (text[index] !== ESC || text[index + 1] !== "[") {
    return null;
  }
  const endIndex = text.indexOf("m", index + 2);
  if (endIndex === -1) {
    return null;
  }
  const paramsText = text.slice(index + 2, endIndex);
  if (!/^[0-9;]*$/.test(paramsText)) {
    return null;
  }
  return {
    sequence: text.slice(index, endIndex + 1),
    paramsText,
    endIndex
  };
}
__name(readSgrSequence, "readSgrSequence");
function preserveForegroundAcrossLineBreaks(text) {
  let activeForeground = "";
  let result = "";
  let lastIndex = 0;
  let index = 0;
  while (index < text.length) {
    const sgr = readSgrSequence(text, index);
    if (!sgr) {
      index += 1;
      continue;
    }
    const segment2 = text.slice(lastIndex, index);
    result += activeForeground ? segment2.replace(/\n/g, `\x1B[39m
${activeForeground}`) : segment2;
    result += sgr.sequence;
    activeForeground = updateActiveForeground(activeForeground, sgr.paramsText);
    index = sgr.endIndex + 1;
    lastIndex = index;
  }
  const segment = text.slice(lastIndex);
  result += activeForeground ? segment.replace(/\n/g, `\x1B[39m
${activeForeground}`) : segment;
  return result;
}
__name(preserveForegroundAcrossLineBreaks, "preserveForegroundAcrossLineBreaks");
var ansiFmt = {
  bold: /* @__PURE__ */ __name((t2) => `\x1B[1m${t2}\x1B[22m`, "bold"),
  italic: /* @__PURE__ */ __name((t2) => `\x1B[3m${t2}\x1B[23m`, "italic"),
  underline: /* @__PURE__ */ __name((t2) => `\x1B[4m${t2}\x1B[24m`, "underline"),
  strikethrough: /* @__PURE__ */ __name((t2) => `\x1B[9m${t2}\x1B[29m`, "strikethrough")
};
function renderMarkdownToAnsi(text, enableInlineMath = false) {
  const inlineRegex = enableInlineMath ? INLINE_MARKDOWN_WITH_MATH_REGEX : INLINE_MARKDOWN_REGEX;
  inlineRegex.lastIndex = 0;
  const canHyperlink = supportsHyperlinks();
  let result = "";
  let lastIndex = 0;
  let match;
  while ((match = inlineRegex.exec(text)) !== null) {
    result += text.slice(lastIndex, match.index);
    const fullMatch = match[0];
    let rendered = null;
    if (fullMatch.startsWith("**") && fullMatch.endsWith("**") && fullMatch.length > 4) {
      rendered = ansiFmt.bold(fullMatch.slice(2, -2));
    } else if (fullMatch.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)
    )) {
      rendered = ansiFmt.italic(fullMatch.slice(1, -1));
    } else if (fullMatch.startsWith("~~") && fullMatch.endsWith("~~") && fullMatch.length > 4) {
      rendered = ansiFmt.strikethrough(fullMatch.slice(2, -2));
    } else if (fullMatch.startsWith("`") && fullMatch.endsWith("`") && fullMatch.length > 1) {
      const codeMatch = fullMatch.match(/^(`+)(.+?)\1$/s);
      if (codeMatch?.[2]) {
        rendered = applyColor(codeMatch[2], theme.text.code);
      }
    } else if (fullMatch.startsWith("[") && fullMatch.includes("](") && fullMatch.endsWith(")")) {
      const linkMatch = fullMatch.match(MD_LINK_CAPTURE);
      if (linkMatch) {
        const labelText = linkMatch[1] ?? "";
        const url = linkMatch[2] ?? "";
        if (shouldWrapMarkdownLink(url, canHyperlink)) {
          const safeLabel = sanitizeForOsc(labelText);
          const safeUrl = sanitizeForOsc(url);
          const visibleLabel = applyColor(
            safeLabel || safeUrl,
            theme.text.link
          );
          const envelope = `${osc8Open(url)}${visibleLabel}${osc8Close()}`;
          rendered = labelMayDeceive(safeLabel, safeUrl) ? `${envelope} ${applyColor(`(${safeUrl})`, theme.text.link)}` : envelope;
        } else {
          rendered = `${labelText} ${applyColor(`(${url})`, theme.text.link)}`;
        }
      }
    } else if (enableInlineMath && fullMatch.startsWith("$") && fullMatch.endsWith("$") && fullMatch.length > 2) {
      rendered = applyColor(
        renderInlineLatex(fullMatch.slice(1, -1)),
        theme.text.accent
      );
    } else if (fullMatch.startsWith("<u>") && fullMatch.endsWith("</u>") && fullMatch.length > 7) {
      rendered = ansiFmt.underline(fullMatch.slice(3, -4));
    } else if (/^https?:\/\//.test(fullMatch)) {
      const visible = applyColor(fullMatch, theme.text.link);
      if (canHyperlink) {
        const trimmedUrl = trimTrailingUrlPunctuation(fullMatch);
        rendered = isSafeOscScheme(trimmedUrl) ? `${osc8Open(trimmedUrl)}${visible}${osc8Close()}` : visible;
      } else {
        rendered = visible;
      }
    }
    result += rendered ?? fullMatch;
    lastIndex = inlineRegex.lastIndex;
  }
  result += text.slice(lastIndex);
  return result;
}
__name(renderMarkdownToAnsi, "renderMarkdownToAnsi");
function padAligned(content, displayWidth, targetWidth, align) {
  const padding = Math.max(0, targetWidth - displayWidth);
  if (align === "center") {
    const leftPad = Math.floor(padding / 2);
    return " ".repeat(leftPad) + content + " ".repeat(padding - leftPad);
  }
  if (align === "right") {
    return " ".repeat(padding) + content;
  }
  return content + " ".repeat(padding);
}
__name(padAligned, "padAligned");
function wrapText(text, width, options) {
  if (width <= 0) return [text];
  const trimmedText = text.trimEnd();
  const wrapped = wrapAnsi(trimmedText, width, {
    hard: options?.hard ?? false,
    trim: false,
    wordWrap: true
  });
  const lines = preserveForegroundAcrossLineBreaks(wrapped).split("\n");
  while (lines.length > 1 && lines[lines.length - 1].length === 0) {
    lines.pop();
  }
  return lines.length > 0 ? lines : [""];
}
__name(wrapText, "wrapText");
var TableRenderer = /* @__PURE__ */ __name(({
  headers,
  rows,
  contentWidth,
  aligns,
  enableInlineMath = false
}) => {
  const colCount = headers.length;
  if (colCount === 0) {
    return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(Box_default, {});
  }
  const computeMetrics = /* @__PURE__ */ __name((text) => {
    const rendered = renderMarkdownToAnsi(text, enableInlineMath);
    const visible = stripAnsi(rendered);
    const words = visible.split(/\s+/).filter((w) => w.length > 0);
    return {
      rendered,
      renderedWidth: getCachedStringWidth(visible),
      minWordWidth: words.length > 0 ? Math.max(
        ...words.map((w) => getCachedStringWidth(w)),
        MIN_COLUMN_WIDTH
      ) : MIN_COLUMN_WIDTH
    };
  }, "computeMetrics");
  const headerMetrics = headers.map((h) => computeMetrics(h));
  const rowMetrics = rows.map(
    (row) => Array.from({ length: colCount }, (_, i) => computeMetrics(row[i] || ""))
  );
  const minColumnWidths = headers.map((_, colIndex) => {
    let maxMin = headerMetrics[colIndex].minWordWidth;
    for (const row of rowMetrics) {
      maxMin = Math.max(maxMin, row[colIndex].minWordWidth);
    }
    return maxMin;
  });
  const idealWidths = headers.map((_, colIndex) => {
    let maxIdeal = Math.max(
      headerMetrics[colIndex].renderedWidth,
      MIN_COLUMN_WIDTH
    );
    for (const row of rowMetrics) {
      maxIdeal = Math.max(maxIdeal, row[colIndex].renderedWidth);
    }
    return maxIdeal;
  });
  const borderOverhead = 1 + colCount * 3;
  const availableWidth = Math.max(
    contentWidth - borderOverhead - SAFETY_MARGIN,
    colCount * MIN_COLUMN_WIDTH
  );
  const totalMin = minColumnWidths.reduce((sum, w) => sum + w, 0);
  const totalIdeal = idealWidths.reduce((sum, w) => sum + w, 0);
  let needsHardWrap = false;
  let columnWidths;
  if (totalIdeal <= availableWidth) {
    columnWidths = idealWidths;
  } else if (totalMin <= availableWidth) {
    const extraSpace = availableWidth - totalMin;
    const overflows = idealWidths.map(
      (ideal, i) => ideal - minColumnWidths[i]
    );
    const totalOverflow = overflows.reduce((sum, o) => sum + o, 0);
    columnWidths = minColumnWidths.map((min, i) => {
      if (totalOverflow === 0) return min;
      const extra = Math.floor(overflows[i] / totalOverflow * extraSpace);
      return min + extra;
    });
  } else {
    needsHardWrap = true;
    const scaleFactor = availableWidth / totalMin;
    columnWidths = minColumnWidths.map(
      (w) => Math.max(Math.floor(w * scaleFactor), MIN_COLUMN_WIDTH)
    );
    let excess = columnWidths.reduce((s, w) => s + w, 0) - availableWidth;
    while (excess > 0) {
      const maxW = Math.max(...columnWidths);
      if (maxW <= MIN_COLUMN_WIDTH) break;
      const idx = columnWidths.indexOf(maxW);
      const reduction = Math.min(excess, maxW - MIN_COLUMN_WIDTH);
      columnWidths[idx] = maxW - reduction;
      excess -= reduction;
    }
  }
  function calculateMaxRowLines() {
    let maxLines = 1;
    for (let i = 0; i < colCount; i++) {
      const wrapped = wrapText(headerMetrics[i].rendered, columnWidths[i], {
        hard: needsHardWrap
      });
      maxLines = Math.max(maxLines, wrapped.length);
    }
    for (const row of rowMetrics) {
      for (let i = 0; i < colCount; i++) {
        const wrapped = wrapText(row[i].rendered, columnWidths[i], {
          hard: needsHardWrap
        });
        maxLines = Math.max(maxLines, wrapped.length);
      }
    }
    return maxLines;
  }
  __name(calculateMaxRowLines, "calculateMaxRowLines");
  const maxRowLines = calculateMaxRowLines();
  const minHorizontalTableWidth = Math.max(
    ABSOLUTE_MIN_HORIZONTAL_TABLE_WIDTH,
    colCount * MIN_COLUMN_WIDTH + borderOverhead + SAFETY_MARGIN
  );
  const useVerticalFormat = contentWidth < minHorizontalTableWidth || maxRowLines > MAX_ROW_LINES;
  const getAlign = /* @__PURE__ */ __name((colIndex) => aligns?.[colIndex] ?? "left", "getAlign");
  function renderBorderLine(type) {
    const [left, mid, cross, right] = {
      top: ["\u250C", "\u2500", "\u252C", "\u2510"],
      middle: ["\u251C", "\u2500", "\u253C", "\u2524"],
      bottom: ["\u2514", "\u2500", "\u2534", "\u2518"]
    }[type];
    let line = left;
    columnWidths.forEach((width, colIndex) => {
      line += mid.repeat(width + 2);
      line += colIndex < columnWidths.length - 1 ? cross : right;
    });
    return applyColor(line, theme.border.default);
  }
  __name(renderBorderLine, "renderBorderLine");
  function renderRowLines(renderedCells, isHeader) {
    const cellLines = renderedCells.map(
      (cell, colIndex) => wrapText(cell, columnWidths[colIndex], { hard: needsHardWrap })
    );
    const maxLines = Math.max(...cellLines.map((l) => l.length), 1);
    const offsets = cellLines.map((l) => Math.floor((maxLines - l.length) / 2));
    const borderPipe = applyColor("\u2502", theme.border.default);
    const result = [];
    for (let lineIdx = 0; lineIdx < maxLines; lineIdx++) {
      let line = borderPipe;
      for (let colIndex = 0; colIndex < colCount; colIndex++) {
        const lines = cellLines[colIndex];
        const offset = offsets[colIndex];
        const contentLineIdx = lineIdx - offset;
        const lineText = contentLineIdx >= 0 && contentLineIdx < lines.length ? lines[contentLineIdx] : "";
        const width = columnWidths[colIndex];
        const displayWidth = getCachedStringWidth(stripAnsi(lineText));
        const align = aligns?.[colIndex] != null ? getAlign(colIndex) : isHeader ? "center" : "left";
        const padded = padAligned(lineText, displayWidth, width, align);
        if (isHeader) {
          const linkCode = getColorCode(theme.text.link);
          const recolored = linkCode ? recolorAfterResets(padded, linkCode) : padded;
          const styledPadded = applyColor(
            ansiFmt.bold(recolored),
            theme.text.link
          );
          line += " " + styledPadded + " " + borderPipe;
        } else {
          const primaryCode = getColorCode(theme.text.primary);
          const recolored = primaryCode ? recolorAfterResets(padded, primaryCode) : padded;
          const styledCell = primaryCode ? applyColor(recolored, theme.text.primary) : recolored;
          line += " " + styledCell + " " + borderPipe;
        }
      }
      result.push(line);
    }
    return result;
  }
  __name(renderRowLines, "renderRowLines");
  function renderVerticalFormat() {
    const lines = [];
    const separatorWidth = Math.max(Math.min(contentWidth - 1, 40), 0);
    const separator = separatorWidth > 0 ? "\u2500".repeat(separatorWidth) : "";
    rowMetrics.forEach((row, rowIndex) => {
      if (rowIndex > 0) {
        lines.push(separator);
      }
      for (let colIndex = 0; colIndex < colCount; colIndex++) {
        const rawLabel = headers[colIndex] ?? `Column ${colIndex + 1}`;
        const label = renderMarkdownToAnsi(rawLabel, enableInlineMath);
        const value = row[colIndex].rendered.trim().replace(/\n+/g, " ").replace(/\s+/g, " ").trim();
        const linkCode = getColorCode(theme.text.link);
        const recoloredLabel = linkCode ? recolorAfterResets(`${label}:`, linkCode) : `${label}:`;
        const primaryCode = getColorCode(theme.text.primary);
        const styledValue = primaryCode ? applyColor(
          recolorAfterResets(value, primaryCode),
          theme.text.primary
        ) : value;
        lines.push(
          `${applyColor(ansiFmt.bold(recoloredLabel), theme.text.link)} ${styledValue}`
        );
      }
    });
    return lines.join("\n");
  }
  __name(renderVerticalFormat, "renderVerticalFormat");
  if (useVerticalFormat) {
    return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(Box_default, { marginY: 1, children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(Text, { children: renderVerticalFormat() }) });
  }
  const headerRendered = headerMetrics.map((m) => m.rendered);
  const tableLines = [];
  tableLines.push(renderBorderLine("top"));
  tableLines.push(...renderRowLines(headerRendered, true));
  tableLines.push(renderBorderLine("middle"));
  rowMetrics.forEach((row, rowIndex) => {
    tableLines.push(
      ...renderRowLines(
        row.map((m) => m.rendered),
        false
      )
    );
    if (rowIndex < rows.length - 1) {
      tableLines.push(renderBorderLine("middle"));
    }
  });
  tableLines.push(renderBorderLine("bottom"));
  const maxLineWidth = Math.max(
    ...tableLines.map((line) => getCachedStringWidth(stripAnsi(line)))
  );
  if (maxLineWidth > contentWidth - SAFETY_MARGIN) {
    return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(Box_default, { marginY: 1, children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(Text, { children: renderVerticalFormat() }) });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(Box_default, { flexDirection: "column", marginY: 1, children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(Text, { children: tableLines.join("\n") }) });
}, "TableRenderer");

// packages/cli/src/ui/utils/InlineMarkdownRenderer.tsx
init_esbuild_shims();
var import_react5 = __toESM(require_react(), 1);
var import_jsx_runtime3 = __toESM(require_jsx_runtime(), 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 INLINE_MATH_MARKER_LENGTH = 1;
var INLINE_MATH_MAX_CHARS2 = 1024;
var INLINE_MATH_PATTERN2 = new RegExp(
  String.raw`(?<![\w$])\$(?![\s\d$])(?=[^$\n]{1,${INLINE_MATH_MAX_CHARS2}}\S\$)[^$\n]{1,${INLINE_MATH_MAX_CHARS2}}\$(?![\w$])`,
  "g"
);
var INLINE_MARKDOWN_REGEX2 = new RegExp(
  String.raw`(\*\*.*?\*\*|\*.*?\*|_.*?_|~~.*?~~|${MD_LINK_PATTERN}|` + String.raw`\`+.+?\`+|<u>.*?<\/u>|https?:\/\/\S+)`,
  "g"
);
var INLINE_MARKDOWN_WITH_MATH_REGEX2 = new RegExp(
  String.raw`(\*\*.*?\*\*|\*.*?\*|_.*?_|~~.*?~~|${MD_LINK_PATTERN}|` + String.raw`\`+.+?\`+|(?<![\w$])\$(?![\s\d$])(?=[^$\n]{1,${INLINE_MATH_MAX_CHARS2}}\S\$)[^$\n]{1,${INLINE_MATH_MAX_CHARS2}}\$(?![\w$])|<u>.*?<\/u>|https?:\/\/\S+)`,
  "g"
);
var debugLogger2 = createDebugLogger("INLINE_MARKDOWN");
var RenderInlineInternal = /* @__PURE__ */ __name(({
  text,
  textColor = theme.text.primary,
  enableInlineMath = false
}) => {
  if (!/[*_~`<[]|https?:/.test(text) && !(enableInlineMath && text.includes("$"))) {
    return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(Text, { color: textColor, children: text });
  }
  const nodes = [];
  let lastIndex = 0;
  const canHyperlink = supportsHyperlinks();
  const inlineRegex = enableInlineMath ? INLINE_MARKDOWN_WITH_MATH_REGEX2 : INLINE_MARKDOWN_REGEX2;
  inlineRegex.lastIndex = 0;
  let match;
  while ((match = inlineRegex.exec(text)) !== null) {
    if (match.index > lastIndex) {
      nodes.push(
        /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(Text, { children: text.slice(lastIndex, match.index) }, `t-${lastIndex}`)
      );
    }
    const fullMatch = match[0];
    let renderedNode = null;
    const key = `m-${match.index}`;
    try {
      if (fullMatch.startsWith("**") && fullMatch.endsWith("**") && fullMatch.length > BOLD_MARKER_LENGTH * 2) {
        renderedNode = /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(Text, { bold: true, children: fullMatch.slice(BOLD_MARKER_LENGTH, -BOLD_MARKER_LENGTH) }, key);
      } 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)
      )) {
        renderedNode = /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(Text, { italic: true, children: fullMatch.slice(ITALIC_MARKER_LENGTH, -ITALIC_MARKER_LENGTH) }, key);
      } else if (fullMatch.startsWith("~~") && fullMatch.endsWith("~~") && fullMatch.length > STRIKETHROUGH_MARKER_LENGTH * 2) {
        renderedNode = /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(Text, { strikethrough: true, children: fullMatch.slice(
          STRIKETHROUGH_MARKER_LENGTH,
          -STRIKETHROUGH_MARKER_LENGTH
        ) }, key);
      } else if (fullMatch.startsWith("`") && fullMatch.endsWith("`") && fullMatch.length > INLINE_CODE_MARKER_LENGTH) {
        const codeMatch = fullMatch.match(/^(`+)(.+?)\1$/s);
        if (codeMatch && codeMatch[2]) {
          renderedNode = /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(Text, { color: theme.text.code, children: codeMatch[2] }, key);
        }
      } else if (fullMatch.startsWith("[") && fullMatch.includes("](") && fullMatch.endsWith(")")) {
        const linkMatch = fullMatch.match(MD_LINK_CAPTURE);
        if (linkMatch) {
          const linkText = linkMatch[1] ?? "";
          const url = linkMatch[2] ?? "";
          const wrapOsc8 = shouldWrapMarkdownLink(url, canHyperlink);
          const safeLabel = wrapOsc8 ? sanitizeForOsc(linkText) : linkText;
          const safeUrl = wrapOsc8 ? sanitizeForOsc(url) : url;
          const showUrlSuffix = wrapOsc8 && labelMayDeceive(safeLabel, safeUrl);
          renderedNode = wrapOsc8 ? /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(Text, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(Text, { color: theme.text.link, children: [
              osc8Open(url),
              safeLabel || safeUrl,
              osc8Close()
            ] }),
            showUrlSuffix ? /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(Text, { color: theme.text.link, children: [
              " (",
              safeUrl,
              ")"
            ] }) : null
          ] }, key) : /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(Text, { children: [
            linkText,
            /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(Text, { color: theme.text.link, children: [
              " (",
              url,
              ")"
            ] })
          ] }, key);
        }
      } else if (fullMatch.startsWith("<u>") && fullMatch.endsWith("</u>") && fullMatch.length > UNDERLINE_TAG_START_LENGTH + UNDERLINE_TAG_END_LENGTH - 1) {
        renderedNode = /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(Text, { underline: true, children: fullMatch.slice(
          UNDERLINE_TAG_START_LENGTH,
          -UNDERLINE_TAG_END_LENGTH
        ) }, key);
      } else if (enableInlineMath && fullMatch.startsWith("$") && fullMatch.endsWith("$") && fullMatch.length > INLINE_MATH_MARKER_LENGTH * 2) {
        renderedNode = /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(Text, { color: theme.text.accent, children: renderInlineLatex(
          fullMatch.slice(
            INLINE_MATH_MARKER_LENGTH,
            -INLINE_MATH_MARKER_LENGTH
          )
        ) }, key);
      } else if (fullMatch.match(/^https?:\/\//)) {
        const trimmedUrl = canHyperlink ? trimTrailingUrlPunctuation(fullMatch) : fullMatch;
        const wrapOsc8 = canHyperlink && isSafeOscScheme(trimmedUrl);
        renderedNode = /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(Text, { color: theme.text.link, children: [
          wrapOsc8 ? osc8Open(trimmedUrl) : null,
          fullMatch,
          wrapOsc8 ? osc8Close() : null
        ] }, key);
      }
    } catch (e) {
      debugLogger2.error("Error parsing inline markdown part:", fullMatch, e);
      renderedNode = null;
    }
    nodes.push(renderedNode ?? /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(Text, { children: fullMatch }, key));
    lastIndex = inlineRegex.lastIndex;
  }
  if (lastIndex < text.length) {
    nodes.push(/* @__PURE__ */ (0, import_jsx_runtime3.jsx)(Text, { children: text.slice(lastIndex) }, `t-${lastIndex}`));
  }
  return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(import_jsx_runtime3.Fragment, { children: nodes.filter((node) => node !== null) });
}, "RenderInlineInternal");
var RenderInline = import_react5.default.memo(RenderInlineInternal);

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

// packages/cli/src/ui/utils/mermaidVisualRenderer.ts
init_esbuild_shims();
var FLOW_START_RE = /^(?:flowchart|graph)\s+([A-Za-z]{2})/i;
var SEQUENCE_START_RE = /^sequenceDiagram\b/i;
var CLASS_START_RE = /^classDiagram(?:-v2)?\b/i;
var STATE_START_RE = /^stateDiagram(?:-v2)?\b/i;
var ER_START_RE = /^erDiagram\b/i;
var GANTT_START_RE = /^gantt\b/i;
var PIE_START_RE = /^pie\b/i;
var JOURNEY_START_RE = /^journey\b/i;
var GIT_GRAPH_START_RE = /^gitGraph\b/i;
var MINDMAP_START_RE = /^mindmap\b/i;
var REQUIREMENT_START_RE = /^requirementDiagram\b/i;
var LINE_COMMENT_RE = /^%%/;
var FLOW_ARROW_OPERATOR = String.fromCharCode(45, 45, 62);
var MAX_RENDERED_LINES = 80;
var MAX_FLOWCHART_PREVIEW_LINES = 120;
var MAX_FLOWCHART_PREVIEW_EDGES = 80;
var MAX_SEQUENCE_PREVIEW_LINES = 160;
var MAX_SEQUENCE_PREVIEW_MESSAGES = 80;
var MAX_GENERIC_PREVIEW_LINES = 80;
var MAX_SOURCE_FALLBACK_LINES = 80;
var MAX_PREVIEW_SOURCE_LINE_LENGTH = 1e3;
var MIN_CANVAS_WIDTH = 24;
var NODE_GAP_X = 4;
var NODE_GAP_Y = 4;
var FLOW_EDGE_OPERATOR_RE = new RegExp(
  String.raw`\s*(?:` + `${escapeRegExp(FLOW_ARROW_OPERATOR)}\\|([^|]+)\\|` + String.raw`|--\s+(.+?)\s+` + escapeRegExp(FLOW_ARROW_OPERATOR) + `|(?:${[FLOW_ARROW_OPERATOR, "---", "==>", "-.->", "--x", "--o"].map(escapeRegExp).join("|")}))` + String.raw`\s*`,
  "g"
);
function escapeRegExp(text) {
  return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
__name(escapeRegExp, "escapeRegExp");
function truncateToWidth(text, width) {
  if (width <= 0 || stringWidth(text) <= width) return text;
  let result = "";
  for (const char of text) {
    if (stringWidth(result + char + "\u2026") > width) break;
    result += char;
  }
  return result + "\u2026";
}
__name(truncateToWidth, "truncateToWidth");
function center(text, width) {
  const padding = Math.max(0, width - stringWidth(text));
  const left = Math.floor(padding / 2);
  return " ".repeat(left) + text + " ".repeat(padding - left);
}
__name(center, "center");
function sanitizeTerminalText(text) {
  let result = "";
  for (const char of stripAnsi(text)) {
    const code = char.charCodeAt(0);
    if (code <= 31 && code !== 10 || code === 127 || code >= 128 && code <= 159) {
      continue;
    }
    result += char;
  }
  return result;
}
__name(sanitizeTerminalText, "sanitizeTerminalText");
function stripMermaidPunctuation(text) {
  return sanitizeTerminalText(text).trim().replace(/[;,]+$/g, "").trim();
}
__name(stripMermaidPunctuation, "stripMermaidPunctuation");
function normalizePreviewLine(line) {
  const trimmed = sanitizeTerminalText(line).trim();
  return trimmed.length > MAX_PREVIEW_SOURCE_LINE_LENGTH ? trimmed.slice(0, MAX_PREVIEW_SOURCE_LINE_LENGTH) : trimmed;
}
__name(normalizePreviewLine, "normalizePreviewLine");
function sanitizePreviewSourceLine(line) {
  const sanitized = sanitizeTerminalText(line);
  return sanitized.length > MAX_PREVIEW_SOURCE_LINE_LENGTH ? sanitized.slice(0, MAX_PREVIEW_SOURCE_LINE_LENGTH) : sanitized;
}
__name(sanitizePreviewSourceLine, "sanitizePreviewSourceLine");
function normalizeNodeLabel(label) {
  return sanitizeTerminalText(label).replace(/^["']|["']$/g, "").replace(/<br\s*\/?>/gi, "\n").replace(/\\n/g, "\n");
}
__name(normalizeNodeLabel, "normalizeNodeLabel");
function nodeLabelLines(label) {
  return label.split(/\n/).map((line) => line.trim()).filter((line) => line.length > 0);
}
__name(nodeLabelLines, "nodeLabelLines");
function singleLineLabel(label) {
  return nodeLabelLines(label).join(" ");
}
__name(singleLineLabel, "singleLineLabel");
function previewSourceFallback(source, contentWidth, type, warning) {
  const allSourceLines = sanitizeTerminalText(source).trim().split(/\r?\n/).map(sanitizePreviewSourceLine);
  const sourceLines = allSourceLines.slice(0, MAX_SOURCE_FALLBACK_LINES);
  const truncated = allSourceLines.length > sourceLines.length;
  const lines = ["```mermaid", ...sourceLines, "```"].map(
    (line) => truncateToWidth(line, contentWidth)
  );
  return {
    title: `Mermaid source (${type})`,
    lines,
    warning: [
      warning ?? "Visual preview is not available; showing source so it remains readable and copyable.",
      truncated ? `Source truncated to ${MAX_SOURCE_FALLBACK_LINES} lines.` : void 0
    ].filter(Boolean).join(" ") || void 0
  };
}
__name(previewSourceFallback, "previewSourceFallback");
function diagramLines(source, startRe, maxLines = MAX_GENERIC_PREVIEW_LINES) {
  const allLines = source.split(/\r?\n/).map(normalizePreviewLine).filter(
    (line) => line.length > 0 && !LINE_COMMENT_RE.test(line) && !startRe.test(line)
  );
  return {
    lines: allLines.slice(0, maxLines),
    truncated: allLines.length > maxLines
  };
}
__name(diagramLines, "diagramLines");
function budgetWarning(truncated, maxLines = MAX_GENERIC_PREVIEW_LINES) {
  return truncated ? `Preview limited to ${maxLines} source lines.` : void 0;
}
__name(budgetWarning, "budgetWarning");
function parseNodeToken(rawToken) {
  const token = stripMermaidPunctuation(rawToken).replace(/^\|.*?\|/, "").trim();
  if (!token || /^subgraph\b|^end$/i.test(token)) return null;
  const idMatch = /^([A-Za-z0-9_.$:-]+)\s*(.*)$/.exec(token);
  if (!idMatch) {
    return {
      id: token,
      label: normalizeNodeLabel(token),
      shape: "rect"
    };
  }
  const id = idMatch[1];
  const rest = idMatch[2].trim();
  const labelMatch = /^\[\[(.+)\]\]$/.exec(rest) ?? /^\[(.+)\]$/.exec(rest) ?? /^\(\((.+)\)\)$/.exec(rest) ?? /^\((.+)\)$/.exec(rest) ?? /^\{(.+)\}$/.exec(rest) ?? /^>\s*(.+)\]$/.exec(rest);
  const shape = /^\{(.+)\}$/.test(rest) ? "diamond" : /^\(\((.+)\)\)$/.test(rest) || /^\((.+)\)$/.test(rest) ? "round" : "rect";
  return {
    id,
    label: normalizeNodeLabel(labelMatch?.[1] ?? id),
    shape
  };
}
__name(parseNodeToken, "parseNodeToken");
function parseFlowEdge(line) {
  const patterns = [
    {
      re: /^(.+?)\s*--\s*(.+?)\s*-->\s*(.+)$/i,
      fromIndex: 1,
      labelIndex: 2,
      toIndex: 3
    },
    {
      re: /^(.+?)\s*-->\|(.+?)\|\s*(.+)$/i,
      fromIndex: 1,
      labelIndex: 2,
      toIndex: 3
    },
    {
      re: /^(.+?)\s*(?:-->|---|==>|-\.->|--x|--o)\s*(.+)$/i,
      fromIndex: 1,
      toIndex: 2
    }
  ];
  for (const pattern of patterns) {
    const match = pattern.re.exec(line);
    if (!match) continue;
    const from = parseNodeToken(match[pattern.fromIndex]);
    const to = parseNodeToken(match[pattern.toIndex]);
    if (!from || !to) return null;
    const label = pattern.labelIndex !== void 0 ? stripMermaidPunctuation(match[pattern.labelIndex]) : void 0;
    return { from, to, label: label || void 0 };
  }
  return null;
}
__name(parseFlowEdge, "parseFlowEdge");
function parseFlowEdges(line) {
  const singleEdge = parseFlowEdge(line);
  const operators = [...line.matchAll(FLOW_EDGE_OPERATOR_RE)];
  if (operators.length <= 1) return singleEdge ? [singleEdge] : [];
  const tokens = [];
  const labels = [];
  let cursor = 0;
  for (const operator of operators) {
    tokens.push(line.slice(cursor, operator.index).trim());
    labels.push(
      stripMermaidPunctuation(operator[1] ?? operator[2] ?? "") || void 0
    );
    cursor = operator.index + operator[0].length;
  }
  tokens.push(line.slice(cursor).trim());
  if (tokens.length !== operators.length + 1) {
    return [];
  }
  const nodes = tokens.map(parseNodeToken);
  if (nodes.some((node) => node === null)) {
    return [];
  }
  const edges = [];
  for (let index = 0; index < nodes.length - 1; index++) {
    edges.push({
      from: nodes[index],
      to: nodes[index + 1],
      label: labels[index]
    });
  }
  return edges;
}
__name(parseFlowEdges, "parseFlowEdges");
function normalizeFlowNodeLabels(edges) {
  const labelById = /* @__PURE__ */ new Map();
  const shapeById = /* @__PURE__ */ new Map();
  for (const edge of edges) {
    for (const node of [edge.from, edge.to]) {
      if (node.label !== node.id && !labelById.has(node.id)) {
        labelById.set(node.id, node.label);
      }
      if (node.shape !== "rect" && !shapeById.has(node.id)) {
        shapeById.set(node.id, node.shape);
      }
    }
  }
  return edges.map((edge) => ({
    ...edge,
    from: {
      ...edge.from,
      label: labelById.get(edge.from.id) ?? edge.from.label,
      shape: shapeById.get(edge.from.id) ?? edge.from.shape
    },
    to: {
      ...edge.to,
      label: labelById.get(edge.to.id) ?? edge.to.label,
      shape: shapeById.get(edge.to.id) ?? edge.to.shape
    }
  }));
}
__name(normalizeFlowNodeLabels, "normalizeFlowNodeLabels");
function boxNode(node, width) {
  const labels = nodeLabelLines(node.label).map(
    (line) => truncateToWidth(line, Math.max(3, width - 4))
  );
  const innerWidth = Math.max(4, ...labels.map((label) => stringWidth(label)));
  if (node.shape === "diamond") {
    return [
      ` \u2571${"\u2500".repeat(innerWidth + 2)}\u2572 `,
      ...labels.map((label) => ` \u25C7 ${center(label, innerWidth)} \u25C7 `),
      ` \u2572${"\u2500".repeat(innerWidth + 2)}\u2571 `
    ];
  }
  if (node.shape === "round") {
    return [
      `\u256D${"\u2500".repeat(innerWidth + 2)}\u256E`,
      ...labels.map((label) => `\u2502 ${center(label, innerWidth)} \u2502`),
      `\u2570${"\u2500".repeat(innerWidth + 2)}\u256F`
    ];
  }
  return [
    `\u250C${"\u2500".repeat(innerWidth + 2)}\u2510`,
    ...labels.map((label) => `\u2502 ${center(label, innerWidth)} \u2502`),
    `\u2514${"\u2500".repeat(innerWidth + 2)}\u2518`
  ];
}
__name(boxNode, "boxNode");
function buildFlowGraph(edges) {
  const nodes = /* @__PURE__ */ new Map();
  const outgoing = /* @__PURE__ */ new Map();
  const incomingCount = /* @__PURE__ */ new Map();
  for (const edge of edges) {
    nodes.set(edge.from.id, edge.from);
    nodes.set(edge.to.id, edge.to);
    const outgoingEdges = outgoing.get(edge.from.id) ?? [];
    outgoingEdges.push(edge);
    outgoing.set(edge.from.id, outgoingEdges);
    incomingCount.set(edge.to.id, (incomingCount.get(edge.to.id) ?? 0) + 1);
    if (!incomingCount.has(edge.from.id)) incomingCount.set(edge.from.id, 0);
  }
  const roots = Array.from(nodes.values()).filter(
    (node) => (incomingCount.get(node.id) ?? 0) === 0
  );
  return {
    nodes,
    outgoing,
    incomingCount,
    roots: roots.length > 0 ? roots : [edges[0].from]
  };
}
__name(buildFlowGraph, "buildFlowGraph");
function renderNodeLines(node, maxWidth) {
  return boxNode(node, Math.max(8, maxWidth));
}
__name(renderNodeLines, "renderNodeLines");
function lineWidth(line) {
  return stringWidth(line);
}
__name(lineWidth, "lineWidth");
function computeRanks(graph) {
  const ranks = /* @__PURE__ */ new Map();
  const queue = [...graph.roots];
  for (const root of graph.roots) {
    ranks.set(root.id, 0);
  }
  while (queue.length > 0) {
    const node = queue.shift();
    const rank = ranks.get(node.id) ?? 0;
    for (const edge of graph.outgoing.get(node.id) ?? []) {
      if (ranks.has(edge.to.id)) continue;
      ranks.set(edge.to.id, rank + 1);
      queue.push(edge.to);
    }
  }
  for (const node of graph.nodes.values()) {
    if (!ranks.has(node.id)) ranks.set(node.id, 0);
  }
  return ranks;
}
__name(computeRanks, "computeRanks");
function branchPreference(label) {
  if (!label) return 0;
  const normalized = label.trim().toLowerCase();
  if (/^(no|false|fail|failed|否|不|失败)$/.test(normalized)) return -1;
  if (/^(yes|true|pass|passed|是|成功)$/.test(normalized)) return 1;
  return 0;
}
__name(branchPreference, "branchPreference");
function groupNodesByRank(graph, ranks) {
  const layers = [];
  const preferenceById = /* @__PURE__ */ new Map();
  const parentEdgesById = /* @__PURE__ */ new Map();
  const originalIndexById = /* @__PURE__ */ new Map();
  Array.from(graph.nodes.values()).forEach((node, index) => {
    originalIndexById.set(node.id, index);
  });
  for (const edgeList of graph.outgoing.values()) {
    for (const edge of edgeList) {
      const parentEdges = parentEdgesById.get(edge.to.id) ?? [];
      parentEdges.push(edge);
      parentEdgesById.set(edge.to.id, parentEdges);
      const preference = branchPreference(edge.label);
      if (preference !== 0 && !preferenceById.has(edge.to.id)) {
        preferenceById.set(edge.to.id, preference);
      }
    }
  }
  for (const node of graph.nodes.values()) {
    const rank = ranks.get(node.id) ?? 0;
    layers[rank] ??= [];
    layers[rank].push(node);
  }
  const orderById = /* @__PURE__ */ new Map();
  for (const [rank, layer] of layers.entries()) {
    layer?.sort((a, b) => {
      const parentOrderDelta = parentOrder(a, rank, ranks, parentEdgesById, orderById) - parentOrder(b, rank, ranks, parentEdgesById, orderById);
      if (parentOrderDelta !== 0) return parentOrderDelta;
      const preferenceDelta = (preferenceById.get(a.id) ?? 0) - (preferenceById.get(b.id) ?? 0);
      if (preferenceDelta !== 0) return preferenceDelta;
      return (originalIndexById.get(a.id) ?? 0) - (originalIndexById.get(b.id) ?? 0);
    });
    layer?.forEach((node, index) => {
      orderById.set(node.id, index);
    });
  }
  return layers.filter((layer) => layer.length > 0);
}
__name(groupNodesByRank, "groupNodesByRank");
function parentOrder(node, rank, ranks, parentEdgesById, orderById) {
  const parentEdges = parentEdgesById.get(node.id) ?? [];
  const orders = parentEdges.filter((edge) => (ranks.get(edge.from.id) ?? 0) < rank).map((edge) => orderById.get(edge.from.id)).filter((order) => order !== void 0);
  if (orders.length === 0) return Number.POSITIVE_INFINITY;
  return orders.reduce((sum, order) => sum + order, 0) / orders.length;
}
__name(parentOrder, "parentOrder");
function createCanvas(width, height) {
  return Array.from({ length: height }, () => Array(width).fill(" "));
}
__name(createCanvas, "createCanvas");
function mergeCanvasChar(existing, next) {
  if (existing === "") return existing;
  if (next === "") return existing;
  if (existing === " " || existing === next) return next;
  if ("\u25BC\u25B2\u25C0\u25B6\u2192\u2190\u21A9".includes(existing)) return existing;
  if ("\u25BC\u25B2\u25C0\u25B6\u2192\u2190\u21A9".includes(next)) return next;
  if (existing === "\u2502" && next === "\u2500" || existing === "\u2500" && next === "\u2502" || existing === "\u253C" || next === "\u253C") {
    return "\u253C";
  }
  if ("\u250C\u2510\u2514\u2518\u256D\u256E\u2570\u256F\u2571\u2572\u25C7".includes(existing)) return existing;
  return next;
}
__name(mergeCanvasChar, "mergeCanvasChar");
function putChar(canvas, x, y, char, overwrite = false) {
  if (y < 0 || y >= canvas.length || x < 0 || x >= canvas[y].length) return;
  canvas[y][x] = overwrite ? char : mergeCanvasChar(canvas[y][x], char);
}
__name(putChar, "putChar");
function putText(canvas, x, y, text, overwrite = false) {
  let cursor = x;
  for (const char of text) {
    const width = Math.max(1, stringWidth(char));
    putChar(canvas, cursor, y, char, overwrite);
    for (let offset = 1; offset < width; offset++) {
      if (y >= 0 && y < canvas.length && cursor + offset >= 0 && cursor + offset < canvas[y].length) {
        canvas[y][cursor + offset] = "";
      }
    }
    cursor += width;
  }
}
__name(putText, "putText");
function drawHorizontal(canvas, y, x1, x2) {
  const start = Math.min(x1, x2);
  const end = Math.max(x1, x2);
  for (let x = start; x <= end; x++) putChar(canvas, x, y, "\u2500");
}
__name(drawHorizontal, "drawHorizontal");
function drawVertical(canvas, x, y1, y2) {
  const start = Math.min(y1, y2);
  const end = Math.max(y1, y2);
  for (let y = start; y <= end; y++) putChar(canvas, x, y, "\u2502");
}
__name(drawVertical, "drawVertical");
function drawNode(canvas, positioned) {
  positioned.lines.forEach((line, offset) => {
    putText(canvas, positioned.x, positioned.y + offset, line, true);
  });
}
__name(drawNode, "drawNode");
function layoutVertical(graph, contentWidth) {
  const ranks = computeRanks(graph);
  const layers = groupNodesByRank(graph, ranks);
  const positioned = [];
  let y = 0;
  for (const layer of layers) {
    const gapCount = Math.max(0, layer.length - 1);
    const maxNodeWidth = Math.max(
      8,
      Math.floor((contentWidth - gapCount * NODE_GAP_X) / layer.length)
    );
    const rendered = layer.map((node) => ({
      node,
      lines: renderNodeLines(node, Math.min(28, maxNodeWidth))
    }));
    const totalWidth = rendered.reduce((sum, item) => sum + lineWidth(item.lines[0]), 0) + gapCount * NODE_GAP_X;
    let x = Math.max(0, Math.floor((contentWidth - totalWidth) / 2));
    const layerHeight = Math.max(...rendered.map((item) => item.lines.length));
    for (const item of rendered) {
      const width = lineWidth(item.lines[0]);
      const height = item.lines.length;
      positioned.push({
        node: item.node,
        lines: item.lines,
        x,
        y,
        width,
        height,
        centerX: x + Math.floor(width / 2),
        centerY: y + Math.floor(height / 2),
        rank: ranks.get(item.node.id) ?? 0
      });
      x += width + NODE_GAP_X;
    }
    y += layerHeight + NODE_GAP_Y;
  }
  return positioned;
}
__name(layoutVertical, "layoutVertical");
function layoutHorizontal(graph, contentWidth) {
  const ranks = computeRanks(graph);
  const layers = groupNodesByRank(graph, ranks);
  const columnWidth = Math.max(
    10,
    Math.min(
      24,
      Math.floor(
        (contentWidth - (layers.length - 1) * NODE_GAP_X) / layers.length
      )
    )
  );
  const totalWidth = layers.length * columnWidth + (layers.length - 1) * NODE_GAP_X;
  if (totalWidth > contentWidth || layers.length === 0) return null;
  const positioned = [];
  let x = Math.max(0, Math.floor((contentWidth - totalWidth) / 2));
  for (const layer of layers) {
    let y = 0;
    for (const node of layer) {
      const lines = renderNodeLines(node, columnWidth);
      const width = lineWidth(lines[0]);
      positioned.push({
        node,
        lines,
        x: x + Math.floor((columnWidth - width) / 2),
        y,
        width,
        height: lines.length,
        centerX: x + Math.floor(columnWidth / 2),
        centerY: y + Math.floor(lines.length / 2),
        rank: ranks.get(node.id) ?? 0
      });
      y += lines.length + NODE_GAP_Y;
    }
    x += columnWidth + NODE_GAP_X;
  }
  return positioned;
}
__name(layoutHorizontal, "layoutHorizontal");
function drawForwardVerticalEdge(canvas, from, to, label) {
  const startY = from.y + from.height;
  const endY = to.y - 1;
  const midY = Math.max(startY, Math.floor((startY + endY) / 2));
  if (Math.abs(from.centerX - to.centerX) <= 1) {
    drawVertical(canvas, from.centerX, startY, endY);
    putChar(canvas, from.centerX, endY, "\u25BC");
    if (label) {
      putText(
        canvas,
        Math.min(canvas[midY].length - 1, from.centerX + 2),
        midY,
        truncateToWidth(label, 14)
      );
    }
    return;
  }
  const bendY = Math.max(startY, Math.min(midY, endY - 1));
  const targetIsRight = to.centerX > from.centerX;
  drawVertical(canvas, from.centerX, startY, bendY);
  drawHorizontal(canvas, bendY, from.centerX, to.centerX);
  if (bendY + 1 <= endY) {
    drawVertical(canvas, to.centerX, bendY + 1, endY);
  }
  putChar(canvas, from.centerX, bendY, targetIsRight ? "\u2514" : "\u2518", true);
  putChar(canvas, to.centerX, bendY, targetIsRight ? "\u2510" : "\u250C", true);
  putChar(canvas, to.centerX, endY, "\u25BC");
  if (label) {
    const text = truncateToWidth(label, 14);
    const labelX = Math.abs(to.centerX - from.centerX) > stringWidth(text) + 2 ? Math.min(from.centerX, to.centerX) + Math.floor(
      (Math.abs(to.centerX - from.centerX) - stringWidth(text)) / 2
    ) : Math.min(canvas[bendY].length - stringWidth(text), from.centerX + 2);
    putText(canvas, Math.max(0, labelX), bendY, text, true);
  }
}
__name(drawForwardVerticalEdge, "drawForwardVerticalEdge");
function drawVerticalFork(canvas, from, targets) {
  if (targets.length === 0) return;
  if (targets.length === 1) {
    drawForwardVerticalEdge(
      canvas,
      from,
      targets[0].to,
      targets[0].edge.label
    );
    return;
  }
  const sortedTargets = [...targets].sort(
    (a, b) => a.to.centerX - b.to.centerX
  );
  const startY = from.y + from.height;
  const firstTargetTop = Math.min(
    ...sortedTargets.map((target) => target.to.y)
  );
  const forkY = Math.max(startY, firstTargetTop - 3);
  const labelY = Math.min(forkY + 1, firstTargetTop - 2);
  const minX = Math.min(...sortedTargets.map((target) => target.to.centerX));
  const maxX = Math.max(...sortedTargets.map((target) => target.to.centerX));
  drawVertical(canvas, from.centerX, startY, forkY);
  drawHorizontal(canvas, forkY, minX, maxX);
  putChar(canvas, from.centerX, forkY, "\u2534", true);
  for (const [index, target] of sortedTargets.entries()) {
    const endY = target.to.y - 1;
    const targetJunction = sortedTargets.length === 1 ? "\u2534" : index === 0 ? "\u250C" : index === sortedTargets.length - 1 ? "\u2510" : "\u252C";
    putChar(canvas, target.to.centerX, forkY, targetJunction, true);
    putChar(canvas, target.to.centerX, endY, "\u25BC");
    if (target.edge.label) {
      const label = `[${truncateToWidth(target.edge.label, 10)}]`;
      const x = Math.max(
        0,
        Math.min(
          canvas[labelY].length - stringWidth(label),
          target.to.centerX - Math.floor(stringWidth(label) / 2)
        )
      );
      putText(canvas, x, labelY, label, true);
    }
    if (forkY + 1 <= labelY - 1) {
      drawVertical(canvas, target.to.centerX, forkY + 1, labelY - 1);
    }
    if (labelY + 1 <= endY) {
      drawVertical(canvas, target.to.centerX, labelY + 1, endY);
    }
  }
}
__name(drawVerticalFork, "drawVerticalFork");
function formatLoopNote(from, to, label) {
  const edgeLabel = label ? ` [${label}]` : "";
  return `${singleLineLabel(from.node.label)}${edgeLabel} \u21A9 to ${singleLineLabel(
    to.node.label
  )}`;
}
__name(formatLoopNote, "formatLoopNote");
function drawHorizontalEdge(canvas, from, to, label) {
  const forward = to.rank > from.rank;
  const fromX = forward ? from.x + from.width : from.x - 1;
  const toX = forward ? to.x - 1 : to.x + to.width;
  const midX = Math.floor((fromX + toX) / 2);
  if (from.centerY === to.centerY) {
    drawHorizontal(canvas, from.centerY, fromX, toX);
    putChar(canvas, toX, to.centerY, forward ? "\u25B6" : "\u25C0");
    if (label) {
      const text = truncateToWidth(label, 12);
      putText(
        canvas,
        Math.max(0, midX - Math.floor(stringWidth(text) / 2)),
        from.centerY,
        text
      );
    }
    return;
  }
  drawHorizontal(canvas, from.centerY, fromX, midX);
  drawVertical(canvas, midX, from.centerY, to.centerY);
  drawHorizontal(canvas, to.centerY, midX, toX);
  putChar(canvas, toX, to.centerY, forward ? "\u25B6" : "\u25C0");
  if (label) {
    const text = truncateToWidth(label, 12);
    putText(
      canvas,
      Math.max(0, midX - Math.floor(stringWidth(text) / 2)),
      Math.min(from.centerY, to.centerY),
      text
    );
  }
}
__name(drawHorizontalEdge, "drawHorizontalEdge");
function canvasToLines(canvas, contentWidth) {
  return canvas.map((row) => truncateToWidth(row.join("").trimEnd(), contentWidth)).filter(
    (line, index, lines) => line.length > 0 || index < lines.length - 1
  );
}
__name(canvasToLines, "canvasToLines");
function renderLayeredFlowchart(edges, contentWidth, horizontal) {
  const width = Math.max(MIN_CANVAS_WIDTH, contentWidth);
  const graph = buildFlowGraph(edges);
  const positioned = horizontal && graph.nodes.size <= 8 ? layoutHorizontal(graph, width) ?? layoutVertical(graph, width) : layoutVertical(graph, width);
  const byId = new Map(positioned.map((node) => [node.node.id, node]));
  const canvasHeight = Math.max(...positioned.map((node) => node.y + node.height), 1) + 2;
  const canvas = createCanvas(width, canvasHeight);
  const loopNotes = [];
  for (const edge of edges) {
    if (!horizontal && (graph.outgoing.get(edge.from.id)?.length ?? 0) > 1) {
      continue;
    }
    const from = byId.get(edge.from.id);
    const to = byId.get(edge.to.id);
    if (!from || !to) continue;
    if (horizontal && to.rank !== from.rank) {
      drawHorizontalEdge(canvas, from, to, edge.label);
    } else if (to.rank > from.rank) {
      drawForwardVerticalEdge(canvas, from, to, edge.label);
    } else {
      loopNotes.push(formatLoopNote(from, to, edge.label));
    }
  }
  if (!horizontal) {
    for (const edgeList of graph.outgoing.values()) {
      if (edgeList.length <= 1) continue;
      const source = byId.get(edgeList[0].from.id);
      if (!source) continue;
      const forwardTargets = [];
      for (const edge of edgeList) {
        const target = byId.get(edge.to.id);
        if (!target) continue;
        if (target.rank > source.rank) {
          forwardTargets.push({ edge, to: target });
        } else {
          loopNotes.push(formatLoopNote(source, target, edge.label));
        }
      }
      drawVerticalFork(canvas, source, forwardTargets);
    }
  }
  for (const node of positioned) {
    drawNode(canvas, node);
  }
  const lines = canvasToLines(canvas, contentWidth);
  if (loopNotes.length > 0) {
    lines.push("");
    lines.push("Cycles:");
    for (const note of loopNotes) {
      lines.push(truncateToWidth(`  ${note}`, contentWidth));
    }
  }
  return lines;
}
__name(renderLayeredFlowchart, "renderLayeredFlowchart");
function renderFlowchart(source, contentWidth) {
  const allRawLines = source.split(/\r?\n/).map(normalizePreviewLine).filter((line) => line.length > 0 && !LINE_COMMENT_RE.test(line));
  const rawLines = allRawLines.slice(0, MAX_FLOWCHART_PREVIEW_LINES);
  const lineBudgetExceeded = allRawLines.length > rawLines.length;
  const first = rawLines[0] ?? "";
  const direction = FLOW_START_RE.exec(first)?.[1]?.toUpperCase() ?? "TD";
  const lines = rawLines.slice(FLOW_START_RE.test(first) ? 1 : 0);
  const edgeLines = [];
  let edgeBudgetExceeded = false;
  for (const line of lines) {
    for (const part of line.split(";")) {
      const statement = part.trim();
      if (!statement) continue;
      if (edgeLines.length >= MAX_FLOWCHART_PREVIEW_EDGES) {
        edgeBudgetExceeded = true;
        break;
      }
      edgeLines.push(statement);
    }
    if (edgeBudgetExceeded) break;
  }
  const edges = edgeLines.flatMap(parseFlowEdges);
  const normalizedEdges = normalizeFlowNodeLabels(edges);
  if (normalizedEdges.length === 0) {
    return previewSourceFallback(
      source,
      contentWidth,
      "flowchart",
      "Flowchart preview supports simple A --> B style edges; showing source instead."
    );
  }
  const horizontal = direction.includes("LR") || direction.includes("RL");
  const rendered = renderLayeredFlowchart(
    normalizedEdges,
    contentWidth,
    horizontal
  );
  return {
    title: `Mermaid flowchart (${direction})`,
    lines: rendered.slice(0, MAX_RENDERED_LINES),
    warning: [
      lineBudgetExceeded ? `Preview limited to ${MAX_FLOWCHART_PREVIEW_LINES} source lines.` : void 0,
      edgeBudgetExceeded ? `Preview limited to ${MAX_FLOWCHART_PREVIEW_EDGES} edges.` : void 0,
      rendered.length > MAX_RENDERED_LINES ? `Preview truncated to ${MAX_RENDERED_LINES} rendered lines.` : void 0
    ].filter(Boolean).join(" ") || void 0
  };
}
__name(renderFlowchart, "renderFlowchart");
function parseParticipant(line) {
  const match = /^(?:participant|actor)\s+(.+?)(?:\s+as\s+(.+))?$/i.exec(line);
  if (!match) return null;
  const id = stripMermaidPunctuation(match[1]);
  return {
    id,
    label: stripMermaidPunctuation(match[2] ?? id)
  };
}
__name(parseParticipant, "parseParticipant");
function renderSequence(source, contentWidth) {
  const allRawLines = source.split(/\r?\n/).map(normalizePreviewLine).filter(
    (line) => line.length > 0 && !LINE_COMMENT_RE.test(line) && !SEQUENCE_START_RE.test(line)
  );
  const rawLines = allRawLines.slice(0, MAX_SEQUENCE_PREVIEW_LINES);
  const lineBudgetExceeded = allRawLines.length > rawLines.length;
  const participants = /* @__PURE__ */ new Map();
  const messages = [];
  let messageBudgetExceeded = false;
  for (const line of rawLines) {
    const participant = parseParticipant(line);
    if (participant) {
      participants.set(participant.id, participant.label);
      continue;
    }
    const messageMatch = /^(.+?)(-->>|->>|-->|->|--x|-x)\s*(.+?)\s*:\s*(.+)$/.exec(line);
    if (!messageMatch) continue;
    const from = stripMermaidPunctuation(messageMatch[1]);
    const arrow = messageMatch[2].includes("--") ? "\u21E2" : "\u2192";
    const to = stripMermaidPunctuation(messageMatch[3]);
    const message = stripMermaidPunctuation(messageMatch[4]);
    if (!participants.has(from)) participants.set(from, from);
    if (!participants.has(to)) participants.set(to, to);
    if (messages.length >= MAX_SEQUENCE_PREVIEW_MESSAGES) {
      messageBudgetExceeded = true;
      continue;
    }
    messages.push(
      truncateToWidth(
        `${participants.get(from) ?? from} ${arrow} ${participants.get(to) ?? to}: ${message}`,
        contentWidth
      )
    );
  }
  const header = participants.size > 0 ? `Participants: ${Array.from(participants.values()).join(" | ")}` : "Participants: not declared";
  if (messages.length === 0) {
    return previewSourceFallback(
      source,
      contentWidth,
      "sequenceDiagram",
      "Sequence preview supports A->>B: message style arrows; showing source instead."
    );
  }
  const lines = [truncateToWidth(header, contentWidth), ""];
  lines.push(...messages);
  return {
    title: "Mermaid sequence diagram",
    lines: lines.slice(0, MAX_RENDERED_LINES),
    warning: [
      lineBudgetExceeded ? `Preview limited to ${MAX_SEQUENCE_PREVIEW_LINES} source lines.` : void 0,
      messageBudgetExceeded ? `Preview limited to ${MAX_SEQUENCE_PREVIEW_MESSAGES} messages.` : void 0
    ].filter(Boolean).join(" ") || void 0
  };
}
__name(renderSequence, "renderSequence");
function renderClassDiagram(source, contentWidth) {
  const { lines: rawLines, truncated } = diagramLines(source, CLASS_START_RE);
  const classes = /* @__PURE__ */ new Set();
  const relationships = [];
  const members = [];
  let currentClass = null;
  for (const line of rawLines) {
    const classBlockMatch = /^class\s+([A-Za-z0-9_.$:-]+)\s*\{?$/i.exec(line);
    if (classBlockMatch) {
      currentClass = classBlockMatch[1];
      classes.add(currentClass);
      continue;
    }
    if (line === "}") {
      currentClass = null;
      continue;
    }
    const relationMatch = /^([A-Za-z0-9_.$:-]+)\s+([<|*o.]*--[|>*o.]*|<\|--|--\|>|\*--|o--|-->|<--|\.\.>)\s+([A-Za-z0-9_.$:-]+)(?:\s*:\s*(.+))?$/i.exec(
      line
    );
    if (relationMatch) {
      const from = relationMatch[1];
      const relation = relationMatch[2];
      const to = relationMatch[3];
      const label = stripMermaidPunctuation(relationMatch[4] ?? "");
      classes.add(from);
      classes.add(to);
      relationships.push(
        truncateToWidth(
          `${from} ${relation} ${to}${label ? `: ${label}` : ""}`,
          contentWidth
        )
      );
      continue;
    }
    const inlineMemberMatch = /^([A-Za-z0-9_.$:-]+)\s*:\s*(.+)$/i.exec(line);
    if (inlineMemberMatch) {
      classes.add(inlineMemberMatch[1]);
      members.push(
        truncateToWidth(
          `${inlineMemberMatch[1]}: ${stripMermaidPunctuation(inlineMemberMatch[2])}`,
          contentWidth
        )
      );
      continue;
    }
    if (currentClass) {
      members.push(
        truncateToWidth(
          `${currentClass}: ${stripMermaidPunctuation(line)}`,
          contentWidth
        )
      );
    }
  }
  if (classes.size === 0 && relationships.length === 0 && members.length === 0) {
    return previewSourceFallback(
      source,
      contentWidth,
      "classDiagram",
      "Class preview found no previewable classes or relationships; showing source instead."
    );
  }
  const output = [
    truncateToWidth(
      `Classes: ${Array.from(classes).join(" | ") || "not declared"}`,
      contentWidth
    ),
    "",
    ...relationships.length > 0 ? ["Relationships:", ...relationships] : ["Relationships: none previewed"],
    ...members.length > 0 ? ["", "Members:", ...members.slice(0, 24)] : []
  ];
  return {
    title: "Mermaid class diagram",
    lines: output.slice(0, MAX_RENDERED_LINES),
    warning: budgetWarning(truncated)
  };
}
__name(renderClassDiagram, "renderClassDiagram");
function renderStateDiagram(source, contentWidth) {
  const { lines: rawLines, truncated } = diagramLines(source, STATE_START_RE);
  const transitions = [];
  const declarations = [];
  for (const line of rawLines) {
    const transitionMatch = /^(.+?)\s*-->\s*(.+?)(?:\s*:\s*(.+))?$/.exec(line);
    if (transitionMatch) {
      const from = stripMermaidPunctuation(transitionMatch[1]);
      const to = stripMermaidPunctuation(transitionMatch[2]);
      const label = stripMermaidPunctuation(transitionMatch[3] ?? "");
      transitions.push(
        truncateToWidth(
          `${from} \u2192 ${to}${label ? `: ${label}` : ""}`,
          contentWidth
        )
      );
      continue;
    }
    const stateMatch = /^state\s+(.+?)(?:\s+as\s+(.+))?$/i.exec(line);
    if (stateMatch) {
      declarations.push(
        truncateToWidth(
          stripMermaidPunctuation(stateMatch[2] ?? stateMatch[1]),
          contentWidth
        )
      );
    }
  }
  if (declarations.length === 0 && transitions.length === 0) {
    return previewSourceFallback(
      source,
      contentWidth,
      "stateDiagram",
      "State preview found no previewable states or transitions; showing source instead."
    );
  }
  const output = [
    ...declarations.length > 0 ? ["States:", ...declarations.slice(0, 20), ""] : [],
    ...transitions.length > 0 ? ["Transitions:", ...transitions] : ["Transitions: none previewed"]
  ];
  return {
    title: "Mermaid state diagram",
    lines: output.slice(0, MAX_RENDERED_LINES),
    warning: budgetWarning(truncated)
  };
}
__name(renderStateDiagram, "renderStateDiagram");
function renderErDiagram(source, contentWidth) {
  const { lines: rawLines, truncated } = diagramLines(source, ER_START_RE);
  const entities = /* @__PURE__ */ new Set();
  const relationships = [];
  const attributes = [];
  let currentEntity = null;
  for (const line of rawLines) {
    const entityBlock = /^([A-Za-z0-9_.$:-]+)\s*\{$/.exec(line);
    if (entityBlock) {
      currentEntity = entityBlock[1];
      entities.add(currentEntity);
      continue;
    }
    if (line === "}") {
      currentEntity = null;
      continue;
    }
    const relationMatch = /^([A-Za-z0-9_.$:-]+)\s+([|o}{]{1,2}--[|o}{]{1,2})\s+([A-Za-z0-9_.$:-]+)(?:\s*:\s*(.+))?$/i.exec(
      line
    );
    if (relationMatch) {
      entities.add(relationMatch[1]);
      entities.add(relationMatch[3]);
      relationships.push(
        truncateToWidth(
          `${relationMatch[1]} ${relationMatch[2]} ${relationMatch[3]}${relationMatch[4] ? `: ${stripMermaidPunctuation(relationMatch[4])}` : ""}`,
          contentWidth
        )
      );
      continue;
    }
    if (currentEntity) {
      attributes.push(
        truncateToWidth(
          `${currentEntity}: ${stripMermaidPunctuation(line)}`,
          contentWidth
        )
      );
    }
  }
  if (entities.size === 0 && relationships.length === 0 && attributes.length === 0) {
    return previewSourceFallback(
      source,
      contentWidth,
      "erDiagram",
      "ER preview found no previewable entities or relationships; showing source instead."
    );
  }
  return {
    title: "Mermaid ER diagram",
    lines: [
      truncateToWidth(
        `Entities: ${Array.from(entities).join(" | ") || "not declared"}`,
        contentWidth
      ),
      "",
      ...relationships.length > 0 ? ["Relationships:", ...relationships] : ["Relationships: none previewed"],
      ...attributes.length > 0 ? ["", "Attributes:", ...attributes.slice(0, 24)] : []
    ].slice(0, MAX_RENDERED_LINES),
    warning: budgetWarning(truncated)
  };
}
__name(renderErDiagram, "renderErDiagram");
function renderPieDiagram(source, contentWidth) {
  const { lines: rawLines, truncated } = diagramLines(source, PIE_START_RE);
  const titleLine = rawLines.find((line) => /^title\b/i.test(line));
  const slices = rawLines.map((line) => /^["']?(.+?)["']?\s*:\s*([0-9.]+)\s*$/.exec(line)).filter((match) => match !== null).map(
    (match) => truncateToWidth(
      `${stripMermaidPunctuation(match[1])}: ${match[2]}`,
      contentWidth
    )
  );
  if (slices.length === 0) {
    return previewSourceFallback(
      source,
      contentWidth,
      "pie",
      "Pie preview found no previewable slices; showing source instead."
    );
  }
  return {
    title: "Mermaid pie chart",
    lines: [
      ...titleLine ? [
        truncateToWidth(stripMermaidPunctuation(titleLine), contentWidth),
        ""
      ] : [],
      ...slices
    ],
    warning: budgetWarning(truncated)
  };
}
__name(renderPieDiagram, "renderPieDiagram");
function renderGanttDiagram(source, contentWidth) {
  const { lines: rawLines, truncated } = diagramLines(source, GANTT_START_RE);
  const output = [];
  for (const line of rawLines) {
    if (/^(dateFormat|axisFormat|tickInterval|weekday|excludes|todayMarker)\b/i.test(
      line
    )) {
      continue;
    }
    const section = /^section\s+(.+)$/i.exec(line);
    if (section) {
      output.push("");
      output.push(
        truncateToWidth(
          `Section: ${stripMermaidPunctuation(section[1])}`,
          contentWidth
        )
      );
      continue;
    }
    const title = /^title\s+(.+)$/i.exec(line);
    if (title) {
      output.push(
        truncateToWidth(
          `Title: ${stripMermaidPunctuation(title[1])}`,
          contentWidth
        )
      );
      continue;
    }
    output.push(
      truncateToWidth(`\u2022 ${stripMermaidPunctuation(line)}`, contentWidth)
    );
  }
  if (output.length === 0) {
    return previewSourceFallback(
      source,
      contentWidth,
      "gantt",
      "Gantt preview found no previewable tasks; showing source instead."
    );
  }
  return {
    title: "Mermaid gantt chart",
    lines: output.slice(0, MAX_RENDERED_LINES),
    warning: budgetWarning(truncated)
  };
}
__name(renderGanttDiagram, "renderGanttDiagram");
function renderJourneyDiagram(source, contentWidth) {
  const { lines: rawLines, truncated } = diagramLines(source, JOURNEY_START_RE);
  const output = [];
  for (const line of rawLines) {
    const title = /^title\s+(.+)$/i.exec(line);
    if (title) {
      output.push(
        truncateToWidth(
          `Title: ${stripMermaidPunctuation(title[1])}`,
          contentWidth
        )
      );
      continue;
    }
    const section = /^section\s+(.+)$/i.exec(line);
    if (section) {
      output.push("");
      output.push(
        truncateToWidth(
          `Section: ${stripMermaidPunctuation(section[1])}`,
          contentWidth
        )
      );
      continue;
    }
    output.push(
      truncateToWidth(`\u2022 ${stripMermaidPunctuation(line)}`, contentWidth)
    );
  }
  if (output.length === 0) {
    return previewSourceFallback(
      source,
      contentWidth,
      "journey",
      "Journey preview found no previewable steps; showing source instead."
    );
  }
  return {
    title: "Mermaid journey diagram",
    lines: output.slice(0, MAX_RENDERED_LINES),
    warning: budgetWarning(truncated)
  };
}
__name(renderJourneyDiagram, "renderJourneyDiagram");
function renderIndentedTreeDiagram(source, contentWidth, startRe, title, sourceType) {
  const allLines = source.split(/\r?\n/).filter(
    (line) => normalizePreviewLine(line).length > 0 && !LINE_COMMENT_RE.test(normalizePreviewLine(line)) && !startRe.test(normalizePreviewLine(line))
  );
  const rawLines = allLines.slice(0, MAX_GENERIC_PREVIEW_LINES);
  const truncated = allLines.length > rawLines.length;
  const lines = rawLines.map((line) => {
    const safeLine = sanitizeTerminalText(line);
    const indentation = /^\s*/.exec(safeLine)?.[0].length ?? 0;
    const depth = Math.floor(indentation / 2);
    return truncateToWidth(
      `${"  ".repeat(depth)}\u2022 ${safeLine.trim()}`,
      contentWidth
    );
  });
  if (lines.length === 0) {
    return previewSourceFallback(
      source,
      contentWidth,
      sourceType,
      `${title} preview found no previewable nodes; showing source instead.`
    );
  }
  return {
    title,
    lines: lines.slice(0, MAX_RENDERED_LINES),
    warning: budgetWarning(truncated)
  };
}
__name(renderIndentedTreeDiagram, "renderIndentedTreeDiagram");
function renderMermaidVisual(source, contentWidth) {
  const trimmed = sanitizeTerminalText(source).trim();
  const firstLine = trimmed.split(/\r?\n/).find((line) => line.trim()) ?? "";
  if (FLOW_START_RE.test(firstLine)) {
    return renderFlowchart(trimmed, contentWidth);
  }
  if (SEQUENCE_START_RE.test(firstLine)) {
    return renderSequence(trimmed, contentWidth);
  }
  if (CLASS_START_RE.test(firstLine)) {
    return renderClassDiagram(trimmed, contentWidth);
  }
  if (STATE_START_RE.test(firstLine)) {
    return renderStateDiagram(trimmed, contentWidth);
  }
  if (ER_START_RE.test(firstLine)) {
    return renderErDiagram(trimmed, contentWidth);
  }
  if (GANTT_START_RE.test(firstLine)) {
    return renderGanttDiagram(trimmed, contentWidth);
  }
  if (PIE_START_RE.test(firstLine)) {
    return renderPieDiagram(trimmed, contentWidth);
  }
  if (JOURNEY_START_RE.test(firstLine)) {
    return renderJourneyDiagram(trimmed, contentWidth);
  }
  if (MINDMAP_START_RE.test(firstLine)) {
    return renderIndentedTreeDiagram(
      trimmed,
      contentWidth,
      MINDMAP_START_RE,
      "Mermaid mindmap",
      "mindmap"
    );
  }
  if (GIT_GRAPH_START_RE.test(firstLine)) {
    return renderIndentedTreeDiagram(
      trimmed,
      contentWidth,
      GIT_GRAPH_START_RE,
      "Mermaid git graph",
      "gitGraph"
    );
  }
  if (REQUIREMENT_START_RE.test(firstLine)) {
    return renderIndentedTreeDiagram(
      trimmed,
      contentWidth,
      REQUIREMENT_START_RE,
      "Mermaid requirement diagram",
      "requirementDiagram"
    );
  }
  const type = firstLine.split(/\s+/)[0] || "unknown";
  return previewSourceFallback(trimmed, contentWidth, type);
}
__name(renderMermaidVisual, "renderMermaidVisual");

// packages/cli/src/ui/utils/mermaidImageRenderer.ts
init_esbuild_shims();
import crypto from "node:crypto";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { spawn, spawnSync } from "node:child_process";
var CACHE_LIMIT = 40;
var PNG_CACHE_LIMIT = 20;
var CACHE_BYTE_LIMIT = 32 * 1024 * 1024;
var PNG_CACHE_BYTE_LIMIT = 32 * 1024 * 1024;
var DEFAULT_RENDER_TIMEOUT_MS = 8e3;
var DEFAULT_MERMAID_RENDER_WIDTH = 1280;
var MAX_MERMAID_PNG_BYTES = 8 * 1024 * 1024;
var MAX_RENDERER_OUTPUT_CHARS = 16 * 1024;
var MAX_RENDER_TIMEOUT_MS = 6e4;
var OUTPUT_TRUNCATION_MARKER = "\n... renderer output truncated ...";
var NPX_MERMAID_CLI = "npx:@mermaid-js/mermaid-cli@11.12.0";
var PNG_SIGNATURE = "89504e470d0a1a0a";
var KITTY_PLACEHOLDER = "\u{10EEEE}";
var RENDERER_ENV_ALLOWLIST = [
  "PATH",
  "PATHEXT",
  "HOME",
  "USERPROFILE",
  "TMPDIR",
  "TMP",
  "TEMP",
  "SystemRoot",
  "WINDIR",
  "COMSPEC",
  "LOCALAPPDATA",
  "APPDATA",
  "CHROME_PATH",
  "PUPPETEER_EXECUTABLE_PATH",
  "PUPPETEER_CACHE_DIR",
  "PLAYWRIGHT_BROWSERS_PATH"
];
var KITTY_PLACEHOLDER_DIACRITICS = [
  "\u0305",
  "\u030D",
  "\u030E",
  "\u0310",
  "\u0312",
  "\u033D",
  "\u033E",
  "\u033F",
  "\u0346",
  "\u034A",
  "\u034B",
  "\u034C",
  "\u0350",
  "\u0351",
  "\u0352",
  "\u0357",
  "\u035B",
  "\u0363",
  "\u0364",
  "\u0365",
  "\u0366",
  "\u0367",
  "\u0368",
  "\u0369",
  "\u036A",
  "\u036B",
  "\u036C",
  "\u036D",
  "\u036E",
  "\u036F",
  "\u0483",
  "\u0484",
  "\u0485",
  "\u0486",
  "\u0487",
  "\u0592",
  "\u0593",
  "\u0594",
  "\u0595",
  "\u0597",
  "\u0598",
  "\u0599",
  "\u059C",
  "\u059D",
  "\u059E",
  "\u059F",
  "\u05A0",
  "\u05A1",
  "\u05A8",
  "\u05A9",
  "\u05AB",
  "\u05AC",
  "\u05AF",
  "\u05C4",
  "\u0610",
  "\u0611",
  "\u0612",
  "\u0613",
  "\u0614",
  "\u0615",
  "\u0616",
  "\u0617",
  "\u0657",
  "\u0658",
  "\u0659",
  "\u065A",
  "\u065B",
  "\u065D",
  "\u065E",
  "\u06D6",
  "\u06D7",
  "\u06D8",
  "\u06D9",
  "\u06DA",
  "\u06DB",
  "\u06DC",
  "\u06DF",
  "\u06E0",
  "\u06E1",
  "\u06E2",
  "\u06E4",
  "\u06E7",
  "\u06E8",
  "\u06EB",
  "\u06EC",
  "\u0730",
  "\u0732",
  "\u0733",
  "\u0735",
  "\u0736",
  "\u073A",
  "\u073D",
  "\u073F",
  "\u0740",
  "\u0741",
  "\u0743",
  "\u0745",
  "\u0747",
  "\u0749",
  "\u074A",
  "\u07EB",
  "\u07EC",
  "\u07ED",
  "\u07EE",
  "\u07EF",
  "\u07F0",
  "\u07F1",
  "\u07F3",
  "\u0816",
  "\u0817",
  "\u0818",
  "\u0819",
  "\u081B",
  "\u081C",
  "\u081D",
  "\u081E",
  "\u081F",
  "\u0820",
  "\u0821",
  "\u0822",
  "\u0823",
  "\u0825",
  "\u0826",
  "\u0827",
  "\u0829",
  "\u082A",
  "\u082B",
  "\u082C"
];
var cachedResults = /* @__PURE__ */ new Map();
var cachedPngResults = /* @__PURE__ */ new Map();
var cachedResultsBytes = 0;
var cachedPngResultsBytes = 0;
function detectTerminalImageProtocol(env = process.env) {
  if (env["QWEN_CODE_DISABLE_MERMAID_IMAGES"] === "1") {
    return null;
  }
  const forced = env["QWEN_CODE_MERMAID_IMAGE_PROTOCOL"]?.toLowerCase();
  if (forced === "off" || forced === "none" || forced === "0") {
    return null;
  }
  if (!process.stdout.isTTY || env["TMUX"] || env["SSH_TTY"] || env["SSH_CLIENT"]) {
    return null;
  }
  if (forced) {
    if (forced === "kitty") return "kitty";
    if (forced === "iterm" || forced === "iterm2") return "iterm2";
  }
  const term = env["TERM"]?.toLowerCase() ?? "";
  const termProgram = env["TERM_PROGRAM"]?.toLowerCase() ?? "";
  if (env["KITTY_WINDOW_ID"] || term.includes("kitty") || termProgram.includes("ghostty")) {
    return "kitty";
  }
  if (termProgram === "iterm.app" || termProgram.includes("wezterm")) {
    return "iterm2";
  }
  return null;
}
__name(detectTerminalImageProtocol, "detectTerminalImageProtocol");
function encodeITerm2InlineImage(png, widthCells, rows) {
  return `\x1B]1337;File=inline=1;width=${widthCells};height=${rows};preserveAspectRatio=1:${png.toString(
    "base64"
  )}\x07`;
}
__name(encodeITerm2InlineImage, "encodeITerm2InlineImage");
function encodeKittyVirtualImage(png, imageId, widthCells, rows) {
  return encodeKittyImageCommand(
    png,
    `a=T,f=100,i=${imageId},q=2,U=1,c=${widthCells},r=${rows}`
  );
}
__name(encodeKittyVirtualImage, "encodeKittyVirtualImage");
function encodeKittyImageCommand(png, firstControl) {
  const encoded = png.toString("base64");
  const chunkSize = 4096;
  const chunks = [];
  for (let offset = 0; offset < encoded.length; offset += chunkSize) {
    const chunk = encoded.slice(offset, offset + chunkSize);
    const hasMore = offset + chunkSize < encoded.length;
    const control = offset === 0 ? `${firstControl},m=${hasMore ? 1 : 0}` : `m=${hasMore ? 1 : 0}`;
    chunks.push(`\x1B_G${control};${chunk}\x1B\\`);
  }
  return chunks.join("");
}
__name(encodeKittyImageCommand, "encodeKittyImageCommand");
function buildKittyPlaceholder(imageId, widthCells, rows) {
  const clampedRows = Math.min(rows, KITTY_PLACEHOLDER_DIACRITICS.length);
  const clampedWidth = Math.min(
    widthCells,
    KITTY_PLACEHOLDER_DIACRITICS.length
  );
  const lines = Array.from({ length: clampedRows }, (_, row) => {
    const rowDiacritic = KITTY_PLACEHOLDER_DIACRITICS[row];
    const cells = Array.from({ length: clampedWidth }, (_2, column) => {
      const columnDiacritic = KITTY_PLACEHOLDER_DIACRITICS[column];
      return `${KITTY_PLACEHOLDER}${rowDiacritic}${columnDiacritic}`;
    });
    return cells.join("");
  });
  return {
    color: `#${imageId.toString(16).padStart(6, "0")}`,
    imageId,
    lines
  };
}
__name(buildKittyPlaceholder, "buildKittyPlaceholder");
function readPngSize(png) {
  if (png.length < 24 || png.subarray(0, 8).toString("hex") !== PNG_SIGNATURE) {
    return null;
  }
  return {
    width: png.readUInt32BE(16),
    height: png.readUInt32BE(20)
  };
}
__name(readPngSize, "readPngSize");
function isMermaidImageRenderingDisabled(env) {
  return env["QWEN_CODE_DISABLE_MERMAID_IMAGES"] === "1";
}
__name(isMermaidImageRenderingDisabled, "isMermaidImageRenderingDisabled");
function unavailableImageRenderingDisabled() {
  return {
    kind: "unavailable",
    reason: "Mermaid image rendering is disabled via QWEN_CODE_DISABLE_MERMAID_IMAGES."
  };
}
__name(unavailableImageRenderingDisabled, "unavailableImageRenderingDisabled");
async function renderMermaidImageAsync({
  source,
  contentWidth,
  availableTerminalHeight,
  env = process.env,
  signal
}) {
  if (isMermaidImageRenderingDisabled(env)) {
    return unavailableImageRenderingDisabled();
  }
  const imageRendering = env["QWEN_CODE_MERMAID_IMAGE_RENDERING"];
  if (imageRendering !== "1" && imageRendering?.toLowerCase() !== "on" && imageRendering?.toLowerCase() !== "true") {
    return {
      kind: "unavailable",
      reason: "Mermaid image rendering is disabled by default. Set QWEN_CODE_MERMAID_IMAGE_RENDERING=1 to enable external renderers.",
      showReason: false
    };
  }
  const protocol = detectTerminalImageProtocol(env);
  if (protocol === "iterm2") {
    return {
      kind: "unavailable",
      reason: "iTerm2 inline image rendering is disabled in the async TUI path to avoid cursor-position races.",
      showReason: false
    };
  }
  const chafa = protocol ? null : findExecutable("chafa", env);
  if (!protocol && !chafa) {
    return {
      kind: "unavailable",
      reason: "No supported terminal image protocol or chafa renderer was detected."
    };
  }
  const mmdc = findMmdc(env);
  if (!mmdc) {
    return {
      kind: "unavailable",
      reason: "Mermaid CLI (mmdc) was not found. Install @mermaid-js/mermaid-cli, set QWEN_CODE_MERMAID_MMD_CLI, or set QWEN_CODE_MERMAID_ALLOW_NPX=1."
    };
  }
  const cacheKey = createCacheKey(
    source,
    contentWidth,
    availableTerminalHeight,
    protocol ?? `chafa:${chafa}`,
    mmdc,
    env
  );
  const cached = getResultCache(cacheKey);
  if (cached) return cached;
  const pngCacheKey = createPngCacheKey(source, mmdc, env);
  const cachedPng = getPngCache(pngCacheKey);
  let rendered = cachedPng;
  if (!rendered) {
    const nextRendered = await renderPngWithMmdcAsync(
      source,
      mmdc,
      env,
      signal
    );
    rendered = signal?.aborted ? nextRendered : rememberPng(pngCacheKey, nextRendered);
  }
  if (!rendered.ok) {
    if (signal?.aborted) {
      return {
        kind: "unavailable",
        reason: rendered.error
      };
    }
    return remember(cacheKey, {
      kind: "unavailable",
      reason: rendered.error
    });
  }
  const pngSize = readPngSize(rendered.png);
  if (!pngSize) {
    return remember(cacheKey, {
      kind: "unavailable",
      reason: "Mermaid CLI did not produce a valid PNG."
    });
  }
  const imageShape = fitImageToTerminal(
    pngSize,
    contentWidth,
    availableTerminalHeight,
    env
  );
  if (protocol) {
    const imageId = protocol === "kitty" ? createKittyImageId(rendered.png, imageShape) : void 0;
    const sequence = protocol === "kitty" ? encodeKittyVirtualImage(
      rendered.png,
      imageId,
      imageShape.widthCells,
      imageShape.rows
    ) : encodeITerm2InlineImage(
      rendered.png,
      imageShape.widthCells,
      imageShape.rows
    );
    return remember(cacheKey, {
      kind: "terminal-image",
      title: `Mermaid diagram image (${protocol})`,
      sequence,
      rows: imageShape.rows,
      protocol,
      placeholder: protocol === "kitty" ? buildKittyPlaceholder(
        imageId,
        imageShape.widthCells,
        imageShape.rows
      ) : void 0
    });
  }
  const ansi = await renderPngWithChafaAsync(
    rendered.png,
    imageShape.widthCells,
    imageShape.rows,
    chafa,
    env,
    signal
  );
  if (!ansi.ok) {
    if (signal?.aborted) {
      return {
        kind: "unavailable",
        reason: ansi.error
      };
    }
    return remember(cacheKey, {
      kind: "unavailable",
      reason: ansi.error
    });
  }
  return remember(cacheKey, {
    kind: "ansi",
    title: "Mermaid diagram image (ANSI)",
    lines: ansi.output.split(/\r?\n/).filter((line) => line.length > 0)
  });
}
__name(renderMermaidImageAsync, "renderMermaidImageAsync");
function createKittyImageId(png, imageShape) {
  const hash = crypto.createHash("sha256").update(png).update("\0").update(String(imageShape.widthCells)).update("\0").update(String(imageShape.rows)).digest();
  const id = hash.readUIntBE(0, 3);
  return id === 0 ? 1 : id;
}
__name(createKittyImageId, "createKittyImageId");
function getResultCache(key) {
  const cached = cachedResults.get(key);
  if (cached) {
    cachedResults.delete(key);
    cachedResults.set(key, cached);
  }
  return cached;
}
__name(getResultCache, "getResultCache");
function getPngCache(key) {
  const cached = cachedPngResults.get(key);
  if (cached) {
    cachedPngResults.delete(key);
    cachedPngResults.set(key, cached);
  }
  return cached;
}
__name(getPngCache, "getPngCache");
function createPngCacheKey(source, mmdc, env) {
  return crypto.createHash("sha256").update(source).update("\0").update(mmdc).update("\0").update(String(getMermaidRenderWidth(env))).digest("hex");
}
__name(createPngCacheKey, "createPngCacheKey");
function createCacheKey(source, contentWidth, availableTerminalHeight, renderer, mmdc, env) {
  return crypto.createHash("sha256").update(source).update("\0").update(String(contentWidth)).update("\0").update(String(availableTerminalHeight ?? "auto")).update("\0").update(renderer).update("\0").update(mmdc).update("\0").update(String(getMermaidCellAspectRatio(env))).digest("hex");
}
__name(createCacheKey, "createCacheKey");
function remember(key, result) {
  const resultBytes = estimateResultBytes(result);
  if (resultBytes > CACHE_BYTE_LIMIT) {
    cachedResults.delete(key);
    return result;
  }
  const existing = cachedResults.get(key);
  if (existing) {
    cachedResultsBytes -= estimateResultBytes(existing);
  }
  cachedResults.set(key, result);
  cachedResultsBytes += resultBytes;
  while (cachedResults.size > CACHE_LIMIT || cachedResultsBytes > CACHE_BYTE_LIMIT) {
    const oldest = cachedResults.keys().next().value;
    if (!oldest) break;
    const oldestResult = cachedResults.get(oldest);
    if (oldestResult) {
      cachedResultsBytes -= estimateResultBytes(oldestResult);
    }
    cachedResults.delete(oldest);
  }
  return result;
}
__name(remember, "remember");
function rememberPng(key, result) {
  const resultBytes = estimatePngResultBytes(result);
  if (resultBytes > PNG_CACHE_BYTE_LIMIT) {
    cachedPngResults.delete(key);
    return result;
  }
  const existing = cachedPngResults.get(key);
  if (existing) {
    cachedPngResultsBytes -= estimatePngResultBytes(existing);
  }
  cachedPngResults.set(key, result);
  cachedPngResultsBytes += resultBytes;
  while (cachedPngResults.size > PNG_CACHE_LIMIT || cachedPngResultsBytes > PNG_CACHE_BYTE_LIMIT) {
    const oldest = cachedPngResults.keys().next().value;
    if (!oldest) break;
    const oldestResult = cachedPngResults.get(oldest);
    if (oldestResult) {
      cachedPngResultsBytes -= estimatePngResultBytes(oldestResult);
    }
    cachedPngResults.delete(oldest);
  }
  return result;
}
__name(rememberPng, "rememberPng");
function estimateResultBytes(result) {
  switch (result.kind) {
    case "terminal-image":
      return Buffer.byteLength(result.sequence, "utf8") + (result.placeholder?.lines.reduce(
        (total, line) => total + Buffer.byteLength(line, "utf8"),
        0
      ) ?? 0);
    case "ansi":
      return result.lines.reduce(
        (total, line) => total + Buffer.byteLength(line, "utf8"),
        0
      );
    case "unavailable":
      return Buffer.byteLength(result.reason, "utf8");
    default: {
      const exhaustive = result;
      return exhaustive;
    }
  }
}
__name(estimateResultBytes, "estimateResultBytes");
function estimatePngResultBytes(result) {
  return result.ok ? result.png.byteLength : Buffer.byteLength(result.error);
}
__name(estimatePngResultBytes, "estimatePngResultBytes");
function findMmdc(env) {
  const explicit = env["QWEN_CODE_MERMAID_MMD_CLI"];
  if (explicit && isExecutable(explicit)) return explicit;
  const mmdc = findExecutable("mmdc", env);
  if (mmdc) return mmdc;
  if (env["QWEN_CODE_MERMAID_ALLOW_NPX"] === "1" && findExecutable("npx", env)) {
    return NPX_MERMAID_CLI;
  }
  return null;
}
__name(findMmdc, "findMmdc");
function findExecutable(command, env) {
  const candidates = [];
  const extensions = process.platform === "win32" ? (env["PATHEXT"] ?? ".EXE;.CMD;.BAT;.COM").split(";").filter(Boolean) : [""];
  const addCandidates = /* @__PURE__ */ __name((dir) => {
    for (const extension of extensions) {
      candidates.push(path.join(dir, `${command}${extension}`));
    }
  }, "addCandidates");
  const allowLocalRenderers = env["QWEN_CODE_MERMAID_ALLOW_LOCAL_RENDERERS"] === "1";
  const localRendererDir = normalizeExecutableDir(
    process.cwd(),
    "node_modules",
    ".bin"
  );
  if (allowLocalRenderers) {
    addCandidates(localRendererDir);
  }
  for (const dir of (env["PATH"] ?? "").split(path.delimiter).filter(Boolean)) {
    const normalizedDir = normalizeExecutableDir(dir);
    if (!allowLocalRenderers && (normalizedDir === localRendererDir || normalizedDir.endsWith(`${path.sep}node_modules${path.sep}.bin`))) {
      continue;
    }
    addCandidates(dir);
  }
  return candidates.find(isExecutable) ?? null;
}
__name(findExecutable, "findExecutable");
function normalizeExecutableDir(...segments) {
  const dir = path.resolve(...segments);
  try {
    return fs.realpathSync.native(dir);
  } catch {
    return dir;
  }
}
__name(normalizeExecutableDir, "normalizeExecutableDir");
function isExecutable(filePath) {
  try {
    fs.accessSync(filePath, fs.constants.X_OK);
    return true;
  } catch {
    return false;
  }
}
__name(isExecutable, "isExecutable");
async function renderPngWithMmdcAsync(source, mmdc, env, signal) {
  const tempDir = await fs.promises.mkdtemp(
    path.join(os.tmpdir(), "qwen-mermaid-")
  );
  const inputPath = path.join(tempDir, "diagram.mmd");
  const outputPath = path.join(tempDir, "diagram.png");
  const renderWidth = getMermaidRenderWidth(env);
  try {
    await fs.promises.writeFile(inputPath, source, "utf8");
    const mmdcArgs = [
      "-i",
      inputPath,
      "-o",
      outputPath,
      "-b",
      "transparent",
      "-w",
      String(renderWidth)
    ];
    const command = mmdc === NPX_MERMAID_CLI ? findExecutable("npx", env) : mmdc;
    const args = mmdc === NPX_MERMAID_CLI ? ["-y", "@mermaid-js/mermaid-cli@11.12.0", ...mmdcArgs] : mmdcArgs;
    const result = await runCommand(command, args, {
      env: createRendererChildEnv(env),
      shell: shouldRunThroughShell(command),
      timeout: getMermaidRenderTimeout(env),
      signal
    });
    if (result.error) {
      return { ok: false, error: result.error };
    }
    if (result.status !== 0) {
      const stderr = result.stderr.trim();
      return {
        ok: false,
        error: stderr || `Mermaid CLI exited with status ${result.status}.`
      };
    }
    let outputSize;
    try {
      outputSize = (await fs.promises.stat(outputPath)).size;
    } catch {
      return { ok: false, error: "Mermaid CLI did not write an output file." };
    }
    if (outputSize > MAX_MERMAID_PNG_BYTES) {
      return {
        ok: false,
        error: `Mermaid CLI output exceeded ${MAX_MERMAID_PNG_BYTES} bytes.`
      };
    }
    return { ok: true, png: await fs.promises.readFile(outputPath) };
  } finally {
    await fs.promises.rm(tempDir, { recursive: true, force: true });
  }
}
__name(renderPngWithMmdcAsync, "renderPngWithMmdcAsync");
function shouldRunThroughShell(command) {
  return process.platform === "win32" && /\.(?:cmd|bat)$/i.test(command);
}
__name(shouldRunThroughShell, "shouldRunThroughShell");
function getMermaidRenderWidth(env) {
  const configuredWidth = Number(env["QWEN_CODE_MERMAID_RENDER_WIDTH"]);
  if (Number.isFinite(configuredWidth) && configuredWidth > 0) {
    return Math.max(320, Math.min(1800, Math.round(configuredWidth)));
  }
  return DEFAULT_MERMAID_RENDER_WIDTH;
}
__name(getMermaidRenderWidth, "getMermaidRenderWidth");
function getMermaidRenderTimeout(env) {
  const configuredTimeout = Number(env["QWEN_CODE_MERMAID_RENDER_TIMEOUT_MS"]);
  if (Number.isFinite(configuredTimeout) && configuredTimeout > 0) {
    return Math.min(Math.round(configuredTimeout), MAX_RENDER_TIMEOUT_MS);
  }
  return DEFAULT_RENDER_TIMEOUT_MS;
}
__name(getMermaidRenderTimeout, "getMermaidRenderTimeout");
function createRendererChildEnv(env) {
  const sourceEnv = { ...process.env, ...env };
  const childEnv = {};
  for (const key of RENDERER_ENV_ALLOWLIST) {
    const value = sourceEnv[key];
    if (value !== void 0) {
      childEnv[key] = value;
    }
  }
  return childEnv;
}
__name(createRendererChildEnv, "createRendererChildEnv");
function getMermaidCellAspectRatio(env) {
  const configuredAspectRatio = Number(
    env["QWEN_CODE_MERMAID_CELL_ASPECT_RATIO"]
  );
  if (Number.isFinite(configuredAspectRatio) && configuredAspectRatio > 0) {
    return Math.max(0.2, Math.min(configuredAspectRatio, 2));
  }
  return 0.5;
}
__name(getMermaidCellAspectRatio, "getMermaidCellAspectRatio");
async function renderPngWithChafaAsync(png, widthCells, rows, chafa, env, signal) {
  const tempDir = await fs.promises.mkdtemp(
    path.join(os.tmpdir(), "qwen-mermaid-")
  );
  const imagePath = path.join(tempDir, "diagram.png");
  try {
    await fs.promises.writeFile(imagePath, png);
    const result = await runCommand(
      chafa,
      [
        "--animate=off",
        "--format=symbols",
        "--symbols=block",
        `--size=${widthCells}x${rows}`,
        imagePath
      ],
      {
        env: createRendererChildEnv(env),
        shell: shouldRunThroughShell(chafa),
        timeout: getMermaidRenderTimeout(env),
        signal
      }
    );
    if (result.error) {
      return { ok: false, error: result.error };
    }
    if (result.status !== 0) {
      return {
        ok: false,
        error: result.stderr.trim() || `chafa exited with status ${result.status}.`
      };
    }
    return { ok: true, output: result.stdout };
  } finally {
    await fs.promises.rm(tempDir, { recursive: true, force: true });
  }
}
__name(renderPngWithChafaAsync, "renderPngWithChafaAsync");
function runCommand(command, args, options) {
  return new Promise((resolve) => {
    if (options.signal?.aborted) {
      resolve({
        status: null,
        stdout: "",
        stderr: "",
        error: "Command cancelled."
      });
      return;
    }
    const child = spawn(command, args, {
      env: options.env,
      shell: options.shell,
      stdio: ["ignore", "pipe", "pipe"]
    });
    let stdout = { text: "", truncated: false };
    let stderr = { text: "", truncated: false };
    let settled = false;
    let killTimer;
    let terminationRequested = false;
    const finish = /* @__PURE__ */ __name((result) => {
      if (settled) return;
      settled = true;
      clearTimeout(timer);
      if (!terminationRequested && killTimer) clearTimeout(killTimer);
      options.signal?.removeEventListener("abort", handleAbort);
      resolve(result);
    }, "finish");
    const terminateChild = /* @__PURE__ */ __name(() => {
      terminationRequested = true;
      child.kill("SIGTERM");
      killTimer = setTimeout(() => {
        child.kill("SIGKILL");
      }, 1e3);
      killTimer.unref?.();
    }, "terminateChild");
    const handleAbort = /* @__PURE__ */ __name(() => {
      terminateChild();
      finish({
        status: null,
        stdout: finalizeBoundedRendererOutput(stdout),
        stderr: finalizeBoundedRendererOutput(stderr),
        error: "Command cancelled."
      });
    }, "handleAbort");
    const timer = setTimeout(() => {
      terminateChild();
      finish({
        status: null,
        stdout: finalizeBoundedRendererOutput(stdout),
        stderr: finalizeBoundedRendererOutput(stderr),
        error: `Command timed out after ${options.timeout}ms.`
      });
    }, options.timeout);
    options.signal?.addEventListener("abort", handleAbort, { once: true });
    child.stdout?.setEncoding("utf8");
    child.stderr?.setEncoding("utf8");
    child.stdout?.on("data", (chunk) => {
      stdout = appendBoundedRendererOutput(stdout, chunk);
    });
    child.stderr?.on("data", (chunk) => {
      stderr = appendBoundedRendererOutput(stderr, chunk);
    });
    child.on("error", (error) => {
      finish({
        status: null,
        stdout: finalizeBoundedRendererOutput(stdout),
        stderr: finalizeBoundedRendererOutput(stderr),
        error: error.message
      });
    });
    child.on("close", (status) => {
      finish({
        status,
        stdout: finalizeBoundedRendererOutput(stdout),
        stderr: finalizeBoundedRendererOutput(stderr)
      });
    });
  });
}
__name(runCommand, "runCommand");
function appendBoundedRendererOutput(current, chunk) {
  if (current.truncated) {
    return current;
  }
  const next = current.text + chunk;
  if (next.length <= MAX_RENDERER_OUTPUT_CHARS) {
    return { text: next, truncated: false };
  }
  return {
    text: next.slice(
      0,
      MAX_RENDERER_OUTPUT_CHARS - OUTPUT_TRUNCATION_MARKER.length
    ) + OUTPUT_TRUNCATION_MARKER,
    truncated: true
  };
}
__name(appendBoundedRendererOutput, "appendBoundedRendererOutput");
function finalizeBoundedRendererOutput(output) {
  if (!output.truncated || output.text.endsWith(OUTPUT_TRUNCATION_MARKER)) {
    return output.text;
  }
  return output.text.slice(
    0,
    MAX_RENDERER_OUTPUT_CHARS - OUTPUT_TRUNCATION_MARKER.length
  ) + OUTPUT_TRUNCATION_MARKER;
}
__name(finalizeBoundedRendererOutput, "finalizeBoundedRendererOutput");
function fitImageToTerminal(size, contentWidth, availableTerminalHeight, env = process.env) {
  const widthCells = Math.max(16, Math.min(contentWidth, 120));
  const naturalRows = Math.ceil(
    size.height / size.width * widthCells * getMermaidCellAspectRatio(env)
  );
  const maxRows = Math.max(4, Math.min(availableTerminalHeight ?? 32, 60));
  return {
    widthCells,
    rows: Math.max(4, Math.min(naturalRows, maxRows))
  };
}
__name(fitImageToTerminal, "fitImageToTerminal");

// packages/cli/src/ui/contexts/TerminalOutputContext.tsx
init_esbuild_shims();
var import_react6 = __toESM(require_react(), 1);
var import_jsx_runtime4 = __toESM(require_jsx_runtime(), 1);
var defaultWriteRaw = /* @__PURE__ */ __name((data) => {
  process.stdout.write(data);
}, "defaultWriteRaw");
var TerminalOutputContext = (0, import_react6.createContext)(defaultWriteRaw);
var TerminalOutputProvider = /* @__PURE__ */ __name(({ value, children }) => /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(TerminalOutputContext.Provider, { value, children }), "TerminalOutputProvider");
function useTerminalOutput() {
  return (0, import_react6.useContext)(TerminalOutputContext);
}
__name(useTerminalOutput, "useTerminalOutput");

// packages/cli/src/ui/utils/MermaidDiagram.tsx
var import_jsx_runtime5 = __toESM(require_jsx_runtime(), 1);
var MERMAID_PADDING = 1;
function getRenderErrorReason(error) {
  return error instanceof Error ? error.message : String(error);
}
__name(getRenderErrorReason, "getRenderErrorReason");
var MermaidDiagramInternal = /* @__PURE__ */ __name(({
  source,
  sourceCopyCommand,
  contentWidth,
  isPending,
  availableTerminalHeight
}) => {
  const writeRaw = useTerminalOutput();
  const preparedTerminalImageSequence = import_react7.default.useRef(null);
  const [imageState, setImageState] = import_react7.default.useState(
    null
  );
  const innerWidth = Math.max(8, contentWidth - MERMAID_PADDING);
  const imageKey = `${source}\0${innerWidth}\0${availableTerminalHeight ?? "auto"}`;
  const image = imageState?.key === imageKey && !isPending ? imageState.result : null;
  const visual = import_react7.default.useMemo(
    () => renderMermaidVisual(source, innerWidth),
    [source, innerWidth]
  );
  import_react7.default.useEffect(() => {
    if (isPending) {
      setImageState(null);
      return;
    }
    let cancelled = false;
    const abortController = new AbortController();
    void renderMermaidImageAsync({
      source,
      contentWidth: innerWidth,
      availableTerminalHeight,
      signal: abortController.signal
    }).then(
      (result) => {
        if (!cancelled) {
          setImageState({ key: imageKey, result });
        }
      },
      (error) => {
        if (!cancelled) {
          setImageState({
            key: imageKey,
            result: {
              kind: "unavailable",
              reason: getRenderErrorReason(error)
            }
          });
        }
      }
    );
    return () => {
      cancelled = true;
      abortController.abort();
    };
  }, [availableTerminalHeight, imageKey, innerWidth, isPending, source]);
  const kittySequence = image?.kind === "terminal-image" && image.protocol === "kitty" && image.placeholder ? image.sequence : null;
  import_react7.default.useEffect(() => {
    preparedTerminalImageSequence.current = null;
  }, [imageKey]);
  import_react7.default.useEffect(() => {
    if (!kittySequence || preparedTerminalImageSequence.current === kittySequence) {
      return;
    }
    preparedTerminalImageSequence.current = kittySequence;
    process.nextTick(() => writeRaw(kittySequence));
  }, [kittySequence, writeRaw]);
  const titleWithSourceHint = /* @__PURE__ */ __name((title) => `${title} \xB7 source: ${sourceCopyCommand}`, "titleWithSourceHint");
  if (image?.kind === "terminal-image" && image.protocol === "kitty" && image.placeholder) {
    return /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(
      Box_default,
      {
        paddingLeft: MERMAID_PADDING,
        flexDirection: "column",
        width: contentWidth,
        flexShrink: 0,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(Text, { bold: true, color: theme.text.accent, children: titleWithSourceHint(visual.title) }),
          /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
            MaxSizedBox,
            {
              maxHeight: availableTerminalHeight,
              maxWidth: innerWidth,
              overflowDirection: "bottom",
              children: image.placeholder.lines.map((line, index) => /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(Text, { color: image.placeholder.color, wrap: "truncate-end", children: line }) }, index))
            }
          )
        ]
      }
    );
  }
  if (image?.kind === "ansi") {
    return /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(
      Box_default,
      {
        paddingLeft: MERMAID_PADDING,
        flexDirection: "column",
        width: contentWidth,
        flexShrink: 0,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(Text, { bold: true, color: theme.text.accent, children: titleWithSourceHint(visual.title) }),
          /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
            MaxSizedBox,
            {
              maxHeight: availableTerminalHeight,
              maxWidth: innerWidth,
              overflowDirection: "bottom",
              children: image.lines.map((line, index) => /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(Text, { children: line || " " }) }, index))
            }
          )
        ]
      }
    );
  }
  return /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(
    Box_default,
    {
      paddingLeft: MERMAID_PADDING,
      flexDirection: "column",
      width: contentWidth,
      flexShrink: 0,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(Text, { bold: true, color: theme.text.accent, children: titleWithSourceHint(visual.title) }),
        /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
          MaxSizedBox,
          {
            maxHeight: availableTerminalHeight,
            maxWidth: innerWidth,
            overflowDirection: "bottom",
            children: visual.lines.map((line, index) => /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(Text, { color: theme.text.primary, children: line || " " }) }, index))
          }
        ),
        visual.warning && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(Text, { color: theme.text.secondary, wrap: "wrap", children: visual.warning }),
        !isPending && image?.kind === "unavailable" && image.showReason !== false && /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(Text, { color: theme.text.secondary, wrap: "wrap", children: [
          "Image rendering unavailable: ",
          image.reason
        ] })
      ]
    }
  );
}, "MermaidDiagramInternal");
var MermaidDiagram = import_react7.default.memo(MermaidDiagramInternal);

// packages/cli/src/ui/contexts/RenderModeContext.tsx
init_esbuild_shims();
var import_react8 = __toESM(require_react(), 1);
var RenderModeContext = import_react8.default.createContext({
  renderMode: "render",
  setRenderMode: /* @__PURE__ */ __name(() => void 0, "setRenderMode")
});
var RenderModeProvider = RenderModeContext.Provider;
function useRenderMode() {
  return import_react8.default.useContext(RenderModeContext);
}
__name(useRenderMode, "useRenderMode");

// packages/cli/src/ui/utils/MarkdownDisplay.tsx
var import_jsx_runtime6 = __toESM(require_jsx_runtime(), 1);
var MIN_PENDING_CONTENT_LINES = 1;
function countMarkdownSourceBlocks(text) {
  const codeBlockLanguageCounts = /* @__PURE__ */ new Map();
  const lines = text.split(/\r?\n/);
  const codeFenceRegex = /^ *(`{3,}|~{3,}) *([^`]*)$/;
  const mathFenceRegex = /^ *\$\$ *$/;
  let activeCodeFence = null;
  let inMathBlock = false;
  let mathBlockCount = 0;
  for (const line of lines) {
    const codeFenceMatch = line.match(codeFenceRegex);
    if (activeCodeFence) {
      if (codeFenceMatch && codeFenceMatch[1].startsWith(activeCodeFence[0]) && codeFenceMatch[1].length >= activeCodeFence.length) {
        activeCodeFence = null;
      }
      continue;
    }
    if (inMathBlock) {
      if (mathFenceRegex.test(line)) {
        inMathBlock = false;
      }
      continue;
    }
    if (codeFenceMatch) {
      activeCodeFence = codeFenceMatch[1];
      const lang = codeFenceMatch[2]?.trim().split(/\s+/)[0]?.toLowerCase() || null;
      if (lang) {
        codeBlockLanguageCounts.set(
          lang,
          (codeBlockLanguageCounts.get(lang) ?? 0) + 1
        );
      }
      continue;
    }
    if (mathFenceRegex.test(line)) {
      inMathBlock = true;
      mathBlockCount += 1;
    }
  }
  return { codeBlockLanguageCounts, mathBlockCount };
}
__name(countMarkdownSourceBlocks, "countMarkdownSourceBlocks");
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 BLOCKQUOTE_PREFIX_PADDING = 1;
var MATH_BLOCK_PREFIX_PADDING = 1;
var INLINE_MATH_MAX_CHARS3 = 1024;
var TABLE_INLINE_MATH_SPAN_RE = new RegExp(
  String.raw`(?<![\w$])\$(?![\s\d$])(?=[^$\n]{1,${INLINE_MATH_MAX_CHARS3}}\S\$)[^$\n]{1,${INLINE_MATH_MAX_CHARS3}}\$(?![\w$])`,
  "y"
);
function readTableInlineMathSpan(row, index) {
  TABLE_INLINE_MATH_SPAN_RE.lastIndex = index;
  return TABLE_INLINE_MATH_SPAN_RE.exec(row)?.[0] ?? null;
}
__name(readTableInlineMathSpan, "readTableInlineMathSpan");
function splitMarkdownTableRow(row) {
  const cells = [];
  let current = "";
  let activeCodeFenceLength = 0;
  for (let index = 0; index < row.length; index++) {
    const char = row[index];
    if (char === "\\") {
      const next = row[index + 1];
      if (next === "|") {
        current += "|";
        index += 1;
        continue;
      }
      current += char;
      continue;
    }
    if (char === "`") {
      let runLength = 1;
      while (row[index + runLength] === "`") {
        runLength += 1;
      }
      if (activeCodeFenceLength === 0) {
        activeCodeFenceLength = runLength;
      } else if (runLength === activeCodeFenceLength) {
        activeCodeFenceLength = 0;
      }
      current += "`".repeat(runLength);
      index += runLength - 1;
      continue;
    }
    if (char === "$" && activeCodeFenceLength === 0) {
      const mathSpan = readTableInlineMathSpan(row, index);
      if (mathSpan) {
        current += mathSpan;
        index += mathSpan.length - 1;
        continue;
      }
    }
    if (char === "|" && activeCodeFenceLength === 0) {
      cells.push(current.trim());
      current = "";
      continue;
    }
    current += char;
  }
  cells.push(current.trim());
  return cells;
}
__name(splitMarkdownTableRow, "splitMarkdownTableRow");
var MarkdownDisplayInternal = /* @__PURE__ */ __name(({
  text,
  isPending,
  availableTerminalHeight,
  contentWidth,
  textColor = theme.text.primary,
  sourceCopyIndexOffsets
}) => {
  const { renderMode } = useRenderMode();
  if (!text) return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(import_jsx_runtime6.Fragment, {});
  const renderVisualBlocks = renderMode === "render";
  const displayText = isPending ? text.trimEnd() : text;
  const allLines = displayText.split(/\r?\n/);
  const pendingLineBudget = isPending && availableTerminalHeight !== void 0 ? Math.max(MIN_PENDING_CONTENT_LINES, availableTerminalHeight - 2) : void 0;
  const pendingClipped = pendingLineBudget !== void 0 && allLines.length > pendingLineBudget;
  const lines = pendingClipped ? allLines.slice(0, pendingLineBudget) : allLines;
  const headerRegex = /^ *(#{1,4}) +(.*)/;
  const codeFenceRegex = /^ *(`{3,}|~{3,}) *([^`]*)$/;
  const ulItemRegex = /^([ \t]*)([-*+]) +(.*)/;
  const olItemRegex = /^([ \t]*)(\d+)\. +(.*)/;
  const hrRegex = /^ *([-*_] *){3,} *$/;
  const blockquoteRegex = /^ *> ?(.*)$/;
  const mathFenceRegex = /^ *\$\$ *$/;
  const tableRowRegex = /^\s*\|(.+)\|\s*$/;
  const tableSeparatorRegex = /^(?=.*\|)\s*\|?\s*(:?-+:?)\s*(\|\s*(:?-+:?)\s*)*\|?\s*$/;
  const parseTableAligns = /* @__PURE__ */ __name((line) => splitMarkdownTableRow(line).filter((cell) => cell.length > 0).map((cell) => {
    const startsWithColon = cell.startsWith(":");
    const endsWithColon = cell.endsWith(":");
    if (startsWithColon && endsWithColon) return "center";
    if (endsWithColon) return "right";
    return "left";
  }), "parseTableAligns");
  const contentBlocks = [];
  let inCodeBlock = false;
  let codeBlockIndex = 0;
  let currentCodeBlockIndex = 0;
  let currentCodeBlockLangIndex = 0;
  const codeBlockLanguageCounts = new Map(
    sourceCopyIndexOffsets?.codeBlockLanguageCounts
  );
  let lastLineEmpty = true;
  let codeBlockContent = [];
  let codeBlockLang = null;
  let codeBlockFence = "";
  let inMathBlock = false;
  let mathBlockIndex = sourceCopyIndexOffsets?.mathBlockCount ?? 0;
  let currentMathBlockIndex = 0;
  let mathBlockContent = [];
  let inTable = false;
  let tableRows = [];
  let tableHeaders = [];
  let tableAligns = [];
  function addContentBlock(block) {
    if (block) {
      contentBlocks.push(block);
      lastLineEmpty = false;
    }
  }
  __name(addContentBlock, "addContentBlock");
  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_runtime6.jsx)(
            RenderCodeBlock,
            {
              content: codeBlockContent,
              lang: codeBlockLang,
              codeBlockIndex: currentCodeBlockIndex,
              codeBlockLangIndex: currentCodeBlockLangIndex,
              isPending,
              availableTerminalHeight,
              contentWidth
            },
            key
          )
        );
        inCodeBlock = false;
        currentCodeBlockIndex = 0;
        currentCodeBlockLangIndex = 0;
        codeBlockContent = [];
        codeBlockLang = null;
        codeBlockFence = "";
      } else {
        codeBlockContent.push(line);
      }
      return;
    }
    if (inMathBlock) {
      if (mathFenceRegex.test(line)) {
        addContentBlock(
          /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
            RenderMathBlock,
            {
              content: mathBlockContent,
              sourceCopyCommand: `/copy latex ${currentMathBlockIndex}`,
              contentWidth,
              isPending,
              availableTerminalHeight
            },
            key
          )
        );
        inMathBlock = false;
        currentMathBlockIndex = 0;
        mathBlockContent = [];
      } else {
        mathBlockContent.push(line);
      }
      return;
    }
    const codeFenceMatch = line.match(codeFenceRegex);
    const mathFenceMatch = line.match(mathFenceRegex);
    const headerMatch = line.match(headerRegex);
    const ulMatch = line.match(ulItemRegex);
    const olMatch = line.match(olItemRegex);
    const hrMatch = line.match(hrRegex);
    const blockquoteMatch = line.match(blockquoteRegex);
    const tableRowMatch = line.match(tableRowRegex);
    const tableSeparatorMatch = line.match(tableSeparatorRegex);
    if (codeFenceMatch) {
      inCodeBlock = true;
      codeBlockIndex += 1;
      currentCodeBlockIndex = codeBlockIndex;
      codeBlockFence = codeFenceMatch[1];
      codeBlockLang = codeFenceMatch[2]?.trim().split(/\s+/)[0] || null;
      if (codeBlockLang) {
        const normalizedLang = codeBlockLang.toLowerCase();
        const nextLangIndex = (codeBlockLanguageCounts.get(normalizedLang) ?? 0) + 1;
        codeBlockLanguageCounts.set(normalizedLang, nextLangIndex);
        currentCodeBlockLangIndex = nextLangIndex;
      } else {
        currentCodeBlockLangIndex = 0;
      }
    } else if (mathFenceMatch && renderVisualBlocks) {
      inMathBlock = true;
      mathBlockIndex += 1;
      currentMathBlockIndex = mathBlockIndex;
      mathBlockContent = [];
    } else if (tableRowMatch && !inTable && renderVisualBlocks) {
      const potentialHeaders = splitMarkdownTableRow(tableRowMatch[1]);
      const nextLine = index + 1 < lines.length ? lines[index + 1] : "";
      const sepMatch = nextLine.match(tableSeparatorRegex);
      const sepColCount = sepMatch ? splitMarkdownTableRow(nextLine).filter((c) => c.length > 0).length : 0;
      if (sepMatch && sepColCount === potentialHeaders.length) {
        inTable = true;
        tableHeaders = potentialHeaders;
        tableRows = [];
      } else {
        addContentBlock(
          /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text, { wrap: "wrap", children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
            RenderInline,
            {
              text: line,
              textColor,
              enableInlineMath: renderVisualBlocks
            }
          ) }) }, key)
        );
      }
    } else if (inTable && tableSeparatorMatch) {
      tableAligns = parseTableAligns(line);
    } else if (inTable && tableRowMatch) {
      const cells = splitMarkdownTableRow(tableRowMatch[1]);
      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_runtime6.jsx)(
            RenderTable,
            {
              headers: tableHeaders,
              rows: tableRows,
              contentWidth,
              aligns: tableAligns,
              enableInlineMath: renderVisualBlocks
            },
            `table-${contentBlocks.length}`
          )
        );
      }
      inTable = false;
      tableRows = [];
      tableHeaders = [];
      tableAligns = [];
      if (line.trim().length > 0) {
        addContentBlock(
          /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text, { wrap: "wrap", children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
            RenderInline,
            {
              text: line,
              textColor,
              enableInlineMath: renderVisualBlocks
            }
          ) }) }, key)
        );
      }
    } else if (hrMatch) {
      addContentBlock(
        /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text, { dimColor: true, children: "---" }) }, key)
      );
    } else if (blockquoteMatch && renderVisualBlocks) {
      addContentBlock(
        /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
          RenderBlockquote,
          {
            quoteText: blockquoteMatch[1],
            textColor,
            enableInlineMath: renderVisualBlocks
          },
          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_runtime6.jsx)(Text, { bold: true, color: textColor, children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
            RenderInline,
            {
              text: headerText,
              textColor,
              enableInlineMath: renderVisualBlocks
            }
          ) });
          break;
        case 2:
          headerNode = /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text, { bold: true, color: textColor, children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
            RenderInline,
            {
              text: headerText,
              textColor,
              enableInlineMath: renderVisualBlocks
            }
          ) });
          break;
        case 3:
          headerNode = /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text, { bold: true, color: textColor, children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
            RenderInline,
            {
              text: headerText,
              textColor,
              enableInlineMath: renderVisualBlocks
            }
          ) });
          break;
        case 4:
          headerNode = /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text, { italic: true, color: textColor, children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
            RenderInline,
            {
              text: headerText,
              textColor,
              enableInlineMath: renderVisualBlocks
            }
          ) });
          break;
        default:
          headerNode = /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text, { color: textColor, children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
            RenderInline,
            {
              text: headerText,
              textColor,
              enableInlineMath: renderVisualBlocks
            }
          ) });
          break;
      }
      if (headerNode) addContentBlock(/* @__PURE__ */ (0, import_jsx_runtime6.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_runtime6.jsx)(
          RenderListItem,
          {
            itemText,
            type: "ul",
            marker,
            leadingWhitespace,
            textColor,
            renderVisualBlocks
          },
          key
        )
      );
    } else if (olMatch) {
      const leadingWhitespace = olMatch[1];
      const marker = olMatch[2];
      const itemText = olMatch[3];
      addContentBlock(
        /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
          RenderListItem,
          {
            itemText,
            type: "ol",
            marker,
            leadingWhitespace,
            textColor,
            renderVisualBlocks
          },
          key
        )
      );
    } else {
      if (line.trim().length === 0 && !inCodeBlock) {
        if (!lastLineEmpty) {
          contentBlocks.push(
            /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Box_default, { height: EMPTY_LINE_HEIGHT }, `spacer-${index}`)
          );
          lastLineEmpty = true;
        }
      } else {
        addContentBlock(
          /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text, { wrap: "wrap", color: textColor, children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
            RenderInline,
            {
              text: line,
              textColor,
              enableInlineMath: renderVisualBlocks
            }
          ) }) }, key)
        );
      }
    }
  });
  if (inCodeBlock) {
    addContentBlock(
      /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
        RenderCodeBlock,
        {
          content: codeBlockContent,
          lang: codeBlockLang,
          codeBlockIndex: currentCodeBlockIndex,
          codeBlockLangIndex: currentCodeBlockLangIndex,
          isPending,
          availableTerminalHeight,
          contentWidth
        },
        "line-eof"
      )
    );
  }
  if (inMathBlock) {
    addContentBlock(
      /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
        RenderMathBlock,
        {
          content: mathBlockContent,
          sourceCopyCommand: `/copy latex ${currentMathBlockIndex}`,
          contentWidth,
          isPending,
          availableTerminalHeight
        },
        "math-eof"
      )
    );
  }
  if (inTable && tableHeaders.length > 0 && tableRows.length > 0) {
    addContentBlock(
      /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
        RenderTable,
        {
          headers: tableHeaders,
          rows: tableRows,
          contentWidth,
          aligns: tableAligns,
          enableInlineMath: renderVisualBlocks
        },
        `table-${contentBlocks.length}`
      )
    );
  }
  if (pendingClipped) {
    return /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(Box_default, { flexDirection: "column", children: [
      contentBlocks,
      /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text, { color: theme.text.secondary, wrap: "truncate", children: "... generating more ..." })
    ] });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(import_jsx_runtime6.Fragment, { children: contentBlocks });
}, "MarkdownDisplayInternal");
var RenderCodeBlockInternal = /* @__PURE__ */ __name(({
  content,
  lang,
  codeBlockIndex,
  codeBlockLangIndex,
  isPending,
  availableTerminalHeight,
  contentWidth
}) => {
  const settings = useSettings();
  const { renderMode } = useRenderMode();
  const MIN_LINES_FOR_MESSAGE = 1;
  const RESERVED_LINES = 2;
  if (lang?.toLowerCase() === "mermaid" && renderMode === "render") {
    if (isPending) {
      return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
        RenderPendingMermaidBlock,
        {
          content,
          availableTerminalHeight,
          contentWidth
        }
      );
    }
    return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
      MermaidDiagram,
      {
        source: content.join("\n"),
        sourceCopyCommand: `/copy mermaid ${codeBlockLangIndex || codeBlockIndex}`,
        isPending,
        availableTerminalHeight,
        contentWidth
      }
    );
  }
  const fullContent = content.join("\n");
  if (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_runtime6.jsx)(Box_default, { paddingLeft: CODE_BLOCK_PREFIX_PADDING, children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text, { color: theme.text.secondary, children: "... code is being written ..." }) });
      }
      const truncatedContent = content.slice(0, MAX_CODE_LINES_WHEN_PENDING);
      const colorizedTruncatedCode = colorizeCode(
        truncatedContent.join("\n"),
        lang,
        availableTerminalHeight,
        contentWidth - CODE_BLOCK_PREFIX_PADDING,
        void 0,
        settings
      );
      return /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(Box_default, { paddingLeft: CODE_BLOCK_PREFIX_PADDING, flexDirection: "column", children: [
        colorizedTruncatedCode,
        /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text, { color: theme.text.secondary, children: "... generating more ..." })
      ] });
    }
  }
  const colorizedCode = colorizeCode(
    fullContent,
    lang,
    availableTerminalHeight,
    contentWidth - CODE_BLOCK_PREFIX_PADDING,
    void 0,
    settings
  );
  return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
    Box_default,
    {
      paddingLeft: CODE_BLOCK_PREFIX_PADDING,
      flexDirection: "column",
      width: contentWidth,
      flexShrink: 0,
      children: colorizedCode
    }
  );
}, "RenderCodeBlockInternal");
var RenderCodeBlock = import_react9.default.memo(RenderCodeBlockInternal);
var RenderPendingMermaidBlockInternal = /* @__PURE__ */ __name(({ content, availableTerminalHeight, contentWidth }) => {
  const maxPreviewLines = availableTerminalHeight === void 0 ? 6 : Math.max(0, availableTerminalHeight - 2);
  const previewLines = content.slice(0, maxPreviewLines);
  return /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(
    Box_default,
    {
      paddingLeft: CODE_BLOCK_PREFIX_PADDING,
      flexDirection: "column",
      width: contentWidth,
      flexShrink: 0,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text, { color: theme.text.accent, children: "Mermaid diagram is being written..." }),
        previewLines.map((line, index) => /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text, { color: theme.text.secondary, wrap: "truncate-end", children: line || " " }, index)),
        content.length > previewLines.length && /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text, { color: theme.text.secondary, children: "... generating more ..." })
      ]
    }
  );
}, "RenderPendingMermaidBlockInternal");
var RenderPendingMermaidBlock = import_react9.default.memo(RenderPendingMermaidBlockInternal);
var RenderMathBlockInternal = /* @__PURE__ */ __name(({
  content,
  sourceCopyCommand,
  contentWidth,
  isPending,
  availableTerminalHeight
}) => {
  const RESERVED_LINES = 3;
  if (isPending && availableTerminalHeight !== void 0) {
    const maxPreviewLines = Math.max(
      0,
      availableTerminalHeight - RESERVED_LINES
    );
    if (content.length > maxPreviewLines) {
      const previewLines = content.slice(0, maxPreviewLines);
      return /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(
        Box_default,
        {
          paddingLeft: MATH_BLOCK_PREFIX_PADDING,
          flexDirection: "column",
          width: contentWidth,
          flexShrink: 0,
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(Text, { bold: true, color: theme.text.accent, children: [
              "LaTeX block \xB7 source: ",
              sourceCopyCommand
            ] }),
            previewLines.map((line, index) => /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text, { color: theme.text.secondary, wrap: "truncate-end", children: line || " " }, index)),
            /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text, { color: theme.text.secondary, children: "... generating more ..." })
          ]
        }
      );
    }
  }
  const rendered = renderInlineLatex(content.join(" "));
  return /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(
    Box_default,
    {
      paddingLeft: MATH_BLOCK_PREFIX_PADDING,
      flexDirection: "column",
      width: contentWidth,
      flexShrink: 0,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(Text, { bold: true, color: theme.text.accent, children: [
          "LaTeX block \xB7 source: ",
          sourceCopyCommand
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text, { color: theme.text.accent, wrap: "wrap", children: rendered })
      ]
    }
  );
}, "RenderMathBlockInternal");
var RenderMathBlock = import_react9.default.memo(RenderMathBlockInternal);
var RenderBlockquoteInternal = /* @__PURE__ */ __name(({
  quoteText,
  textColor = theme.text.primary,
  enableInlineMath = true
}) => /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(Box_default, { paddingLeft: BLOCKQUOTE_PREFIX_PADDING, flexDirection: "row", children: [
  /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text, { color: theme.text.secondary, children: "\u2502 " }),
  /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Box_default, { flexGrow: LIST_ITEM_TEXT_FLEX_GROW, children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text, { wrap: "wrap", color: textColor, italic: true, children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
    RenderInline,
    {
      text: quoteText,
      textColor,
      enableInlineMath
    }
  ) }) })
] }), "RenderBlockquoteInternal");
var RenderBlockquote = import_react9.default.memo(RenderBlockquoteInternal);
var RenderListItemInternal = /* @__PURE__ */ __name(({
  itemText,
  type,
  marker,
  leadingWhitespace = "",
  textColor = theme.text.primary,
  renderVisualBlocks = true
}) => {
  const taskMatch = itemText.match(/^\[([ xX])\]\s+(.*)$/);
  const isTaskItem = taskMatch !== null && renderVisualBlocks;
  const isTaskChecked = taskMatch?.[1]?.toLowerCase() === "x";
  const effectiveItemText = isTaskItem ? taskMatch[2] : itemText;
  const prefix = isTaskItem ? `${isTaskChecked ? "\u2713" : "\u25CB"} ` : type === "ol" ? `${marker}. ` : `${marker} `;
  const prefixWidth = prefix.length;
  const indentation = leadingWhitespace.length;
  return /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(
    Box_default,
    {
      paddingLeft: indentation + LIST_ITEM_PREFIX_PADDING,
      flexDirection: "row",
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Box_default, { width: prefixWidth, children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text, { color: textColor, children: prefix }) }),
        /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Box_default, { flexGrow: LIST_ITEM_TEXT_FLEX_GROW, children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text, { wrap: "wrap", color: textColor, children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
          RenderInline,
          {
            text: effectiveItemText,
            textColor,
            enableInlineMath: renderVisualBlocks
          }
        ) }) })
      ]
    }
  );
}, "RenderListItemInternal");
var RenderListItem = import_react9.default.memo(RenderListItemInternal);
var RenderTableInternal = /* @__PURE__ */ __name(({
  headers,
  rows,
  contentWidth,
  aligns,
  enableInlineMath = false
}) => /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
  TableRenderer,
  {
    headers,
    rows,
    contentWidth,
    aligns,
    enableInlineMath
  }
), "RenderTableInternal");
var RenderTable = import_react9.default.memo(RenderTableInternal);
var MarkdownDisplay = import_react9.default.memo(MarkdownDisplayInternal);

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

// packages/cli/src/ui/utils/displayUtils.ts
init_esbuild_shims();
function getArenaStatusLabel(status) {
  switch (status) {
    case "idle" /* IDLE */:
      return { icon: "\u2713", text: "Idle", color: theme.status.success };
    case "completed" /* COMPLETED */:
      return { icon: "\u2713", text: "Done", color: theme.status.success };
    case "cancelled" /* CANCELLED */:
      return { icon: "\u2298", text: "Cancelled", color: theme.status.warning };
    case "failed" /* FAILED */:
      return { icon: "\u2717", text: "Failed", color: theme.status.error };
    case "running" /* RUNNING */:
      return { icon: "\u25CB", text: "Running", color: theme.text.secondary };
    case "initializing" /* INITIALIZING */:
      return { icon: "\u25CB", text: "Initializing", color: theme.text.secondary };
    default:
      return { icon: "\u25CB", text: status, color: theme.text.secondary };
  }
}
__name(getArenaStatusLabel, "getArenaStatusLabel");
var TOOL_SUCCESS_RATE_HIGH = 95;
var TOOL_SUCCESS_RATE_MEDIUM = 85;
var USER_AGREEMENT_RATE_HIGH = 75;
var USER_AGREEMENT_RATE_MEDIUM = 45;
var getStatusColor = /* @__PURE__ */ __name((value, thresholds, options = {}) => {
  if (value >= thresholds.green) {
    return theme.status.success;
  }
  if (value >= thresholds.yellow) {
    return theme.status.warning;
  }
  if (thresholds.red != null && value >= thresholds.red) {
    return theme.status.error;
  }
  return options.defaultColor ?? theme.status.error;
}, "getStatusColor");
function formatDuration2(ms) {
  const totalSeconds = Math.round(ms / 1e3);
  if (totalSeconds < 60) {
    return `${totalSeconds}s`;
  }
  const minutes = Math.floor(totalSeconds / 60);
  const seconds = totalSeconds % 60;
  return seconds > 0 ? `${minutes}m ${seconds}s` : `${minutes}m`;
}
__name(formatDuration2, "formatDuration");

// packages/cli/src/ui/components/messages/ConversationMessages.tsx
var import_jsx_runtime7 = __toESM(require_jsx_runtime(), 1);
var THINKING_ICON = "\u2234 ";
var THINKING_ICON_PENDING = "\u2235 ";
var toggleKeyHint = process.platform === "darwin" ? "option+t" : "alt+t";
function getPrefixWidth(prefix) {
  return stringWidth(prefix) + 1;
}
__name(getPrefixWidth, "getPrefixWidth");
var PrefixedTextMessage = /* @__PURE__ */ __name(({
  text,
  prefix,
  prefixColor,
  textColor,
  ariaLabel,
  marginTop = 0,
  alignSelf
}) => {
  const prefixWidth = getPrefixWidth(prefix);
  return /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(
    Box_default,
    {
      flexDirection: "row",
      paddingY: 0,
      marginTop,
      alignSelf,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(Box_default, { width: prefixWidth, children: /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(Text, { color: prefixColor, "aria-label": ariaLabel, children: prefix }) }),
        /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(Box_default, { flexGrow: 1, children: /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(Text, { wrap: "wrap", color: textColor, children: text }) })
      ]
    }
  );
}, "PrefixedTextMessage");
var PrefixedMarkdownMessage = /* @__PURE__ */ __name(({
  text,
  prefix,
  prefixColor,
  isPending,
  availableTerminalHeight,
  contentWidth,
  ariaLabel,
  textColor,
  sourceCopyIndexOffsets
}) => {
  const prefixWidth = getPrefixWidth(prefix);
  return /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(Box_default, { flexDirection: "row", children: [
    /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(Box_default, { width: prefixWidth, children: /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(Text, { color: prefixColor, "aria-label": ariaLabel, children: prefix }) }),
    /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(Box_default, { flexGrow: 1, flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(
      MarkdownDisplay,
      {
        text,
        isPending,
        availableTerminalHeight,
        contentWidth: contentWidth - prefixWidth,
        textColor,
        sourceCopyIndexOffsets
      }
    ) })
  ] });
}, "PrefixedMarkdownMessage");
var ContinuationMarkdownMessage = /* @__PURE__ */ __name(({
  text,
  isPending,
  availableTerminalHeight,
  contentWidth,
  basePrefix,
  textColor,
  sourceCopyIndexOffsets
}) => {
  const prefixWidth = getPrefixWidth(basePrefix);
  return /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(Box_default, { flexDirection: "column", paddingLeft: prefixWidth, children: /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(
    MarkdownDisplay,
    {
      text,
      isPending,
      availableTerminalHeight,
      contentWidth: contentWidth - prefixWidth,
      textColor,
      sourceCopyIndexOffsets
    }
  ) });
}, "ContinuationMarkdownMessage");
var UserMessage = /* @__PURE__ */ __name(({ text }) => (
  // The TUI paints no background of its own; user messages render directly on
  // the terminal background so they blend in across terminals and themes.
  /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(
    PrefixedTextMessage,
    {
      text,
      prefix: ">",
      prefixColor: theme.text.accent,
      textColor: theme.text.accent,
      ariaLabel: SCREEN_READER_USER_PREFIX,
      alignSelf: "flex-start",
      marginTop: 1
    }
  )
), "UserMessage");
var UserShellMessage = /* @__PURE__ */ __name(({ text }) => {
  const commandToDisplay = text.startsWith("!") ? text.substring(1) : text;
  return /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(
    PrefixedTextMessage,
    {
      text: commandToDisplay,
      prefix: "$",
      prefixColor: theme.text.link,
      textColor: theme.text.primary
    }
  );
}, "UserShellMessage");
var AssistantMessage = /* @__PURE__ */ __name(({
  text,
  isPending,
  availableTerminalHeight,
  contentWidth,
  sourceCopyIndexOffsets
}) => /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(
  PrefixedMarkdownMessage,
  {
    text,
    prefix: "\u25C6",
    prefixColor: theme.text.accent,
    ariaLabel: SCREEN_READER_MODEL_PREFIX,
    isPending,
    availableTerminalHeight,
    contentWidth,
    sourceCopyIndexOffsets
  }
), "AssistantMessage");
var AssistantMessageContent = /* @__PURE__ */ __name(({
  text,
  isPending,
  availableTerminalHeight,
  contentWidth,
  sourceCopyIndexOffsets
}) => /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(
  ContinuationMarkdownMessage,
  {
    text,
    isPending,
    availableTerminalHeight,
    contentWidth,
    basePrefix: "\u25C6",
    sourceCopyIndexOffsets
  }
), "AssistantMessageContent");
var MAX_STREAMING_THINKING_VISUAL_LINES = 4;
function tailVisualLines(text, width, maxLines) {
  const charBudget = maxLines * width * 2;
  let sliceStart = Math.max(0, text.length - charBudget);
  if (sliceStart > 0) {
    const nl = text.indexOf("\n", sliceStart);
    if (nl !== -1 && nl < text.length - 1) {
      sliceStart = nl + 1;
    }
  }
  const lines = wrapToVisualLines(text.slice(sliceStart), width);
  return lines.slice(-maxLines).join("\n");
}
__name(tailVisualLines, "tailVisualLines");
var ThinkMessage = /* @__PURE__ */ __name(({
  text,
  isPending,
  expanded = false,
  availableTerminalHeight,
  contentWidth,
  durationMs
}) => {
  const durationSuffix = durationMs != null ? ` ${formatDuration2(durationMs)}` : "";
  if (!isPending && !expanded) {
    const label = durationMs != null ? `${t("Thought for")} ${formatDuration2(durationMs)}` : t("Thinking");
    return /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(Text, { dimColor: true, italic: true, children: [
      THINKING_ICON,
      label,
      " ",
      t("({{keyHint}} to expand)", { keyHint: toggleKeyHint })
    ] });
  }
  if (isPending) {
    const innerWidth = Math.max(contentWidth - 2, 20);
    const maxLines = availableTerminalHeight != null ? Math.max(
      1,
      Math.min(
        MAX_STREAMING_THINKING_VISUAL_LINES,
        Math.floor(availableTerminalHeight / 3)
      )
    ) : MAX_STREAMING_THINKING_VISUAL_LINES;
    const display = tailVisualLines(text, innerWidth, maxLines);
    return /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(Box_default, { flexDirection: "column", children: [
      /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(Text, { dimColor: true, italic: true, children: [
        THINKING_ICON_PENDING,
        t("Thinking"),
        "\u2026",
        durationSuffix
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(Box_default, { paddingLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(Text, { dimColor: true, wrap: "truncate", children: display }) })
    ] });
  }
  const expandedLabel = durationMs != null ? `${t("Thought for")} ${formatDuration2(durationMs)}` : `${t("Thinking")}\u2026`;
  return /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(Box_default, { flexDirection: "column", children: [
    /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(Text, { dimColor: true, italic: true, children: [
      THINKING_ICON,
      expandedLabel,
      " ",
      t("({{keyHint}} to collapse)", { keyHint: toggleKeyHint })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(Box_default, { paddingLeft: 2, flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(
      MarkdownDisplay,
      {
        text,
        isPending: false,
        availableTerminalHeight,
        contentWidth: contentWidth - 2,
        textColor: theme.text.secondary
      }
    ) })
  ] });
}, "ThinkMessage");
var ThinkMessageContent = /* @__PURE__ */ __name(({
  text,
  isPending,
  expanded = false,
  availableTerminalHeight,
  contentWidth
}) => {
  if (!isPending && !expanded) {
    return null;
  }
  if (isPending) {
    const innerWidth = Math.max(contentWidth - 2, 20);
    const maxLines = availableTerminalHeight != null ? Math.max(
      1,
      Math.min(
        MAX_STREAMING_THINKING_VISUAL_LINES,
        Math.floor(availableTerminalHeight / 3)
      )
    ) : MAX_STREAMING_THINKING_VISUAL_LINES;
    const display = tailVisualLines(text, innerWidth, maxLines);
    return /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(Box_default, { paddingLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(Text, { dimColor: true, wrap: "truncate", children: display }) });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(Box_default, { paddingLeft: 2, flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(
    MarkdownDisplay,
    {
      text,
      isPending: false,
      availableTerminalHeight,
      contentWidth: contentWidth - 2,
      textColor: theme.text.secondary
    }
  ) });
}, "ThinkMessageContent");

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

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

// packages/cli/src/ui/components/messages/DiffRenderer.tsx
init_esbuild_shims();
import crypto2 from "node:crypto";
var import_jsx_runtime8 = __toESM(require_jsx_runtime(), 1);
function parseDiffWithLineNumbers(diffContent) {
  const lines = diffContent.split("\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);
      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;
}
__name(parseDiffWithLineNumbers, "parseDiffWithLineNumbers");
var DEFAULT_TAB_WIDTH = 4;
var DiffRenderer = /* @__PURE__ */ __name(({
  diffContent,
  filename,
  tabWidth = DEFAULT_TAB_WIDTH,
  availableTerminalHeight,
  contentWidth,
  theme: theme2,
  settings
}) => {
  const screenReaderEnabled = use_is_screen_reader_enabled_default();
  if (!diffContent || typeof diffContent !== "string") {
    return /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(Text, { color: theme.status.warning, children: "No diff content." });
  }
  const parsedLines = parseDiffWithLineNumbers(diffContent);
  if (parsedLines.length === 0) {
    return /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(
      Box_default,
      {
        borderStyle: "round",
        borderColor: theme.border.default,
        padding: 1,
        children: /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(Text, { dimColor: true, children: "No changes detected." })
      }
    );
  }
  if (screenReaderEnabled) {
    return /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(Box_default, { flexDirection: "column", children: parsedLines.map((line, index) => /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)(Text, { children: [
      line.type,
      ": ",
      line.content
    ] }, index)) });
  }
  const isNewFile = parsedLines.every(
    (line) => line.type === "add" || line.type === "hunk" || line.type === "other" || line.content.startsWith("diff --git") || line.content.startsWith("new file mode")
  );
  let renderedOutput;
  if (isNewFile) {
    const addedContent = parsedLines.filter((line) => line.type === "add").map((line) => line.content).join("\n");
    const fileExtension = filename?.split(".").pop() || null;
    const language = fileExtension ? getLanguageFromExtension(fileExtension) : null;
    renderedOutput = colorizeCode(
      addedContent,
      language,
      availableTerminalHeight,
      contentWidth,
      theme2,
      settings,
      tabWidth
    );
  } else {
    renderedOutput = renderDiffContent(
      parsedLines,
      filename,
      tabWidth,
      availableTerminalHeight,
      contentWidth,
      settings
    );
  }
  return renderedOutput;
}, "DiffRenderer");
var renderDiffContent = /* @__PURE__ */ __name((parsedLines, filename, tabWidth = DEFAULT_TAB_WIDTH, availableTerminalHeight, contentWidth, settings) => {
  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_runtime8.jsx)(
      Box_default,
      {
        borderStyle: "round",
        borderColor: theme.border.default,
        padding: 1,
        children: /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(Text, { dimColor: true, children: "No changes detected." })
      }
    );
  }
  const showLineNumbers = settings?.merged.ui?.showLineNumbers ?? true;
  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 = filename?.split(".").pop() || null;
  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;
  }
  const key = filename ? `diff-box-${filename}` : `diff-box-${crypto2.createHash("sha1").update(JSON.stringify(parsedLines)).digest("hex")}`;
  let lastLineNumber = null;
  const MAX_CONTEXT_LINES_WITHOUT_GAP = 5;
  return /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(
    MaxSizedBox,
    {
      maxHeight: availableTerminalHeight,
      maxWidth: contentWidth,
      children: 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_runtime8.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(Text, { wrap: "truncate", color: theme.text.secondary, children: "\u2550".repeat(contentWidth) }) }, `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);
        acc.push(
          /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)(Box_default, { flexDirection: "row", children: [
            showLineNumbers && /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)(
              Text,
              {
                color: theme.text.secondary,
                backgroundColor: line.type === "add" ? theme.background.diff.added : line.type === "del" ? theme.background.diff.removed : void 0,
                children: [
                  gutterNumStr.padStart(gutterWidth),
                  " "
                ]
              }
            ),
            line.type === "context" ? /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)(import_jsx_runtime8.Fragment, { children: [
              /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)(Text, { children: [
                prefixSymbol,
                " "
              ] }),
              /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(Text, { wrap: "wrap", children: colorizeLine(displayContent, language) })
            ] }) : /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)(
              Text,
              {
                backgroundColor: line.type === "add" ? theme.background.diff.added : theme.background.diff.removed,
                wrap: "wrap",
                children: [
                  /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(
                    Text,
                    {
                      color: line.type === "add" ? theme.status.success : theme.status.error,
                      children: prefixSymbol
                    }
                  ),
                  " ",
                  colorizeLine(displayContent, language)
                ]
              }
            )
          ] }, lineKey)
        );
        return acc;
      }, [])
    },
    key
  );
}, "renderDiffContent");
var getLanguageFromExtension = /* @__PURE__ */ __name((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;
}, "getLanguageFromExtension");

// packages/cli/src/ui/components/AnsiOutput.tsx
init_esbuild_shims();
var import_jsx_runtime9 = __toESM(require_jsx_runtime(), 1);
var DEFAULT_HEIGHT = 24;
var AnsiOutputText = /* @__PURE__ */ __name(({
  data,
  availableTerminalHeight,
  maxWidth
}) => {
  const lastLines = data.slice(
    -(availableTerminalHeight && availableTerminalHeight > 0 ? availableTerminalHeight : DEFAULT_HEIGHT)
  );
  return /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(MaxSizedBox, { maxHeight: availableTerminalHeight, maxWidth, children: lastLines.map((line, lineIndex) => /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(Box_default, { children: line.length > 0 ? line.map((token, tokenIndex) => /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
    Text,
    {
      color: token.inverse ? token.bg : token.fg,
      backgroundColor: token.inverse ? token.fg : token.bg,
      dimColor: token.dim,
      bold: token.bold,
      italic: token.italic,
      underline: token.underline,
      wrap: "truncate",
      children: token.text
    },
    tokenIndex
  )) : null }, lineIndex)) });
}, "AnsiOutputText");
var ShellStatsBar = /* @__PURE__ */ __name(({
  totalLines,
  totalBytes,
  displayHeight = DEFAULT_HEIGHT
}) => {
  const parts = [];
  if (totalLines && totalLines > displayHeight) {
    parts.push(`+${totalLines - displayHeight} lines`);
  }
  if (totalBytes && totalBytes > 0) {
    parts.push(formatMemoryUsage(totalBytes));
  }
  if (parts.length === 0) return null;
  return /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(Box_default, { flexDirection: "row", gap: 1, children: parts.map((part, i) => /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(Text, { color: theme.text.secondary, children: part }, i)) });
}, "ShellStatsBar");

// packages/cli/src/ui/components/TodoDisplay.tsx
init_esbuild_shims();
var import_jsx_runtime10 = __toESM(require_jsx_runtime(), 1);
var STATUS_ICONS = {
  pending: "\u25CB",
  in_progress: "\u25D0",
  completed: "\u25CF"
};
var TodoDisplay = /* @__PURE__ */ __name(({ todos }) => {
  if (!todos || todos.length === 0) {
    return null;
  }
  return /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(Box_default, { flexDirection: "column", children: todos.map((todo) => /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(TodoItemRow, { todo }, todo.id)) });
}, "TodoDisplay");
var TodoItemRow = /* @__PURE__ */ __name(({ todo }) => {
  const statusIcon = STATUS_ICONS[todo.status];
  const isCompleted = todo.status === "completed";
  const isInProgress = todo.status === "in_progress";
  const itemColor = isCompleted ? Colors.Foreground : isInProgress ? Colors.AccentGreen : Colors.Foreground;
  return /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)(Box_default, { flexDirection: "row", minHeight: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(Box_default, { width: 3, children: /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(Text, { color: itemColor, children: statusIcon }) }),
    /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(Box_default, { flexGrow: 1, children: /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(Text, { color: itemColor, strikethrough: isCompleted, wrap: "wrap", children: todo.content }) })
  ] });
}, "TodoItemRow");

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

// packages/cli/src/ui/components/shared/RadioButtonSelect.tsx
init_esbuild_shims();

// packages/cli/src/ui/components/shared/BaseSelectionList.tsx
init_esbuild_shims();
var import_react11 = __toESM(require_react(), 1);

// packages/cli/src/ui/hooks/useSelectionList.ts
init_esbuild_shims();
var import_react10 = __toESM(require_react(), 1);

// packages/cli/src/ui/keyMatchers.ts
init_esbuild_shims();

// packages/cli/src/config/keyBindings.ts
init_esbuild_shims();
var Command = /* @__PURE__ */ ((Command2) => {
  Command2["RETURN"] = "return";
  Command2["ESCAPE"] = "escape";
  Command2["HOME"] = "home";
  Command2["END"] = "end";
  Command2["KILL_LINE_RIGHT"] = "killLineRight";
  Command2["KILL_LINE_LEFT"] = "killLineLeft";
  Command2["CLEAR_INPUT"] = "clearInput";
  Command2["DELETE_WORD_BACKWARD"] = "deleteWordBackward";
  Command2["CLEAR_SCREEN"] = "clearScreen";
  Command2["HISTORY_UP"] = "historyUp";
  Command2["HISTORY_DOWN"] = "historyDown";
  Command2["NAVIGATION_UP"] = "navigationUp";
  Command2["NAVIGATION_DOWN"] = "navigationDown";
  Command2["SELECTION_UP"] = "selectionUp";
  Command2["SELECTION_DOWN"] = "selectionDown";
  Command2["ACCEPT_SUGGESTION"] = "acceptSuggestion";
  Command2["COMPLETION_UP"] = "completionUp";
  Command2["COMPLETION_DOWN"] = "completionDown";
  Command2["SUBMIT"] = "submit";
  Command2["NEWLINE"] = "newline";
  Command2["VOICE_PUSH_TO_TALK"] = "voicePushToTalk";
  Command2["OPEN_EXTERNAL_EDITOR"] = "openExternalEditor";
  Command2["PASTE_CLIPBOARD_IMAGE"] = "pasteClipboardImage";
  Command2["TOGGLE_TOOL_DESCRIPTIONS"] = "toggleToolDescriptions";
  Command2["TOGGLE_IDE_CONTEXT_DETAIL"] = "toggleIDEContextDetail";
  Command2["QUIT"] = "quit";
  Command2["EXIT"] = "exit";
  Command2["SHOW_MORE_LINES"] = "showMoreLines";
  Command2["RETRY_LAST"] = "retryLast";
  Command2["TOGGLE_COMPACT_MODE"] = "toggleCompactMode";
  Command2["TOGGLE_RENDER_MODE"] = "toggleRenderMode";
  Command2["PROMOTE_SHELL_TO_BACKGROUND"] = "promoteShellToBackground";
  Command2["REVERSE_SEARCH"] = "reverseSearch";
  Command2["SUBMIT_REVERSE_SEARCH"] = "submitReverseSearch";
  Command2["ACCEPT_SUGGESTION_REVERSE_SEARCH"] = "acceptSuggestionReverseSearch";
  Command2["TOGGLE_SHELL_INPUT_FOCUS"] = "toggleShellInputFocus";
  Command2["EXPAND_SUGGESTION"] = "expandSuggestion";
  Command2["COLLAPSE_SUGGESTION"] = "collapseSuggestion";
  Command2["TOGGLE_THINKING_EXPANDED"] = "toggleThinkingExpanded";
  Command2["SCROLL_UP"] = "scrollUp";
  Command2["SCROLL_DOWN"] = "scrollDown";
  Command2["PAGE_UP"] = "pageUp";
  Command2["PAGE_DOWN"] = "pageDown";
  Command2["SCROLL_HOME"] = "scrollHome";
  Command2["SCROLL_END"] = "scrollEnd";
  return Command2;
})(Command || {});
var defaultKeyBindings = {
  // Basic bindings
  ["return" /* RETURN */]: [{ key: "return" }],
  ["escape" /* ESCAPE */]: [{ key: "escape" }],
  // Cursor movement
  ["home" /* HOME */]: [{ key: "a", ctrl: true }],
  ["end" /* END */]: [{ key: "e", ctrl: true }],
  // Text deletion
  ["killLineRight" /* KILL_LINE_RIGHT */]: [{ key: "k", ctrl: true }],
  ["killLineLeft" /* KILL_LINE_LEFT */]: [{ key: "u", ctrl: true }],
  ["clearInput" /* CLEAR_INPUT */]: [{ key: "c", ctrl: true }],
  // Added command (meta/alt/option) for mac compatibility
  ["deleteWordBackward" /* DELETE_WORD_BACKWARD */]: [
    { key: "backspace", ctrl: true },
    { key: "backspace", command: true },
    // MinTTY (Git Bash on Windows) emits the byte \x1f (ASCII Unit
    // Separator, rendered as "^_" by `cat -v`) for Ctrl+Backspace under
    // its standard Ctrl-modifies-meta-keys convention. The same byte is
    // the historical Ctrl-mapping of the Unit Separator on traditional
    // ANSI/VT terminals (Ctrl+_ and Ctrl+/ also emit it), but qwen-code
    // doesn't bind those keystrokes elsewhere so this entry is additive
    // and non-conflicting on every platform.
    { sequence: "" }
  ],
  // Screen control
  ["clearScreen" /* CLEAR_SCREEN */]: [{ key: "l", ctrl: true }],
  // History navigation
  ["historyUp" /* HISTORY_UP */]: [{ key: "p", ctrl: true }],
  ["historyDown" /* HISTORY_DOWN */]: [{ key: "n", ctrl: true }],
  ["navigationUp" /* NAVIGATION_UP */]: [{ key: "up", shift: false }],
  ["navigationDown" /* NAVIGATION_DOWN */]: [{ key: "down", shift: false }],
  // Selection-list nav: arrows + k/j + Ctrl+P/Ctrl+N
  // ctrl: false on bare k/j skips Ctrl+K and Ctrl+J
  ["selectionUp" /* SELECTION_UP */]: [
    { key: "up", shift: false },
    { key: "k", ctrl: false },
    { key: "p", ctrl: true }
  ],
  ["selectionDown" /* SELECTION_DOWN */]: [
    { key: "down", shift: false },
    { key: "j", ctrl: false },
    { key: "n", ctrl: true }
  ],
  // Auto-completion
  ["acceptSuggestion" /* ACCEPT_SUGGESTION */]: [{ key: "tab" }, { key: "return", ctrl: false }],
  // Completion navigation: arrows + readline/Vim-style Ctrl+P/Ctrl+N
  ["completionUp" /* COMPLETION_UP */]: [
    { key: "up", shift: false },
    { key: "p", ctrl: true }
  ],
  ["completionDown" /* COMPLETION_DOWN */]: [
    { key: "down", shift: false },
    { key: "n", ctrl: true }
  ],
  // Text input
  // Must also exclude shift to allow shift+enter for newline
  ["submit" /* SUBMIT */]: [
    {
      key: "return",
      ctrl: false,
      command: false,
      paste: false,
      shift: false
    }
  ],
  // Split into multiple data-driven bindings
  // Now also includes shift+enter for multi-line input
  ["newline" /* NEWLINE */]: [
    { key: "return", ctrl: true },
    { key: "return", command: true },
    { key: "return", paste: true },
    { key: "return", shift: true },
    { key: "j", ctrl: true }
  ],
  ["voicePushToTalk" /* VOICE_PUSH_TO_TALK */]: [{ key: "space", ctrl: false, meta: false }],
  // External tools
  ["openExternalEditor" /* OPEN_EXTERNAL_EDITOR */]: [
    { key: "x", ctrl: true },
    { sequence: "", ctrl: true }
  ],
  ["pasteClipboardImage" /* PASTE_CLIPBOARD_IMAGE */]: process.platform === "win32" ? [
    { key: "v", command: true },
    { key: "v", meta: true }
  ] : [
    { key: "v", ctrl: true },
    { key: "v", command: true }
  ],
  // App level bindings
  ["toggleToolDescriptions" /* TOGGLE_TOOL_DESCRIPTIONS */]: [{ key: "t", ctrl: true }],
  ["toggleIDEContextDetail" /* TOGGLE_IDE_CONTEXT_DETAIL */]: [{ key: "g", ctrl: true }],
  ["quit" /* QUIT */]: [{ key: "c", ctrl: true }],
  ["exit" /* EXIT */]: [{ key: "d", ctrl: true }],
  ["showMoreLines" /* SHOW_MORE_LINES */]: [{ key: "s", ctrl: true }],
  ["retryLast" /* RETRY_LAST */]: [{ key: "y", ctrl: true }],
  ["toggleCompactMode" /* TOGGLE_COMPACT_MODE */]: [{ key: "o", ctrl: true }],
  ["toggleRenderMode" /* TOGGLE_RENDER_MODE */]: [{ key: "m", meta: true }],
  ["promoteShellToBackground" /* PROMOTE_SHELL_TO_BACKGROUND */]: [{ key: "b", ctrl: true }],
  // Shell commands
  ["reverseSearch" /* REVERSE_SEARCH */]: [{ key: "r", ctrl: true }],
  // Note: original logic ONLY checked ctrl=false, ignored meta/shift/paste
  ["submitReverseSearch" /* SUBMIT_REVERSE_SEARCH */]: [{ key: "return", ctrl: false }],
  ["acceptSuggestionReverseSearch" /* ACCEPT_SUGGESTION_REVERSE_SEARCH */]: [{ key: "tab" }],
  ["toggleShellInputFocus" /* TOGGLE_SHELL_INPUT_FOCUS */]: [{ key: "f", ctrl: true }],
  // Suggestion expansion
  ["expandSuggestion" /* EXPAND_SUGGESTION */]: [{ key: "right" }],
  ["collapseSuggestion" /* COLLAPSE_SUGGESTION */]: [{ key: "left" }],
  // Thinking expansion
  ["toggleThinkingExpanded" /* TOGGLE_THINKING_EXPANDED */]: [{ key: "t", meta: true }],
  // Scroll commands
  ["scrollUp" /* SCROLL_UP */]: [{ key: "up", shift: true }],
  ["scrollDown" /* SCROLL_DOWN */]: [{ key: "down", shift: true }],
  ["pageUp" /* PAGE_UP */]: [{ key: "pageup" }],
  ["pageDown" /* PAGE_DOWN */]: [{ key: "pagedown" }],
  ["scrollHome" /* SCROLL_HOME */]: [{ key: "home", ctrl: true }],
  ["scrollEnd" /* SCROLL_END */]: [{ key: "end", ctrl: true }]
};

// packages/cli/src/ui/keyMatchers.ts
function matchKeyBinding(keyBinding, key) {
  let keyMatches = false;
  if (keyBinding.key !== void 0) {
    keyMatches = keyBinding.key === key.name;
  } else if (keyBinding.sequence !== void 0) {
    keyMatches = keyBinding.sequence === key.sequence;
  } else {
    return false;
  }
  if (!keyMatches) {
    return false;
  }
  if (keyBinding.ctrl !== void 0 && !!key.ctrl !== keyBinding.ctrl) {
    return false;
  }
  if (keyBinding.shift !== void 0 && !!key.shift !== keyBinding.shift) {
    return false;
  }
  if (keyBinding.command !== void 0 && !!key.meta !== keyBinding.command) {
    return false;
  }
  if (keyBinding.paste !== void 0 && !!key.paste !== keyBinding.paste) {
    return false;
  }
  if (keyBinding.meta !== void 0 && !!key.meta !== keyBinding.meta) {
    return false;
  }
  return true;
}
__name(matchKeyBinding, "matchKeyBinding");
function matchCommand(command, key, config = defaultKeyBindings) {
  const bindings = config[command];
  return bindings.some((binding) => matchKeyBinding(binding, key));
}
__name(matchCommand, "matchCommand");
function createKeyMatchers(config = defaultKeyBindings) {
  const matchers = {};
  for (const command of Object.values(Command)) {
    matchers[command] = (key) => matchCommand(command, key, config);
  }
  return matchers;
}
__name(createKeyMatchers, "createKeyMatchers");
var keyMatchers = createKeyMatchers(defaultKeyBindings);

// packages/cli/src/ui/hooks/useSelectionList.ts
var debugLogger3 = createDebugLogger("SELECTION_LIST");
var NUMBER_INPUT_TIMEOUT_MS = 1e3;
var findNextValidIndex = /* @__PURE__ */ __name((currentIndex, direction, items) => {
  const len = items.length;
  if (len === 0) return currentIndex;
  let nextIndex = currentIndex;
  const step = direction === "down" ? 1 : -1;
  for (let i = 0; i < len; i++) {
    nextIndex = (nextIndex + step + len) % len;
    if (!items[nextIndex]?.disabled) {
      return nextIndex;
    }
  }
  return currentIndex;
}, "findNextValidIndex");
var computeInitialIndex = /* @__PURE__ */ __name((initialIndex, items, initialKey) => {
  if (items.length === 0) {
    return 0;
  }
  if (initialKey !== void 0) {
    for (let i = 0; i < items.length; i++) {
      if (items[i].key === initialKey && !items[i].disabled) {
        return i;
      }
    }
  }
  let targetIndex = initialIndex;
  if (targetIndex < 0 || targetIndex >= items.length) {
    targetIndex = 0;
  }
  if (items[targetIndex]?.disabled) {
    const nextValid = findNextValidIndex(targetIndex, "down", items);
    targetIndex = nextValid;
  }
  return targetIndex;
}, "computeInitialIndex");
var areItemsStructurallyEqual = /* @__PURE__ */ __name((a, b) => {
  if (a === b) {
    return true;
  }
  if (a.length !== b.length) {
    return false;
  }
  for (let i = 0; i < a.length; i++) {
    if (a[i]?.key !== b[i]?.key || a[i]?.disabled !== b[i]?.disabled) {
      return false;
    }
  }
  return true;
}, "areItemsStructurallyEqual");
function selectionListReducer(state, action) {
  switch (action.type) {
    case "SET_ACTIVE_INDEX": {
      const { index, items } = action.payload;
      if (index === state.activeIndex) {
        return state;
      }
      if (index >= 0 && index < items.length) {
        return { ...state, activeIndex: index, pendingHighlight: true };
      }
      return state;
    }
    case "MOVE_UP": {
      const { items } = action.payload;
      const newIndex = findNextValidIndex(state.activeIndex, "up", items);
      if (newIndex !== state.activeIndex) {
        return { ...state, activeIndex: newIndex, pendingHighlight: true };
      }
      return state;
    }
    case "MOVE_DOWN": {
      const { items } = action.payload;
      const newIndex = findNextValidIndex(state.activeIndex, "down", items);
      if (newIndex !== state.activeIndex) {
        return { ...state, activeIndex: newIndex, pendingHighlight: true };
      }
      return state;
    }
    case "SELECT_CURRENT": {
      return { ...state, pendingSelect: true };
    }
    case "INITIALIZE": {
      const { initialIndex, items } = action.payload;
      const initialIndexChanged = initialIndex !== state.initialIndex;
      const activeKey = !initialIndexChanged && state.activeIndex !== state.initialIndex ? state.items[state.activeIndex]?.key : void 0;
      const targetIndex = computeInitialIndex(initialIndex, items, activeKey);
      const itemsStructurallyEqual = areItemsStructurallyEqual(
        items,
        state.items
      );
      if (!initialIndexChanged && targetIndex === state.activeIndex && itemsStructurallyEqual) {
        return state;
      }
      return {
        ...state,
        items: itemsStructurallyEqual ? state.items : items,
        activeIndex: targetIndex,
        initialIndex,
        pendingHighlight: false
      };
    }
    case "CLEAR_PENDING_FLAGS": {
      return {
        ...state,
        pendingHighlight: false,
        pendingSelect: false
      };
    }
    default: {
      const exhaustiveCheck = action;
      debugLogger3.error(`Unknown selection list action: ${exhaustiveCheck}`);
      return state;
    }
  }
}
__name(selectionListReducer, "selectionListReducer");
function useSelectionList({
  items,
  initialIndex = 0,
  onSelect,
  onHighlight,
  isFocused = true,
  showNumbers = false,
  disableVimNav = false
}) {
  const [state, dispatch] = (0, import_react10.useReducer)(selectionListReducer, {
    activeIndex: computeInitialIndex(initialIndex, items),
    initialIndex,
    pendingHighlight: false,
    pendingSelect: false,
    items
  });
  const numberInputRef = (0, import_react10.useRef)("");
  const numberInputTimer = (0, import_react10.useRef)(null);
  (0, import_react10.useEffect)(() => {
    dispatch({ type: "INITIALIZE", payload: { initialIndex, items } });
  }, [initialIndex, items]);
  (0, import_react10.useEffect)(() => {
    let needsClear = false;
    if (state.pendingHighlight && items[state.activeIndex]) {
      onHighlight?.(items[state.activeIndex].value);
      needsClear = true;
    }
    if (state.pendingSelect && items[state.activeIndex]) {
      const currentItem = items[state.activeIndex];
      if (currentItem && !currentItem.disabled) {
        onSelect(currentItem.value);
      }
      needsClear = true;
    }
    if (needsClear) {
      dispatch({ type: "CLEAR_PENDING_FLAGS" });
    }
  }, [
    state.pendingHighlight,
    state.pendingSelect,
    state.activeIndex,
    items,
    onHighlight,
    onSelect
  ]);
  (0, import_react10.useEffect)(
    () => () => {
      if (numberInputTimer.current) {
        clearTimeout(numberInputTimer.current);
      }
    },
    []
  );
  useKeypress(
    (key) => {
      const { sequence, name } = key;
      const isNumeric = showNumbers && /^[0-9]$/.test(sequence);
      if (!isNumeric && numberInputTimer.current) {
        clearTimeout(numberInputTimer.current);
        numberInputRef.current = "";
      }
      if (keyMatchers["selectionUp" /* SELECTION_UP */](key)) {
        if (disableVimNav && key.name === "k" && !key.ctrl) {
        } else {
          dispatch({ type: "MOVE_UP", payload: { items } });
          return;
        }
      }
      if (keyMatchers["selectionDown" /* SELECTION_DOWN */](key)) {
        if (disableVimNav && key.name === "j" && !key.ctrl) {
        } else {
          dispatch({ type: "MOVE_DOWN", payload: { items } });
          return;
        }
      }
      if (name === "return") {
        dispatch({ type: "SELECT_CURRENT", payload: { items } });
        return;
      }
      if (isNumeric) {
        if (numberInputTimer.current) {
          clearTimeout(numberInputTimer.current);
        }
        const newNumberInput = numberInputRef.current + sequence;
        numberInputRef.current = newNumberInput;
        const targetIndex = Number.parseInt(newNumberInput, 10) - 1;
        if (newNumberInput === "0") {
          numberInputTimer.current = setTimeout(() => {
            numberInputRef.current = "";
          }, NUMBER_INPUT_TIMEOUT_MS);
          return;
        }
        if (targetIndex >= 0 && targetIndex < items.length) {
          dispatch({
            type: "SET_ACTIVE_INDEX",
            payload: { index: targetIndex, items }
          });
          const potentialNextNumber = Number.parseInt(newNumberInput + "0", 10);
          if (potentialNextNumber > items.length) {
            dispatch({
              type: "SELECT_CURRENT",
              payload: { items }
            });
            numberInputRef.current = "";
          } else {
            numberInputTimer.current = setTimeout(() => {
              dispatch({
                type: "SELECT_CURRENT",
                payload: { items }
              });
              numberInputRef.current = "";
            }, NUMBER_INPUT_TIMEOUT_MS);
          }
        } else {
          numberInputRef.current = "";
        }
      }
    },
    { isActive: !!(isFocused && items.length > 0) }
  );
  const setActiveIndex = /* @__PURE__ */ __name((index) => {
    dispatch({
      type: "SET_ACTIVE_INDEX",
      payload: { index, items }
    });
  }, "setActiveIndex");
  const selectIndex = /* @__PURE__ */ __name((index) => {
    if (items[index]?.disabled) return;
    dispatch({ type: "SET_ACTIVE_INDEX", payload: { index, items } });
    dispatch({ type: "SELECT_CURRENT", payload: { items } });
  }, "selectIndex");
  return {
    activeIndex: state.activeIndex,
    setActiveIndex,
    selectIndex
  };
}
__name(useSelectionList, "useSelectionList");

// packages/cli/src/ui/components/shared/BaseSelectionList.tsx
var import_jsx_runtime11 = __toESM(require_jsx_runtime(), 1);
function getScrollOffsetForIndex(activeIndex, itemCount, maxItemsToShow) {
  return Math.max(
    0,
    Math.min(activeIndex - maxItemsToShow + 1, itemCount - maxItemsToShow)
  );
}
__name(getScrollOffsetForIndex, "getScrollOffsetForIndex");
function BaseSelectionList({
  items,
  initialIndex = 0,
  onSelect,
  onHighlight,
  isFocused = true,
  showNumbers = true,
  showScrollArrows = false,
  maxItemsToShow = 10,
  itemGap = 0,
  renderItem
}) {
  const { activeIndex, setActiveIndex, selectIndex } = useSelectionList({
    items,
    initialIndex,
    onSelect,
    onHighlight,
    isFocused,
    showNumbers
  });
  const [scrollOffset, setScrollOffset] = (0, import_react11.useState)(
    () => getScrollOffsetForIndex(activeIndex, items.length, maxItemsToShow)
  );
  (0, import_react11.useEffect)(() => {
    const newScrollOffset = getScrollOffsetForIndex(
      activeIndex,
      items.length,
      maxItemsToShow
    );
    if (activeIndex < scrollOffset) {
      setScrollOffset(activeIndex);
    } else if (activeIndex >= scrollOffset + maxItemsToShow) {
      setScrollOffset(newScrollOffset);
    }
  }, [activeIndex, items.length, scrollOffset, maxItemsToShow]);
  const settings = (0, import_react11.useContext)(SettingsContext);
  const mouseEnabled = !!settings?.merged.ui?.useTerminalBuffer;
  const containerRef = (0, import_react11.useRef)(null);
  const itemRefs = (0, import_react11.useRef)([]);
  const visibleItems = items.slice(scrollOffset, scrollOffset + maxItemsToShow);
  const numberColumnWidth = String(items.length).length;
  return /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)(Box_default, { ref: containerRef, flexDirection: "column", gap: itemGap, children: [
    mouseEnabled && isFocused && items.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
      RowMouseController,
      {
        containerRef,
        itemRefs,
        scrollOffset,
        isDisabled: (index) => !!items[index]?.disabled,
        onHoverIndex: setActiveIndex,
        onSelectIndex: selectIndex
      }
    ),
    showScrollArrows && /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
      Text,
      {
        color: scrollOffset > 0 ? theme.text.primary : theme.text.secondary,
        children: "\u25B2"
      }
    ),
    visibleItems.map((item, index) => {
      const itemIndex = scrollOffset + index;
      const isSelected = activeIndex === itemIndex;
      let titleColor = theme.text.primary;
      let numberColor = theme.text.primary;
      if (isSelected) {
        titleColor = theme.status.success;
        numberColor = theme.status.success;
      } else if (item.disabled) {
        titleColor = theme.text.secondary;
        numberColor = theme.text.secondary;
      }
      if (!isFocused && !item.disabled) {
        numberColor = theme.text.secondary;
      }
      if (!showNumbers) {
        numberColor = theme.text.secondary;
      }
      const itemNumberText = `${String(itemIndex + 1).padStart(
        numberColumnWidth
      )}.`;
      return /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)(
        Box_default,
        {
          alignItems: "flex-start",
          ref: (node) => {
            itemRefs.current[index] = node;
          },
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(Box_default, { minWidth: 2, flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
              Text,
              {
                color: isSelected ? theme.status.success : theme.text.primary,
                "aria-hidden": true,
                children: isSelected ? "\u203A" : " "
              }
            ) }),
            showNumbers && /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
              Box_default,
              {
                marginRight: 1,
                flexShrink: 0,
                minWidth: itemNumberText.length,
                "aria-state": { checked: isSelected },
                children: /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(Text, { color: numberColor, children: itemNumberText })
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(Box_default, { flexGrow: 1, children: renderItem(item, {
              isSelected,
              titleColor,
              numberColor
            }) })
          ]
        },
        item.key
      );
    }),
    showScrollArrows && /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
      Text,
      {
        color: scrollOffset + maxItemsToShow < items.length ? theme.text.primary : theme.text.secondary,
        children: "\u25BC"
      }
    )
  ] });
}
__name(BaseSelectionList, "BaseSelectionList");

// packages/cli/src/ui/components/shared/RadioButtonSelect.tsx
var import_jsx_runtime12 = __toESM(require_jsx_runtime(), 1);
function RadioButtonSelect({
  items,
  initialIndex = 0,
  onSelect,
  onHighlight,
  isFocused = true,
  showScrollArrows = false,
  maxItemsToShow = 10,
  showNumbers = true
}) {
  return /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
    BaseSelectionList,
    {
      items,
      initialIndex,
      onSelect,
      onHighlight,
      isFocused,
      showNumbers,
      showScrollArrows,
      maxItemsToShow,
      renderItem: (item, { titleColor }) => {
        if (item.themeNameDisplay && item.themeTypeDisplay) {
          return /* @__PURE__ */ (0, import_jsx_runtime12.jsxs)(Text, { color: titleColor, wrap: "truncate", children: [
            item.themeNameDisplay,
            " ",
            /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(Text, { color: theme.text.secondary, children: item.themeTypeDisplay })
          ] }, item.key);
        }
        return /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(Text, { color: titleColor, wrap: "truncate", children: item.label });
      }
    }
  );
}
__name(RadioButtonSelect, "RadioButtonSelect");

// packages/cli/src/ui/components/messages/AskUserQuestionDialog.tsx
init_esbuild_shims();
var import_react15 = __toESM(require_react(), 1);

// packages/cli/src/ui/components/shared/TextInput.tsx
init_esbuild_shims();

// packages/cli/src/ui/components/shared/text-buffer.ts
init_esbuild_shims();
var import_react12 = __toESM(require_react(), 1);
import { spawnSync as spawnSync2 } from "node:child_process";
import fs2 from "node:fs";
import os2 from "node:os";
import pathMod from "node:path";

// packages/cli/src/ui/components/shared/vim-buffer-actions.ts
init_esbuild_shims();

// packages/cli/src/utils/checks.ts
init_esbuild_shims();
function assumeExhaustive(_value) {
}
__name(assumeExhaustive, "assumeExhaustive");
function checkExhaustive(value, msg = `unexpected value ${value}!`) {
  assumeExhaustive(value);
  throw new Error(msg);
}
__name(checkExhaustive, "checkExhaustive");

// packages/cli/src/ui/components/shared/vim-buffer-actions.ts
function isAtEndOfBaseWord(lineCodePoints, col) {
  if (!isWordCharStrict(lineCodePoints[col])) return false;
  let i = col + 1;
  while (i < lineCodePoints.length && isCombiningMark(lineCodePoints[i])) {
    i++;
  }
  return i >= lineCodePoints.length || !isWordCharStrict(lineCodePoints[i]);
}
__name(isAtEndOfBaseWord, "isAtEndOfBaseWord");
function handleVimAction(state, action) {
  const { lines, cursorRow, cursorCol } = state;
  switch (action.type) {
    case "vim_delete_word_forward":
    case "vim_change_word_forward": {
      const { count } = action.payload;
      let endRow = cursorRow;
      let endCol = cursorCol;
      for (let i = 0; i < count; i++) {
        const nextWord = findNextWordAcrossLines(lines, endRow, endCol, true);
        if (nextWord) {
          endRow = nextWord.row;
          endCol = nextWord.col;
        } else {
          const currentLine = lines[endRow] || "";
          const wordEnd = findWordEndInLine(currentLine, endCol);
          if (wordEnd !== null) {
            endCol = wordEnd + 1;
          } else {
            endCol = cpLen(currentLine);
          }
          break;
        }
      }
      if (endRow !== cursorRow || endCol !== cursorCol) {
        const nextState = pushUndo(state);
        return replaceRangeInternal(
          nextState,
          cursorRow,
          cursorCol,
          endRow,
          endCol,
          ""
        );
      }
      return state;
    }
    case "vim_delete_word_backward":
    case "vim_change_word_backward": {
      const { count } = action.payload;
      let startRow = cursorRow;
      let startCol = cursorCol;
      for (let i = 0; i < count; i++) {
        const prevWord = findPrevWordAcrossLines(lines, startRow, startCol);
        if (prevWord) {
          startRow = prevWord.row;
          startCol = prevWord.col;
        } else {
          break;
        }
      }
      if (startRow !== cursorRow || startCol !== cursorCol) {
        const nextState = pushUndo(state);
        return replaceRangeInternal(
          nextState,
          startRow,
          startCol,
          cursorRow,
          cursorCol,
          ""
        );
      }
      return state;
    }
    case "vim_delete_word_end":
    case "vim_change_word_end": {
      const { count } = action.payload;
      let row = cursorRow;
      let col = cursorCol;
      let endRow = cursorRow;
      let endCol = cursorCol;
      for (let i = 0; i < count; i++) {
        const wordEnd = findNextWordAcrossLines(lines, row, col, false);
        if (wordEnd) {
          endRow = wordEnd.row;
          endCol = wordEnd.col + 1;
          if (i < count - 1) {
            const nextWord = findNextWordAcrossLines(
              lines,
              wordEnd.row,
              wordEnd.col + 1,
              true
            );
            if (nextWord) {
              row = nextWord.row;
              col = nextWord.col;
            } else {
              break;
            }
          }
        } else {
          break;
        }
      }
      if (endRow < lines.length) {
        const lineLen = cpLen(lines[endRow] || "");
        endCol = Math.min(endCol, lineLen);
      }
      if (endRow !== cursorRow || endCol !== cursorCol) {
        const nextState = pushUndo(state);
        return replaceRangeInternal(
          nextState,
          cursorRow,
          cursorCol,
          endRow,
          endCol,
          ""
        );
      }
      return state;
    }
    case "vim_delete_line": {
      const { count } = action.payload;
      if (lines.length === 0) return state;
      const linesToDelete = Math.min(count, lines.length - cursorRow);
      const totalLines = lines.length;
      if (totalLines === 1 || linesToDelete >= totalLines) {
        const nextState2 = pushUndo(state);
        return {
          ...nextState2,
          lines: [""],
          cursorRow: 0,
          cursorCol: 0,
          preferredCol: null
        };
      }
      const nextState = pushUndo(state);
      const newLines = [...nextState.lines];
      newLines.splice(cursorRow, linesToDelete);
      const newCursorRow = Math.min(cursorRow, newLines.length - 1);
      const newCursorCol = 0;
      return {
        ...nextState,
        lines: newLines,
        cursorRow: newCursorRow,
        cursorCol: newCursorCol,
        preferredCol: null
      };
    }
    case "vim_change_line": {
      const { count } = action.payload;
      if (lines.length === 0) return state;
      const linesToChange = Math.min(count, lines.length - cursorRow);
      const nextState = pushUndo(state);
      const { startOffset, endOffset } = getLineRangeOffsets(
        cursorRow,
        linesToChange,
        nextState.lines
      );
      const { startRow, startCol, endRow, endCol } = getPositionFromOffsets(
        startOffset,
        endOffset,
        nextState.lines
      );
      return replaceRangeInternal(
        nextState,
        startRow,
        startCol,
        endRow,
        endCol,
        ""
      );
    }
    case "vim_delete_to_end_of_line":
    case "vim_change_to_end_of_line": {
      const currentLine = lines[cursorRow] || "";
      if (cursorCol < cpLen(currentLine)) {
        const nextState = pushUndo(state);
        return replaceRangeInternal(
          nextState,
          cursorRow,
          cursorCol,
          cursorRow,
          cpLen(currentLine),
          ""
        );
      }
      return state;
    }
    case "vim_change_movement": {
      const { movement, count } = action.payload;
      const totalLines = lines.length;
      switch (movement) {
        case "h": {
          const startCol = Math.max(0, cursorCol - count);
          return replaceRangeInternal(
            pushUndo(state),
            cursorRow,
            startCol,
            cursorRow,
            cursorCol,
            ""
          );
        }
        case "j": {
          const linesToChange = Math.min(count + 1, totalLines - cursorRow);
          if (linesToChange > 0) {
            if (totalLines === 1) {
              const currentLine = state.lines[0] || "";
              return replaceRangeInternal(
                pushUndo(state),
                0,
                0,
                0,
                cpLen(currentLine),
                ""
              );
            } else {
              const nextState = pushUndo(state);
              const { startOffset, endOffset } = getLineRangeOffsets(
                cursorRow,
                linesToChange,
                nextState.lines
              );
              const { startRow, startCol, endRow, endCol } = getPositionFromOffsets(startOffset, endOffset, nextState.lines);
              return replaceRangeInternal(
                nextState,
                startRow,
                startCol,
                endRow,
                endCol,
                ""
              );
            }
          }
          return state;
        }
        case "k": {
          const upLines = Math.min(count + 1, cursorRow + 1);
          if (upLines > 0) {
            if (state.lines.length === 1) {
              const currentLine = state.lines[0] || "";
              return replaceRangeInternal(
                pushUndo(state),
                0,
                0,
                0,
                cpLen(currentLine),
                ""
              );
            } else {
              const startRow = Math.max(0, cursorRow - count);
              const linesToChange = cursorRow - startRow + 1;
              const nextState = pushUndo(state);
              const { startOffset, endOffset } = getLineRangeOffsets(
                startRow,
                linesToChange,
                nextState.lines
              );
              const {
                startRow: newStartRow,
                startCol,
                endRow,
                endCol
              } = getPositionFromOffsets(
                startOffset,
                endOffset,
                nextState.lines
              );
              const resultState = replaceRangeInternal(
                nextState,
                newStartRow,
                startCol,
                endRow,
                endCol,
                ""
              );
              return {
                ...resultState,
                cursorRow: startRow,
                cursorCol: 0
              };
            }
          }
          return state;
        }
        case "l": {
          return replaceRangeInternal(
            pushUndo(state),
            cursorRow,
            cursorCol,
            cursorRow,
            Math.min(cpLen(lines[cursorRow] || ""), cursorCol + count),
            ""
          );
        }
        default:
          return state;
      }
    }
    case "vim_delete_movement": {
      const { movement, count } = action.payload;
      const totalLines = lines.length;
      switch (movement) {
        case "h": {
          const startCol = Math.max(0, cursorCol - count);
          return replaceRangeInternal(
            pushUndo(state),
            cursorRow,
            startCol,
            cursorRow,
            cursorCol,
            ""
          );
        }
        case "j": {
          const linesToDelete = Math.min(count + 1, totalLines - cursorRow);
          if (linesToDelete > 0) {
            if (totalLines === 1) {
              const currentLine = state.lines[0] || "";
              return replaceRangeInternal(
                pushUndo(state),
                0,
                0,
                0,
                cpLen(currentLine),
                ""
              );
            } else {
              const nextState = pushUndo(state);
              const { startOffset, endOffset } = getLineRangeOffsets(
                cursorRow,
                linesToDelete,
                nextState.lines
              );
              const { startRow, startCol, endRow, endCol } = getPositionFromOffsets(startOffset, endOffset, nextState.lines);
              return replaceRangeInternal(
                nextState,
                startRow,
                startCol,
                endRow,
                endCol,
                ""
              );
            }
          }
          return state;
        }
        case "k": {
          const upLines = Math.min(count + 1, cursorRow + 1);
          if (upLines > 0) {
            if (state.lines.length === 1) {
              const currentLine = state.lines[0] || "";
              return replaceRangeInternal(
                pushUndo(state),
                0,
                0,
                0,
                cpLen(currentLine),
                ""
              );
            } else {
              const startRow = Math.max(0, cursorRow - count);
              const linesToDelete = cursorRow - startRow + 1;
              const nextState = pushUndo(state);
              const { startOffset, endOffset } = getLineRangeOffsets(
                startRow,
                linesToDelete,
                nextState.lines
              );
              const {
                startRow: newStartRow,
                startCol,
                endRow,
                endCol
              } = getPositionFromOffsets(
                startOffset,
                endOffset,
                nextState.lines
              );
              const resultState = replaceRangeInternal(
                nextState,
                newStartRow,
                startCol,
                endRow,
                endCol,
                ""
              );
              return {
                ...resultState,
                cursorRow: startRow,
                cursorCol: 0
              };
            }
          }
          return state;
        }
        case "l": {
          return replaceRangeInternal(
            pushUndo(state),
            cursorRow,
            cursorCol,
            cursorRow,
            Math.min(cpLen(lines[cursorRow] || ""), cursorCol + count),
            ""
          );
        }
        default:
          return state;
      }
    }
    case "vim_move_left": {
      const { count } = action.payload;
      const { cursorRow: cursorRow2, cursorCol: cursorCol2, lines: lines2 } = state;
      let newRow = cursorRow2;
      let newCol = cursorCol2;
      for (let i = 0; i < count; i++) {
        if (newCol > 0) {
          newCol--;
        } else if (newRow > 0) {
          newRow--;
          const prevLine = lines2[newRow] || "";
          const prevLineLength = cpLen(prevLine);
          newCol = prevLineLength === 0 ? 0 : prevLineLength - 1;
        }
      }
      return {
        ...state,
        cursorRow: newRow,
        cursorCol: newCol,
        preferredCol: null
      };
    }
    case "vim_move_right": {
      const { count } = action.payload;
      const { cursorRow: cursorRow2, cursorCol: cursorCol2, lines: lines2 } = state;
      let newRow = cursorRow2;
      let newCol = cursorCol2;
      for (let i = 0; i < count; i++) {
        const currentLine = lines2[newRow] || "";
        const lineLength = cpLen(currentLine);
        if (lineLength === 0) {
          if (newRow < lines2.length - 1) {
            newRow++;
            newCol = 0;
          }
        } else if (newCol < lineLength - 1) {
          newCol++;
          const currentLinePoints = toCodePoints(currentLine);
          while (newCol < currentLinePoints.length && isCombiningMark(currentLinePoints[newCol]) && newCol < lineLength - 1) {
            newCol++;
          }
        } else if (newRow < lines2.length - 1) {
          newRow++;
          newCol = 0;
        }
      }
      return {
        ...state,
        cursorRow: newRow,
        cursorCol: newCol,
        preferredCol: null
      };
    }
    case "vim_move_up": {
      const { count } = action.payload;
      const { cursorRow: cursorRow2, cursorCol: cursorCol2, lines: lines2 } = state;
      const newRow = Math.max(0, cursorRow2 - count);
      const targetLine = lines2[newRow] || "";
      const targetLineLength = cpLen(targetLine);
      const newCol = Math.min(
        cursorCol2,
        targetLineLength > 0 ? targetLineLength - 1 : 0
      );
      return {
        ...state,
        cursorRow: newRow,
        cursorCol: newCol,
        preferredCol: null
      };
    }
    case "vim_move_down": {
      const { count } = action.payload;
      const { cursorRow: cursorRow2, cursorCol: cursorCol2, lines: lines2 } = state;
      const newRow = Math.min(lines2.length - 1, cursorRow2 + count);
      const targetLine = lines2[newRow] || "";
      const targetLineLength = cpLen(targetLine);
      const newCol = Math.min(
        cursorCol2,
        targetLineLength > 0 ? targetLineLength - 1 : 0
      );
      return {
        ...state,
        cursorRow: newRow,
        cursorCol: newCol,
        preferredCol: null
      };
    }
    case "vim_move_word_forward": {
      const { count } = action.payload;
      let row = cursorRow;
      let col = cursorCol;
      for (let i = 0; i < count; i++) {
        const nextWord = findNextWordAcrossLines(lines, row, col, true);
        if (nextWord) {
          row = nextWord.row;
          col = nextWord.col;
        } else {
          break;
        }
      }
      return {
        ...state,
        cursorRow: row,
        cursorCol: col,
        preferredCol: null
      };
    }
    case "vim_move_word_backward": {
      const { count } = action.payload;
      let row = cursorRow;
      let col = cursorCol;
      for (let i = 0; i < count; i++) {
        const prevWord = findPrevWordAcrossLines(lines, row, col);
        if (prevWord) {
          row = prevWord.row;
          col = prevWord.col;
        } else {
          break;
        }
      }
      return {
        ...state,
        cursorRow: row,
        cursorCol: col,
        preferredCol: null
      };
    }
    case "vim_move_word_end": {
      const { count } = action.payload;
      let row = cursorRow;
      let col = cursorCol;
      for (let i = 0; i < count; i++) {
        if (i === 0) {
          const currentLine = lines[row] || "";
          const lineCodePoints = toCodePoints(currentLine);
          const atEndOfWord = col < lineCodePoints.length && isWordCharStrict(lineCodePoints[col]) && (col + 1 >= lineCodePoints.length || !isWordCharWithCombining(lineCodePoints[col + 1]) || // Or if we're on a base char followed only by combining marks until non-word
          isWordCharStrict(lineCodePoints[col]) && isAtEndOfBaseWord(lineCodePoints, col));
          if (atEndOfWord) {
            const nextWord = findNextWordAcrossLines(
              lines,
              row,
              col + 1,
              false
            );
            if (nextWord) {
              row = nextWord.row;
              col = nextWord.col;
              continue;
            }
          }
        }
        const wordEnd = findNextWordAcrossLines(lines, row, col, false);
        if (wordEnd) {
          row = wordEnd.row;
          col = wordEnd.col;
        } else {
          break;
        }
      }
      return {
        ...state,
        cursorRow: row,
        cursorCol: col,
        preferredCol: null
      };
    }
    case "vim_delete_char": {
      const { count } = action.payload;
      const { cursorRow: cursorRow2, cursorCol: cursorCol2, lines: lines2 } = state;
      const currentLine = lines2[cursorRow2] || "";
      const lineLength = cpLen(currentLine);
      if (cursorCol2 < lineLength) {
        const deleteCount = Math.min(count, lineLength - cursorCol2);
        const nextState = pushUndo(state);
        return replaceRangeInternal(
          nextState,
          cursorRow2,
          cursorCol2,
          cursorRow2,
          cursorCol2 + deleteCount,
          ""
        );
      }
      return state;
    }
    case "vim_insert_at_cursor": {
      return state;
    }
    case "vim_append_at_cursor": {
      const { cursorRow: cursorRow2, cursorCol: cursorCol2, lines: lines2 } = state;
      const currentLine = lines2[cursorRow2] || "";
      const newCol = cursorCol2 < cpLen(currentLine) ? cursorCol2 + 1 : cursorCol2;
      return {
        ...state,
        cursorCol: newCol,
        preferredCol: null
      };
    }
    case "vim_open_line_below": {
      const { cursorRow: cursorRow2, lines: lines2 } = state;
      const nextState = pushUndo(state);
      const endOfLine = cpLen(lines2[cursorRow2] || "");
      return replaceRangeInternal(
        nextState,
        cursorRow2,
        endOfLine,
        cursorRow2,
        endOfLine,
        "\n"
      );
    }
    case "vim_open_line_above": {
      const { cursorRow: cursorRow2 } = state;
      const nextState = pushUndo(state);
      const resultState = replaceRangeInternal(
        nextState,
        cursorRow2,
        0,
        cursorRow2,
        0,
        "\n"
      );
      return {
        ...resultState,
        cursorRow: cursorRow2,
        cursorCol: 0
      };
    }
    case "vim_append_at_line_end": {
      const { cursorRow: cursorRow2, lines: lines2 } = state;
      const lineLength = cpLen(lines2[cursorRow2] || "");
      return {
        ...state,
        cursorCol: lineLength,
        preferredCol: null
      };
    }
    case "vim_insert_at_line_start": {
      const { cursorRow: cursorRow2, lines: lines2 } = state;
      const currentLine = lines2[cursorRow2] || "";
      let col = 0;
      const lineCodePoints = toCodePoints(currentLine);
      while (col < lineCodePoints.length && /\s/.test(lineCodePoints[col])) {
        col++;
      }
      return {
        ...state,
        cursorCol: col,
        preferredCol: null
      };
    }
    case "vim_move_to_line_start": {
      return {
        ...state,
        cursorCol: 0,
        preferredCol: null
      };
    }
    case "vim_move_to_line_end": {
      const { cursorRow: cursorRow2, lines: lines2 } = state;
      const lineLength = cpLen(lines2[cursorRow2] || "");
      return {
        ...state,
        cursorCol: lineLength > 0 ? lineLength - 1 : 0,
        preferredCol: null
      };
    }
    case "vim_move_to_first_nonwhitespace": {
      const { cursorRow: cursorRow2, lines: lines2 } = state;
      const currentLine = lines2[cursorRow2] || "";
      let col = 0;
      const lineCodePoints = toCodePoints(currentLine);
      while (col < lineCodePoints.length && /\s/.test(lineCodePoints[col])) {
        col++;
      }
      return {
        ...state,
        cursorCol: col,
        preferredCol: null
      };
    }
    case "vim_move_to_first_line": {
      return {
        ...state,
        cursorRow: 0,
        cursorCol: 0,
        preferredCol: null
      };
    }
    case "vim_move_to_last_line": {
      const { lines: lines2 } = state;
      const lastRow = lines2.length - 1;
      return {
        ...state,
        cursorRow: lastRow,
        cursorCol: 0,
        preferredCol: null
      };
    }
    case "vim_move_to_line": {
      const { lineNumber } = action.payload;
      const { lines: lines2 } = state;
      const targetRow = Math.min(Math.max(0, lineNumber - 1), lines2.length - 1);
      return {
        ...state,
        cursorRow: targetRow,
        cursorCol: 0,
        preferredCol: null
      };
    }
    case "vim_escape_insert_mode": {
      const { cursorCol: cursorCol2 } = state;
      const newCol = cursorCol2 > 0 ? cursorCol2 - 1 : 0;
      return {
        ...state,
        cursorCol: newCol,
        preferredCol: null
      };
    }
    default: {
      assumeExhaustive(action);
      return state;
    }
  }
}
__name(handleVimAction, "handleVimAction");

// packages/cli/src/ui/components/shared/text-buffer.ts
var debugLogger4 = createDebugLogger("TEXT_BUFFER");
var isWordCharStrict = /* @__PURE__ */ __name((char) => /[\w\p{L}\p{N}]/u.test(char), "isWordCharStrict");
var isWhitespace = /* @__PURE__ */ __name((char) => /\s/.test(char), "isWhitespace");
var isCombiningMark = /* @__PURE__ */ __name((char) => new RegExp("\\p{M}", "u").test(char), "isCombiningMark");
var isWordCharWithCombining = /* @__PURE__ */ __name((char) => isWordCharStrict(char) || isCombiningMark(char), "isWordCharWithCombining");
var getCharScript = /* @__PURE__ */ __name((char) => {
  if (/[\p{Script=Latin}]/u.test(char)) return "latin";
  if (/[\p{Script=Han}]/u.test(char)) return "han";
  if (/[\p{Script=Arabic}]/u.test(char)) return "arabic";
  if (/[\p{Script=Hiragana}]/u.test(char)) return "hiragana";
  if (/[\p{Script=Katakana}]/u.test(char)) return "katakana";
  if (/[\p{Script=Cyrillic}]/u.test(char)) return "cyrillic";
  return "other";
}, "getCharScript");
var isDifferentScript = /* @__PURE__ */ __name((char1, char2) => {
  if (!isWordCharStrict(char1) || !isWordCharStrict(char2)) return false;
  return getCharScript(char1) !== getCharScript(char2);
}, "isDifferentScript");
var CJK_CHAR_REGEX = /[\u4e00-\u9fff\u3400-\u4dbf\uf900-\ufaff\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]/;
var isCjkChar = /* @__PURE__ */ __name((char) => CJK_CHAR_REGEX.test(char), "isCjkChar");
var WORD_BOUNDARIES_CACHE_MAX = 500;
var SEGMENTER_LENGTH_LIMIT = 1500;
var wordBoundariesCache = null;
var segmenter3 = null;
function ensureSegmenterLoaded() {
  if (segmenter3 !== null) return;
  try {
    segmenter3 = new Intl.Segmenter("zh", { granularity: "word" });
    debugLogger4.info("Intl.Segmenter: initialized successfully");
  } catch (err) {
    debugLogger4.warn("Intl.Segmenter: failed to initialize", err);
    segmenter3 = false;
  }
}
__name(ensureSegmenterLoaded, "ensureSegmenterLoaded");
function charByCharFallback(line) {
  const codePoints = toCodePoints(line);
  const fallback = [];
  for (let i = 0; i < codePoints.length; i++) {
    if (isCjkChar(codePoints[i])) {
      fallback.push({ start: i, end: i + 1 });
    }
  }
  return fallback;
}
__name(charByCharFallback, "charByCharFallback");
function evictCacheIfNeeded() {
  if (wordBoundariesCache && wordBoundariesCache.size >= WORD_BOUNDARIES_CACHE_MAX) {
    const firstKey = wordBoundariesCache.keys().next().value;
    if (firstKey !== void 0) {
      wordBoundariesCache.delete(firstKey);
    }
  }
}
__name(evictCacheIfNeeded, "evictCacheIfNeeded");
function getWordBoundaries(line, codePoints) {
  const cps = codePoints ?? toCodePoints(line);
  if (cps.length > SEGMENTER_LENGTH_LIMIT) {
    if (!wordBoundariesCache) wordBoundariesCache = /* @__PURE__ */ new Map();
    if (wordBoundariesCache.has(line)) return wordBoundariesCache.get(line);
    const fallback = charByCharFallback(line);
    evictCacheIfNeeded();
    wordBoundariesCache.set(line, fallback);
    return fallback;
  }
  if (!wordBoundariesCache) wordBoundariesCache = /* @__PURE__ */ new Map();
  const cached = wordBoundariesCache.get(line);
  if (cached) {
    return cached;
  }
  ensureSegmenterLoaded();
  if (!segmenter3) {
    const fallback = charByCharFallback(line);
    evictCacheIfNeeded();
    wordBoundariesCache.set(line, fallback);
    return fallback;
  }
  try {
    const segments = segmenter3.segment(line);
    const cpToStrIdx = [];
    let strIdx = 0;
    for (let i = 0; i < cps.length; i++) {
      cpToStrIdx[i] = strIdx;
      strIdx += cps[i].length;
    }
    const boundaries = [];
    for (const { index, segment, isWordLike } of segments) {
      const trimmedSegment = segment.trim();
      if (!isWordLike && trimmedSegment.length === 0) {
        continue;
      }
      if (isWordLike && segment.includes(".")) {
        let currentOffset = index;
        const parts = segment.split(/(\.)/);
        for (const part of parts) {
          if (part.length === 0) continue;
          const partStartCpIdx = binarySearchCpIndex(cpToStrIdx, currentOffset);
          const partEndStrPos = currentOffset + part.length;
          const partEndCpIdxRaw = binarySearchCpIndex(
            cpToStrIdx,
            partEndStrPos
          );
          const partEndCpIdx = partEndCpIdxRaw === -1 ? cps.length : partEndCpIdxRaw;
          if (partStartCpIdx >= 0 && partStartCpIdx < partEndCpIdx) {
            boundaries.push({ start: partStartCpIdx, end: partEndCpIdx });
          }
          currentOffset += part.length;
        }
        continue;
      }
      if (!isWordLike && /^[.,;!?，。；！？、]+$/.test(trimmedSegment)) {
        const startCpIdx2 = binarySearchCpIndex(cpToStrIdx, index);
        const endStrPos2 = index + segment.length;
        const endCpIdxRaw2 = binarySearchCpIndex(cpToStrIdx, endStrPos2);
        const endCpIdx2 = endCpIdxRaw2 === -1 ? cps.length : endCpIdxRaw2;
        if (startCpIdx2 >= 0 && startCpIdx2 < endCpIdx2) {
          boundaries.push({ start: startCpIdx2, end: endCpIdx2 });
        }
        continue;
      }
      const startCpIdx = binarySearchCpIndex(cpToStrIdx, index);
      const endStrPos = index + segment.length;
      const endCpIdxRaw = binarySearchCpIndex(cpToStrIdx, endStrPos);
      const endCpIdx = endCpIdxRaw === -1 ? cps.length : endCpIdxRaw;
      if (startCpIdx >= 0 && startCpIdx < endCpIdx) {
        boundaries.push({ start: startCpIdx, end: endCpIdx });
      }
    }
    evictCacheIfNeeded();
    wordBoundariesCache.set(line, boundaries);
    return boundaries;
  } catch (err) {
    debugLogger4.warn("getWordBoundaries: error, using char fallback", err);
    const fallback = charByCharFallback(line);
    evictCacheIfNeeded();
    wordBoundariesCache.set(line, fallback);
    return fallback;
  }
}
__name(getWordBoundaries, "getWordBoundaries");
function binarySearchCpIndex(cpToStrIdx, target) {
  let lo = 0;
  let hi = cpToStrIdx.length - 1;
  while (lo <= hi) {
    const mid = lo + hi >>> 1;
    if (cpToStrIdx[mid] >= target) hi = mid - 1;
    else lo = mid + 1;
  }
  return lo < cpToStrIdx.length ? lo : -1;
}
__name(binarySearchCpIndex, "binarySearchCpIndex");
function findPrevWordStart(boundaries, col) {
  for (let i = boundaries.length - 1; i >= 0; i--) {
    const b = boundaries[i];
    if (col > b.start && col <= b.end) {
      return b.start;
    }
    if (col === b.start && i > 0) {
      return boundaries[i - 1].start;
    }
  }
  return null;
}
__name(findPrevWordStart, "findPrevWordStart");
function findNextWordEnd(boundaries, col) {
  for (const b of boundaries) {
    if (col >= b.start && col < b.end) {
      return b.end;
    }
    if (col < b.start) {
      return null;
    }
  }
  return null;
}
__name(findNextWordEnd, "findNextWordEnd");
function findWordEndFallback(arr, startPos) {
  let end = startPos;
  while (end < arr.length) {
    const currChar = arr[end];
    const nextChar = end + 1 < arr.length ? arr[end + 1] : void 0;
    if (!isWordCharStrict(currChar ?? "") || nextChar !== void 0 && isWordCharStrict(currChar ?? "") && isWordCharStrict(nextChar) && isDifferentScript(currChar ?? "", nextChar)) {
      break;
    }
    if (nextChar !== void 0 && isCjkChar(currChar ?? "") && isCjkChar(nextChar)) {
      end++;
      break;
    }
    end++;
  }
  return end;
}
__name(findWordEndFallback, "findWordEndFallback");
var findNextWordStartInLine = /* @__PURE__ */ __name((line, col) => {
  const chars = toCodePoints(line);
  let i = col;
  if (i >= chars.length) return null;
  const currentChar = chars[i];
  if (isWordCharStrict(currentChar)) {
    while (i < chars.length && isWordCharWithCombining(chars[i])) {
      if (i + 1 < chars.length && isWordCharStrict(chars[i + 1]) && isDifferentScript(chars[i], chars[i + 1])) {
        i++;
        break;
      }
      i++;
    }
  } else if (!isWhitespace(currentChar)) {
    while (i < chars.length && !isWordCharStrict(chars[i]) && !isWhitespace(chars[i])) {
      i++;
    }
  }
  while (i < chars.length && isWhitespace(chars[i])) {
    i++;
  }
  return i < chars.length ? i : null;
}, "findNextWordStartInLine");
var findPrevWordStartInLine = /* @__PURE__ */ __name((line, col) => {
  const chars = toCodePoints(line);
  let i = col;
  if (i <= 0) return null;
  i--;
  while (i >= 0 && isWhitespace(chars[i])) {
    i--;
  }
  if (i < 0) return null;
  if (isWordCharStrict(chars[i])) {
    while (i >= 0 && isWordCharStrict(chars[i])) {
      if (i - 1 >= 0 && isWordCharStrict(chars[i - 1]) && isDifferentScript(chars[i], chars[i - 1])) {
        return i;
      }
      i--;
    }
    return i + 1;
  } else {
    while (i >= 0 && !isWordCharStrict(chars[i]) && !isWhitespace(chars[i])) {
      i--;
    }
    return i + 1;
  }
}, "findPrevWordStartInLine");
var findWordEndInLine = /* @__PURE__ */ __name((line, col) => {
  const chars = toCodePoints(line);
  let i = col;
  const atEndOfWordChar = i < chars.length && isWordCharWithCombining(chars[i]) && (i + 1 >= chars.length || !isWordCharWithCombining(chars[i + 1]) || isWordCharStrict(chars[i]) && i + 1 < chars.length && isWordCharStrict(chars[i + 1]) && isDifferentScript(chars[i], chars[i + 1]));
  const atEndOfPunctuation = i < chars.length && !isWordCharWithCombining(chars[i]) && !isWhitespace(chars[i]) && (i + 1 >= chars.length || isWhitespace(chars[i + 1]) || isWordCharWithCombining(chars[i + 1]));
  if (atEndOfWordChar || atEndOfPunctuation) {
    i++;
    while (i < chars.length && isWhitespace(chars[i])) {
      i++;
    }
  }
  if (i < chars.length && !isWordCharWithCombining(chars[i])) {
    while (i < chars.length && isWhitespace(chars[i])) {
      i++;
    }
  }
  let foundWord = false;
  let lastBaseCharPos = -1;
  if (i < chars.length && isWordCharWithCombining(chars[i])) {
    while (i < chars.length && isWordCharWithCombining(chars[i])) {
      foundWord = true;
      if (isWordCharStrict(chars[i])) {
        lastBaseCharPos = i;
      }
      if (i + 1 < chars.length && isWordCharStrict(chars[i + 1]) && isDifferentScript(chars[i], chars[i + 1])) {
        i++;
        if (isWordCharStrict(chars[i - 1])) {
          lastBaseCharPos = i - 1;
        }
        break;
      }
      i++;
    }
  } else if (i < chars.length && !isWhitespace(chars[i])) {
    while (i < chars.length && !isWordCharStrict(chars[i]) && !isWhitespace(chars[i])) {
      foundWord = true;
      lastBaseCharPos = i;
      i++;
    }
  }
  if (foundWord && lastBaseCharPos >= col) {
    return lastBaseCharPos;
  }
  return null;
}, "findWordEndInLine");
var findNextWordAcrossLines = /* @__PURE__ */ __name((lines, cursorRow, cursorCol, searchForWordStart) => {
  const currentLine = lines[cursorRow] || "";
  const colInCurrentLine = searchForWordStart ? findNextWordStartInLine(currentLine, cursorCol) : findWordEndInLine(currentLine, cursorCol);
  if (colInCurrentLine !== null) {
    return { row: cursorRow, col: colInCurrentLine };
  }
  for (let row = cursorRow + 1; row < lines.length; row++) {
    const line = lines[row] || "";
    const chars = toCodePoints(line);
    if (chars.length === 0) {
      let hasWordsInLaterLines = false;
      for (let laterRow = row + 1; laterRow < lines.length; laterRow++) {
        const laterLine = lines[laterRow] || "";
        const laterChars = toCodePoints(laterLine);
        let firstNonWhitespace2 = 0;
        while (firstNonWhitespace2 < laterChars.length && isWhitespace(laterChars[firstNonWhitespace2])) {
          firstNonWhitespace2++;
        }
        if (firstNonWhitespace2 < laterChars.length) {
          hasWordsInLaterLines = true;
          break;
        }
      }
      if (!hasWordsInLaterLines) {
        return { row, col: 0 };
      }
      continue;
    }
    let firstNonWhitespace = 0;
    while (firstNonWhitespace < chars.length && isWhitespace(chars[firstNonWhitespace])) {
      firstNonWhitespace++;
    }
    if (firstNonWhitespace < chars.length) {
      if (searchForWordStart) {
        return { row, col: firstNonWhitespace };
      } else {
        const endCol = findWordEndInLine(line, firstNonWhitespace);
        if (endCol !== null) {
          return { row, col: endCol };
        }
      }
    }
  }
  return null;
}, "findNextWordAcrossLines");
var findPrevWordAcrossLines = /* @__PURE__ */ __name((lines, cursorRow, cursorCol) => {
  const currentLine = lines[cursorRow] || "";
  const colInCurrentLine = findPrevWordStartInLine(currentLine, cursorCol);
  if (colInCurrentLine !== null) {
    return { row: cursorRow, col: colInCurrentLine };
  }
  for (let row = cursorRow - 1; row >= 0; row--) {
    const line = lines[row] || "";
    const chars = toCodePoints(line);
    if (chars.length === 0) continue;
    let lastWordStart = chars.length;
    while (lastWordStart > 0 && isWhitespace(chars[lastWordStart - 1])) {
      lastWordStart--;
    }
    if (lastWordStart > 0) {
      const wordStart = findPrevWordStartInLine(line, lastWordStart);
      if (wordStart !== null) {
        return { row, col: wordStart };
      }
    }
  }
  return null;
}, "findPrevWordAcrossLines");
var offsetToRowCol = /* @__PURE__ */ __name((offset, lines) => {
  let running = 0;
  for (let i = 0; i < lines.length; i++) {
    const lineLength = lines[i].length + 1;
    if (running + lineLength > offset) {
      return { row: i, col: offset - running };
    }
    running += lineLength;
  }
  const last = Math.max(0, lines.length - 1);
  return { row: last, col: lines[last]?.length ?? 0 };
}, "offsetToRowCol");
var getPositionFromOffsets = /* @__PURE__ */ __name((startOffset, endOffset, lines) => {
  const { row: startRow, col: startCol } = offsetToRowCol(startOffset, lines);
  const { row: endRow, col: endCol } = offsetToRowCol(endOffset, lines);
  return { startRow, startCol, endRow, endCol };
}, "getPositionFromOffsets");
var getLineRangeOffsets = /* @__PURE__ */ __name((startRow, lineCount, lines) => {
  let startOffset = 0;
  for (let i = 0; i < startRow; i++) {
    startOffset += lines[i].length + 1;
  }
  let endOffset = startOffset;
  for (let i = 0; i < lineCount; i++) {
    const lineIndex = startRow + i;
    if (lineIndex < lines.length) {
      endOffset += lines[lineIndex].length;
      if (lineIndex < lines.length - 1) {
        endOffset += 1;
      }
    }
  }
  return { startOffset, endOffset };
}, "getLineRangeOffsets");
var replaceRangeInternal = /* @__PURE__ */ __name((state, startRow, startCol, endRow, endCol, text) => {
  const currentLine = /* @__PURE__ */ __name((row) => state.lines[row] || "", "currentLine");
  const currentLineLen = /* @__PURE__ */ __name((row) => cpLen(currentLine(row)), "currentLineLen");
  const clamp2 = /* @__PURE__ */ __name((value, min, max) => Math.min(Math.max(value, min), max), "clamp");
  if (startRow > endRow || startRow === endRow && startCol > endCol || startRow < 0 || startCol < 0 || endRow >= state.lines.length || endRow < state.lines.length && endCol > currentLineLen(endRow)) {
    return state;
  }
  const newLines = [...state.lines];
  const sCol = clamp2(startCol, 0, currentLineLen(startRow));
  const eCol = clamp2(endCol, 0, currentLineLen(endRow));
  const prefix = cpSlice(currentLine(startRow), 0, sCol);
  const suffix = cpSlice(currentLine(endRow), eCol);
  const normalisedReplacement = text.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
  const replacementParts = normalisedReplacement.split("\n");
  const firstLine = prefix + replacementParts[0];
  if (replacementParts.length === 1) {
    newLines.splice(startRow, endRow - startRow + 1, firstLine + suffix);
  } else {
    const lastLine = replacementParts[replacementParts.length - 1] + suffix;
    const middleLines = replacementParts.slice(1, -1);
    newLines.splice(
      startRow,
      endRow - startRow + 1,
      firstLine,
      ...middleLines,
      lastLine
    );
  }
  const finalCursorRow = startRow + replacementParts.length - 1;
  const finalCursorCol = (replacementParts.length > 1 ? 0 : sCol) + cpLen(replacementParts[replacementParts.length - 1]);
  return {
    ...state,
    lines: newLines,
    cursorRow: Math.min(Math.max(finalCursorRow, 0), newLines.length - 1),
    cursorCol: Math.max(
      0,
      Math.min(finalCursorCol, cpLen(newLines[finalCursorRow] || ""))
    ),
    preferredCol: null
  };
}, "replaceRangeInternal");
function clamp(v, min, max) {
  return v < min ? min : v > max ? max : v;
}
__name(clamp, "clamp");
function calculateInitialCursorPosition(initialLines, offset) {
  let remainingChars = offset;
  let row = 0;
  while (row < initialLines.length) {
    const lineLength = cpLen(initialLines[row]);
    const totalCharsInLineAndNewline = lineLength + (row < initialLines.length - 1 ? 1 : 0);
    if (remainingChars <= lineLength) {
      return [row, remainingChars];
    }
    remainingChars -= totalCharsInLineAndNewline;
    row++;
  }
  if (initialLines.length > 0) {
    const lastRow = initialLines.length - 1;
    return [lastRow, cpLen(initialLines[lastRow])];
  }
  return [0, 0];
}
__name(calculateInitialCursorPosition, "calculateInitialCursorPosition");
function offsetToLogicalPos(text, offset) {
  let row = 0;
  let col = 0;
  let currentOffset = 0;
  if (offset === 0) return [0, 0];
  const lines = text.split("\n");
  for (let i = 0; i < lines.length; i++) {
    const line = lines[i];
    const lineLength = cpLen(line);
    const lineLengthWithNewline = lineLength + (i < lines.length - 1 ? 1 : 0);
    if (offset <= currentOffset + lineLength) {
      row = i;
      col = offset - currentOffset;
      return [row, col];
    } else if (offset <= currentOffset + lineLengthWithNewline) {
      row = i;
      col = lineLength;
      if (offset === currentOffset + lineLengthWithNewline && i < lines.length - 1) {
        return [i + 1, 0];
      }
      return [row, col];
    }
    currentOffset += lineLengthWithNewline;
  }
  if (lines.length > 0) {
    row = lines.length - 1;
    col = cpLen(lines[row]);
  } else {
    row = 0;
    col = 0;
  }
  return [row, col];
}
__name(offsetToLogicalPos, "offsetToLogicalPos");
function logicalPosToOffset(lines, row, col) {
  let offset = 0;
  const actualRow = Math.min(row, lines.length - 1);
  for (let i = 0; i < actualRow; i++) {
    offset += cpLen(lines[i]) + 1;
  }
  if (actualRow >= 0 && actualRow < lines.length) {
    offset += Math.min(col, cpLen(lines[actualRow]));
  }
  return offset;
}
__name(logicalPosToOffset, "logicalPosToOffset");
function calculateLayout(logicalLines, viewportWidth) {
  const visualLines = [];
  const logicalToVisualMap = [];
  const visualToLogicalMap = [];
  logicalLines.forEach((logLine, logIndex) => {
    logicalToVisualMap[logIndex] = [];
    if (logLine.length === 0) {
      logicalToVisualMap[logIndex].push([visualLines.length, 0]);
      visualToLogicalMap.push([logIndex, 0]);
      visualLines.push("");
    } else {
      let currentPosInLogLine = 0;
      const codePointsInLogLine = toCodePoints(logLine);
      while (currentPosInLogLine < codePointsInLogLine.length) {
        let currentChunk = "";
        let currentChunkVisualWidth = 0;
        let numCodePointsInChunk = 0;
        let lastWordBreakPoint = -1;
        let numCodePointsAtLastWordBreak = 0;
        for (let i = currentPosInLogLine; i < codePointsInLogLine.length; i++) {
          const char = codePointsInLogLine[i];
          const charVisualWidth = getCachedStringWidth(char);
          if (currentChunkVisualWidth + charVisualWidth > viewportWidth) {
            if (lastWordBreakPoint !== -1 && numCodePointsAtLastWordBreak > 0 && currentPosInLogLine + numCodePointsAtLastWordBreak < i) {
              currentChunk = codePointsInLogLine.slice(
                currentPosInLogLine,
                currentPosInLogLine + numCodePointsAtLastWordBreak
              ).join("");
              numCodePointsInChunk = numCodePointsAtLastWordBreak;
            } else {
              if (numCodePointsInChunk === 0 && charVisualWidth > viewportWidth) {
                currentChunk = char;
                numCodePointsInChunk = 1;
              } else if (numCodePointsInChunk === 0 && charVisualWidth <= viewportWidth) {
              }
            }
            break;
          }
          currentChunk += char;
          currentChunkVisualWidth += charVisualWidth;
          numCodePointsInChunk++;
          if (char === " ") {
            lastWordBreakPoint = i;
            numCodePointsAtLastWordBreak = numCodePointsInChunk - 1;
          }
        }
        if (numCodePointsInChunk === 0 && currentPosInLogLine < codePointsInLogLine.length) {
          const firstChar = codePointsInLogLine[currentPosInLogLine];
          currentChunk = firstChar;
          numCodePointsInChunk = 1;
        }
        if (numCodePointsInChunk === 0 && currentPosInLogLine < codePointsInLogLine.length) {
          currentChunk = codePointsInLogLine[currentPosInLogLine];
          numCodePointsInChunk = 1;
        }
        logicalToVisualMap[logIndex].push([
          visualLines.length,
          currentPosInLogLine
        ]);
        visualToLogicalMap.push([logIndex, currentPosInLogLine]);
        visualLines.push(currentChunk);
        const logicalStartOfThisChunk = currentPosInLogLine;
        currentPosInLogLine += numCodePointsInChunk;
        if (logicalStartOfThisChunk + numCodePointsInChunk < codePointsInLogLine.length && currentPosInLogLine < codePointsInLogLine.length && // Redundant if previous is true, but safe
        codePointsInLogLine[currentPosInLogLine] === " ") {
          currentPosInLogLine++;
        }
      }
    }
  });
  if (logicalLines.length === 0 || logicalLines.length === 1 && logicalLines[0] === "") {
    if (visualLines.length === 0) {
      visualLines.push("");
      if (!logicalToVisualMap[0]) logicalToVisualMap[0] = [];
      logicalToVisualMap[0].push([0, 0]);
      visualToLogicalMap.push([0, 0]);
    }
  }
  return {
    visualLines,
    logicalToVisualMap,
    visualToLogicalMap
  };
}
__name(calculateLayout, "calculateLayout");
function calculateVisualCursorFromLayout(layout, logicalCursor) {
  const { logicalToVisualMap, visualLines } = layout;
  const [logicalRow, logicalCol] = logicalCursor;
  const segmentsForLogicalLine = logicalToVisualMap[logicalRow];
  if (!segmentsForLogicalLine || segmentsForLogicalLine.length === 0) {
    return [0, 0];
  }
  let targetSegmentIndex = segmentsForLogicalLine.findIndex(
    ([, startColInLogical2], index) => {
      const nextStartColInLogical = index + 1 < segmentsForLogicalLine.length ? segmentsForLogicalLine[index + 1][1] : Infinity;
      return logicalCol >= startColInLogical2 && logicalCol < nextStartColInLogical;
    }
  );
  if (targetSegmentIndex === -1) {
    if (logicalCol === 0) {
      targetSegmentIndex = 0;
    } else {
      targetSegmentIndex = segmentsForLogicalLine.length - 1;
    }
  }
  const [visualRow, startColInLogical] = segmentsForLogicalLine[targetSegmentIndex];
  const visualCol = logicalCol - startColInLogical;
  const clampedVisualCol = Math.min(
    visualCol,
    cpLen(visualLines[visualRow] ?? "")
  );
  return [visualRow, clampedVisualCol];
}
__name(calculateVisualCursorFromLayout, "calculateVisualCursorFromLayout");
var historyLimit = 100;
var pushUndo = /* @__PURE__ */ __name((currentState) => {
  const snapshot = {
    lines: [...currentState.lines],
    cursorRow: currentState.cursorRow,
    cursorCol: currentState.cursorCol
  };
  const newStack = [...currentState.undoStack, snapshot];
  if (newStack.length > historyLimit) {
    newStack.shift();
  }
  return { ...currentState, undoStack: newStack, redoStack: [] };
}, "pushUndo");
function textBufferReducerLogic(state, action) {
  const pushUndoLocal = pushUndo;
  const currentLine = /* @__PURE__ */ __name((r) => state.lines[r] ?? "", "currentLine");
  const currentLineLen = /* @__PURE__ */ __name((r) => cpLen(currentLine(r)), "currentLineLen");
  switch (action.type) {
    case "set_text": {
      let nextState = state;
      if (action.pushToUndo !== false) {
        nextState = pushUndoLocal(state);
      }
      const newContentLines = action.payload.replace(/\r\n?/g, "\n").split("\n");
      const lines = newContentLines.length === 0 ? [""] : newContentLines;
      const lastNewLineIndex = lines.length - 1;
      return {
        ...nextState,
        lines,
        cursorRow: lastNewLineIndex,
        cursorCol: cpLen(lines[lastNewLineIndex] ?? ""),
        preferredCol: null
      };
    }
    case "insert": {
      const nextState = pushUndoLocal(state);
      const newLines = [...nextState.lines];
      let newCursorRow = nextState.cursorRow;
      let newCursorCol = nextState.cursorCol;
      const currentLine2 = /* @__PURE__ */ __name((r) => newLines[r] ?? "", "currentLine");
      const str = stripUnsafeCharacters(
        action.payload.replace(/\r\n/g, "\n").replace(/\r/g, "\n")
      );
      const parts = str.split("\n");
      const lineContent = currentLine2(newCursorRow);
      const before = cpSlice(lineContent, 0, newCursorCol);
      const after = cpSlice(lineContent, newCursorCol);
      if (parts.length > 1) {
        newLines[newCursorRow] = before + parts[0];
        const remainingParts = parts.slice(1);
        const lastPartOriginal = remainingParts.pop() ?? "";
        newLines.splice(newCursorRow + 1, 0, ...remainingParts);
        newLines.splice(
          newCursorRow + parts.length - 1,
          0,
          lastPartOriginal + after
        );
        newCursorRow = newCursorRow + parts.length - 1;
        newCursorCol = cpLen(lastPartOriginal);
      } else {
        newLines[newCursorRow] = before + parts[0] + after;
        newCursorCol = cpLen(before) + cpLen(parts[0]);
      }
      return {
        ...nextState,
        lines: newLines,
        cursorRow: newCursorRow,
        cursorCol: newCursorCol,
        preferredCol: null
      };
    }
    case "backspace": {
      const nextState = pushUndoLocal(state);
      const newLines = [...nextState.lines];
      let newCursorRow = nextState.cursorRow;
      let newCursorCol = nextState.cursorCol;
      const currentLine2 = /* @__PURE__ */ __name((r) => newLines[r] ?? "", "currentLine");
      if (newCursorCol === 0 && newCursorRow === 0) return state;
      if (newCursorCol > 0) {
        const lineContent = currentLine2(newCursorRow);
        newLines[newCursorRow] = cpSlice(lineContent, 0, newCursorCol - 1) + cpSlice(lineContent, newCursorCol);
        newCursorCol--;
      } else if (newCursorRow > 0) {
        const prevLineContent = currentLine2(newCursorRow - 1);
        const currentLineContentVal = currentLine2(newCursorRow);
        const newCol = cpLen(prevLineContent);
        newLines[newCursorRow - 1] = prevLineContent + currentLineContentVal;
        newLines.splice(newCursorRow, 1);
        newCursorRow--;
        newCursorCol = newCol;
      }
      return {
        ...nextState,
        lines: newLines,
        cursorRow: newCursorRow,
        cursorCol: newCursorCol,
        preferredCol: null
      };
    }
    case "set_viewport": {
      const { width, height } = action.payload;
      if (width === state.viewportWidth && height === state.viewportHeight) {
        return state;
      }
      return {
        ...state,
        viewportWidth: width,
        viewportHeight: height
      };
    }
    case "move": {
      const { dir } = action.payload;
      const { cursorRow, cursorCol, lines, visualLayout, preferredCol } = state;
      if (dir === "left" || dir === "right" || dir === "up" || dir === "down" || dir === "home" || dir === "end") {
        const visualCursor = calculateVisualCursorFromLayout(visualLayout, [
          cursorRow,
          cursorCol
        ]);
        const { visualLines, visualToLogicalMap } = visualLayout;
        let newVisualRow = visualCursor[0];
        let newVisualCol = visualCursor[1];
        let newPreferredCol = preferredCol;
        const currentVisLineLen = cpLen(visualLines[newVisualRow] ?? "");
        switch (dir) {
          case "left":
            newPreferredCol = null;
            if (newVisualCol > 0) {
              newVisualCol--;
            } else if (newVisualRow > 0) {
              newVisualRow--;
              newVisualCol = cpLen(visualLines[newVisualRow] ?? "");
              const previousMapping = visualToLogicalMap[newVisualRow];
              if (previousMapping) {
                const [previousLogRow, previousLogStartCol] = previousMapping;
                const previousCursorCol = previousLogStartCol + newVisualCol;
                if (previousLogRow === cursorRow && previousCursorCol === cursorCol && newVisualCol > 0) {
                  newVisualCol--;
                }
              }
            }
            break;
          case "right":
            newPreferredCol = null;
            if (newVisualCol < currentVisLineLen) {
              newVisualCol++;
            } else if (newVisualRow < visualLines.length - 1) {
              newVisualRow++;
              newVisualCol = 0;
            }
            break;
          case "up":
            if (newVisualRow > 0) {
              if (newPreferredCol === null) newPreferredCol = newVisualCol;
              newVisualRow--;
              newVisualCol = clamp(
                newPreferredCol,
                0,
                cpLen(visualLines[newVisualRow] ?? "")
              );
            }
            break;
          case "down":
            if (newVisualRow < visualLines.length - 1) {
              if (newPreferredCol === null) newPreferredCol = newVisualCol;
              newVisualRow++;
              newVisualCol = clamp(
                newPreferredCol,
                0,
                cpLen(visualLines[newVisualRow] ?? "")
              );
            }
            break;
          case "home":
            newPreferredCol = null;
            newVisualCol = 0;
            break;
          case "end":
            newPreferredCol = null;
            newVisualCol = currentVisLineLen;
            break;
          default: {
            const exhaustiveCheck = dir;
            debugLogger4.error(
              `Unknown visual movement direction: ${exhaustiveCheck}`
            );
            return state;
          }
        }
        if (visualToLogicalMap[newVisualRow]) {
          const [logRow, logStartCol] = visualToLogicalMap[newVisualRow];
          return {
            ...state,
            cursorRow: logRow,
            cursorCol: clamp(
              logStartCol + newVisualCol,
              0,
              cpLen(lines[logRow] ?? "")
            ),
            preferredCol: newPreferredCol
          };
        }
        return state;
      }
      switch (dir) {
        case "wordLeft": {
          if (cursorCol === 0 && cursorRow === 0) return state;
          let newCursorRow = cursorRow;
          let newCursorCol = cursorCol;
          if (cursorCol === 0) {
            newCursorRow--;
            newCursorCol = cpLen(lines[newCursorRow] ?? "");
          } else {
            const lineContent = lines[cursorRow];
            const arr = toCodePoints(lineContent);
            let start = cursorCol;
            const boundaries = getWordBoundaries(lineContent, arr);
            const startBoundary = findPrevWordStart(boundaries, start);
            if (startBoundary !== null) {
              start = startBoundary;
            } else {
              let onlySpaces = true;
              for (let i = 0; i < start; i++) {
                if (isWordCharStrict(arr[i] ?? "")) {
                  onlySpaces = false;
                  break;
                }
              }
              if (onlySpaces) {
                start = 0;
              } else {
                while (start > 0 && !isWordCharStrict(arr[start - 1] ?? ""))
                  start--;
                while (start > 0) {
                  const prevChar = arr[start - 1];
                  const currChar = arr[start];
                  if (!isWordCharStrict(prevChar ?? "") || isWordCharStrict(currChar ?? "") && isDifferentScript(currChar ?? "", prevChar ?? "")) {
                    break;
                  }
                  if (isCjkChar(currChar ?? "") && isCjkChar(prevChar ?? "")) {
                    break;
                  }
                  start--;
                }
              }
            }
            newCursorCol = start;
          }
          return {
            ...state,
            cursorRow: newCursorRow,
            cursorCol: newCursorCol,
            preferredCol: null
          };
        }
        case "wordRight": {
          if (cursorRow === lines.length - 1 && cursorCol === cpLen(lines[cursorRow] ?? "")) {
            return state;
          }
          let newCursorRow = cursorRow;
          let newCursorCol = cursorCol;
          const lineContent = lines[cursorRow] ?? "";
          const arr = toCodePoints(lineContent);
          if (cursorCol >= arr.length) {
            newCursorRow++;
            newCursorCol = 0;
          } else {
            const boundaries = getWordBoundaries(lineContent, arr);
            const endBoundary = findNextWordEnd(boundaries, cursorCol);
            let end;
            if (endBoundary !== null) {
              end = endBoundary;
              while (end < arr.length && isWhitespace(arr[end] ?? "")) {
                end++;
              }
            } else if (cursorCol < arr.length && !isWordCharStrict(arr[cursorCol] ?? "")) {
              end = cursorCol;
              while (end < arr.length && !isWordCharStrict(arr[end] ?? ""))
                end++;
              if (end < arr.length) {
                const nextEnd = findNextWordEnd(boundaries, end);
                if (nextEnd !== null) {
                  end = nextEnd;
                } else {
                  end = findWordEndFallback(arr, end);
                }
              }
            } else {
              end = cursorCol;
              while (end < arr.length && !isWordCharStrict(arr[end] ?? ""))
                end++;
              end = findWordEndFallback(arr, end);
            }
            newCursorCol = end;
          }
          return {
            ...state,
            cursorRow: newCursorRow,
            cursorCol: newCursorCol,
            preferredCol: null
          };
        }
        default:
          return state;
      }
    }
    case "set_cursor": {
      return {
        ...state,
        ...action.payload
      };
    }
    case "delete": {
      const { cursorRow, cursorCol, lines } = state;
      const lineContent = currentLine(cursorRow);
      if (cursorCol < currentLineLen(cursorRow)) {
        const nextState = pushUndoLocal(state);
        const newLines = [...nextState.lines];
        newLines[cursorRow] = cpSlice(lineContent, 0, cursorCol) + cpSlice(lineContent, cursorCol + 1);
        return {
          ...nextState,
          lines: newLines,
          preferredCol: null
        };
      } else if (cursorRow < lines.length - 1) {
        const nextState = pushUndoLocal(state);
        const nextLineContent = currentLine(cursorRow + 1);
        const newLines = [...nextState.lines];
        newLines[cursorRow] = lineContent + nextLineContent;
        newLines.splice(cursorRow + 1, 1);
        return {
          ...nextState,
          lines: newLines,
          preferredCol: null
        };
      }
      return state;
    }
    case "delete_word_left": {
      const { cursorRow, cursorCol } = state;
      if (cursorCol === 0 && cursorRow === 0) return state;
      const nextState = pushUndoLocal(state);
      const newLines = [...nextState.lines];
      let newCursorRow = cursorRow;
      let newCursorCol = cursorCol;
      if (newCursorCol > 0) {
        const lineContent = currentLine(newCursorRow);
        const arr = toCodePoints(lineContent);
        const boundaries = getWordBoundaries(lineContent, arr);
        const startBoundary = findPrevWordStart(boundaries, newCursorCol);
        let start;
        if (startBoundary !== null) {
          start = startBoundary;
        } else {
          const prevWordStart = findPrevWordStartInLine(
            lineContent,
            newCursorCol
          );
          start = prevWordStart === null ? 0 : prevWordStart;
        }
        newLines[newCursorRow] = cpSlice(lineContent, 0, start) + cpSlice(lineContent, newCursorCol);
        newCursorCol = start;
      } else {
        const prevLineContent = currentLine(cursorRow - 1);
        const currentLineContentVal = currentLine(cursorRow);
        const newCol = cpLen(prevLineContent);
        newLines[cursorRow - 1] = prevLineContent + currentLineContentVal;
        newLines.splice(cursorRow, 1);
        newCursorRow--;
        newCursorCol = newCol;
      }
      return {
        ...nextState,
        lines: newLines,
        cursorRow: newCursorRow,
        cursorCol: newCursorCol,
        preferredCol: null
      };
    }
    case "delete_word_right": {
      const { cursorRow, cursorCol, lines } = state;
      const lineContent = currentLine(cursorRow);
      const lineLen = cpLen(lineContent);
      if (cursorCol >= lineLen && cursorRow === lines.length - 1) {
        return state;
      }
      const nextState = pushUndoLocal(state);
      const newLines = [...nextState.lines];
      if (cursorCol >= lineLen) {
        const nextLineContent = currentLine(cursorRow + 1);
        newLines[cursorRow] = lineContent + nextLineContent;
        newLines.splice(cursorRow + 1, 1);
      } else {
        const arr = toCodePoints(lineContent);
        const boundaries = getWordBoundaries(lineContent, arr);
        const endBoundary = findNextWordEnd(boundaries, cursorCol);
        let end;
        if (endBoundary !== null) {
          end = endBoundary;
          while (end < arr.length && isWhitespace(arr[end] ?? "")) {
            end++;
          }
        } else {
          const nextWordStart = findNextWordStartInLine(lineContent, cursorCol);
          end = nextWordStart === null ? lineLen : nextWordStart;
        }
        newLines[cursorRow] = cpSlice(lineContent, 0, cursorCol) + cpSlice(lineContent, end);
      }
      return {
        ...nextState,
        lines: newLines,
        preferredCol: null
      };
    }
    case "kill_line_right": {
      const { cursorRow, cursorCol, lines } = state;
      const lineContent = currentLine(cursorRow);
      if (cursorCol < currentLineLen(cursorRow)) {
        const nextState = pushUndoLocal(state);
        const newLines = [...nextState.lines];
        newLines[cursorRow] = cpSlice(lineContent, 0, cursorCol);
        return {
          ...nextState,
          lines: newLines
        };
      } else if (cursorRow < lines.length - 1) {
        const nextState = pushUndoLocal(state);
        const nextLineContent = currentLine(cursorRow + 1);
        const newLines = [...nextState.lines];
        newLines[cursorRow] = lineContent + nextLineContent;
        newLines.splice(cursorRow + 1, 1);
        return {
          ...nextState,
          lines: newLines,
          preferredCol: null
        };
      }
      return state;
    }
    case "kill_line_left": {
      const { cursorRow, cursorCol } = state;
      if (cursorCol > 0) {
        const nextState = pushUndoLocal(state);
        const lineContent = currentLine(cursorRow);
        const newLines = [...nextState.lines];
        newLines[cursorRow] = cpSlice(lineContent, cursorCol);
        return {
          ...nextState,
          lines: newLines,
          cursorCol: 0,
          preferredCol: null
        };
      } else if (cursorRow > 0) {
        const nextState = pushUndoLocal(state);
        const prevLineContent = currentLine(cursorRow - 1);
        const currentLineContent = currentLine(cursorRow);
        const newCol = cpLen(prevLineContent);
        const newLines = [...nextState.lines];
        newLines[cursorRow - 1] = prevLineContent + currentLineContent;
        newLines.splice(cursorRow, 1);
        return {
          ...nextState,
          lines: newLines,
          cursorRow: cursorRow - 1,
          cursorCol: newCol,
          preferredCol: null
        };
      }
      return state;
    }
    case "undo": {
      const stateToRestore = state.undoStack[state.undoStack.length - 1];
      if (!stateToRestore) return state;
      const currentSnapshot = {
        lines: [...state.lines],
        cursorRow: state.cursorRow,
        cursorCol: state.cursorCol
      };
      return {
        ...state,
        ...stateToRestore,
        undoStack: state.undoStack.slice(0, -1),
        redoStack: [...state.redoStack, currentSnapshot]
      };
    }
    case "redo": {
      const stateToRestore = state.redoStack[state.redoStack.length - 1];
      if (!stateToRestore) return state;
      const currentSnapshot = {
        lines: [...state.lines],
        cursorRow: state.cursorRow,
        cursorCol: state.cursorCol
      };
      return {
        ...state,
        ...stateToRestore,
        redoStack: state.redoStack.slice(0, -1),
        undoStack: [...state.undoStack, currentSnapshot]
      };
    }
    case "replace_range": {
      const { startRow, startCol, endRow, endCol, text } = action.payload;
      const nextState = pushUndoLocal(state);
      return replaceRangeInternal(
        nextState,
        startRow,
        startCol,
        endRow,
        endCol,
        text
      );
    }
    case "move_to_offset": {
      const { offset } = action.payload;
      const [newRow, newCol] = offsetToLogicalPos(
        state.lines.join("\n"),
        offset
      );
      return {
        ...state,
        cursorRow: newRow,
        cursorCol: newCol,
        preferredCol: null
      };
    }
    case "create_undo_snapshot": {
      return pushUndoLocal(state);
    }
    // Vim-specific operations
    case "vim_delete_word_forward":
    case "vim_delete_word_backward":
    case "vim_delete_word_end":
    case "vim_change_word_forward":
    case "vim_change_word_backward":
    case "vim_change_word_end":
    case "vim_delete_line":
    case "vim_change_line":
    case "vim_delete_to_end_of_line":
    case "vim_change_to_end_of_line":
    case "vim_change_movement":
    case "vim_delete_movement":
    case "vim_move_left":
    case "vim_move_right":
    case "vim_move_up":
    case "vim_move_down":
    case "vim_move_word_forward":
    case "vim_move_word_backward":
    case "vim_move_word_end":
    case "vim_delete_char":
    case "vim_insert_at_cursor":
    case "vim_append_at_cursor":
    case "vim_open_line_below":
    case "vim_open_line_above":
    case "vim_append_at_line_end":
    case "vim_insert_at_line_start":
    case "vim_move_to_line_start":
    case "vim_move_to_line_end":
    case "vim_move_to_first_nonwhitespace":
    case "vim_move_to_first_line":
    case "vim_move_to_last_line":
    case "vim_move_to_line":
    case "vim_escape_insert_mode":
      return handleVimAction(state, action);
    default: {
      const exhaustiveCheck = action;
      debugLogger4.error(`Unknown action encountered: ${exhaustiveCheck}`);
      return state;
    }
  }
}
__name(textBufferReducerLogic, "textBufferReducerLogic");
function textBufferReducer(state, action) {
  const newState = textBufferReducerLogic(state, action);
  if (newState.lines !== state.lines || newState.viewportWidth !== state.viewportWidth) {
    return {
      ...newState,
      visualLayout: calculateLayout(newState.lines, newState.viewportWidth)
    };
  }
  return newState;
}
__name(textBufferReducer, "textBufferReducer");
function looksLikePath(str) {
  const unquoted = str.replace(/^'(.*)'$/, "$1");
  const inner = unquoted.startsWith("'") ? unquoted.slice(1) : unquoted;
  return inner.startsWith("/") || inner.startsWith("./") || inner.startsWith("../") || inner.startsWith("~/") || inner.startsWith(".") || /^[A-Za-z]:/.test(inner);
}
__name(looksLikePath, "looksLikePath");
function tryExtractFilePaths(content, isValidPath) {
  const normalized = content.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
  const lines = normalized.split(/\n/).filter((s) => s.trim().length > 0);
  const validPaths = [];
  const hadNonPathToken = { value: false };
  for (const line of lines) {
    if (hadNonPathToken.value) break;
    const quotedPathRegex = /'((?:[~/.]|[A-Za-z]:)[^']*)'/g;
    let lastIndex = 0;
    let match;
    let hasQuotedPaths = false;
    while ((match = quotedPathRegex.exec(line)) !== null) {
      const gap = line.slice(lastIndex, match.index).trim();
      if (gap) {
        const gapPaths = extractPathsFromSegment(
          gap,
          isValidPath,
          hadNonPathToken
        );
        validPaths.push(...gapPaths);
      }
      const unescaped = unescapePath(match[1]);
      if (isValidPath(unescaped)) {
        validPaths.push(`@${escapePath(unescaped)}`);
      } else {
        hadNonPathToken.value = true;
      }
      lastIndex = quotedPathRegex.lastIndex;
      hasQuotedPaths = true;
    }
    if (hasQuotedPaths) {
      const trailing = line.slice(lastIndex).trim();
      if (trailing) {
        const trailingPaths = extractPathsFromSegment(
          trailing,
          isValidPath,
          hadNonPathToken
        );
        validPaths.push(...trailingPaths);
      }
    } else {
      const linePaths = extractPathsFromSegment(
        line.trim(),
        isValidPath,
        hadNonPathToken
      );
      validPaths.push(...linePaths);
    }
  }
  if (validPaths.length > 0 && !hadNonPathToken.value) {
    return validPaths;
  }
  return null;
}
__name(tryExtractFilePaths, "tryExtractFilePaths");
function extractPathsFromSegment(segment, isValidPath, hadNonPathToken) {
  const tokens = segment.split(/\s+/).filter(Boolean);
  const paths = [];
  let i = 0;
  while (i < tokens.length) {
    if (hadNonPathToken.value) break;
    if (tokens.length > 1 && !looksLikePath(tokens[i])) {
      hadNonPathToken.value = true;
      i++;
      continue;
    }
    let found = false;
    for (let j = tokens.length; j >= i + 1; j--) {
      const candidate = tokens.slice(i, j).join(" ");
      let unquoted = candidate;
      const quoteMatch = unquoted.match(/^'(.*)'$/);
      if (quoteMatch) {
        unquoted = quoteMatch[1];
      }
      const unescaped = unescapePath(unquoted);
      if (isValidPath(unescaped)) {
        paths.push(`@${escapePath(unescaped)}`);
        i = j;
        found = true;
        break;
      }
    }
    if (!found) {
      hadNonPathToken.value = true;
      i++;
    }
  }
  return paths;
}
__name(extractPathsFromSegment, "extractPathsFromSegment");
function useTextBuffer({
  initialText = "",
  initialCursorOffset = 0,
  viewport,
  stdin,
  setRawMode,
  onChange,
  isValidPath,
  shellModeActive = false,
  preferredEditor
}) {
  const initialState = (0, import_react12.useMemo)(() => {
    const lines2 = initialText.split("\n");
    const [initialCursorRow, initialCursorCol] = calculateInitialCursorPosition(
      lines2.length === 0 ? [""] : lines2,
      initialCursorOffset
    );
    const visualLayout2 = calculateLayout(
      lines2.length === 0 ? [""] : lines2,
      viewport.width
    );
    return {
      lines: lines2.length === 0 ? [""] : lines2,
      cursorRow: initialCursorRow,
      cursorCol: initialCursorCol,
      preferredCol: null,
      undoStack: [],
      redoStack: [],
      clipboard: null,
      selectionAnchor: null,
      viewportWidth: viewport.width,
      viewportHeight: viewport.height,
      visualLayout: visualLayout2
    };
  }, [initialText, initialCursorOffset, viewport.width, viewport.height]);
  const stateRef = (0, import_react12.useRef)(initialState);
  const [state, setState] = (0, import_react12.useState)(initialState);
  const dispatch = (0, import_react12.useCallback)((action) => {
    stateRef.current = textBufferReducer(stateRef.current, action);
    setState(stateRef.current);
  }, []);
  const {
    lines,
    cursorRow,
    cursorCol,
    preferredCol,
    selectionAnchor,
    visualLayout
  } = state;
  const text = (0, import_react12.useMemo)(() => lines.join("\n"), [lines]);
  const visualCursor = (0, import_react12.useMemo)(
    () => calculateVisualCursorFromLayout(visualLayout, [cursorRow, cursorCol]),
    [visualLayout, cursorRow, cursorCol]
  );
  const { visualLines, visualToLogicalMap } = visualLayout;
  const [visualScrollRow, setVisualScrollRow] = (0, import_react12.useState)(0);
  (0, import_react12.useEffect)(() => {
    if (onChange) {
      onChange(text);
    }
  }, [text, onChange]);
  (0, import_react12.useEffect)(() => {
    dispatch({
      type: "set_viewport",
      payload: { width: viewport.width, height: viewport.height }
    });
  }, [dispatch, viewport.width, viewport.height]);
  (0, import_react12.useEffect)(() => {
    const { height } = viewport;
    const totalVisualLines = visualLines.length;
    const maxScrollStart = Math.max(0, totalVisualLines - height);
    let newVisualScrollRow = visualScrollRow;
    if (visualCursor[0] < visualScrollRow) {
      newVisualScrollRow = visualCursor[0];
    } else if (visualCursor[0] >= visualScrollRow + height) {
      newVisualScrollRow = visualCursor[0] - height + 1;
    }
    newVisualScrollRow = clamp(newVisualScrollRow, 0, maxScrollStart);
    if (newVisualScrollRow !== visualScrollRow) {
      setVisualScrollRow(newVisualScrollRow);
    }
  }, [visualCursor, visualScrollRow, viewport, visualLines.length]);
  const insert = (0, import_react12.useCallback)(
    (ch, { paste = false } = {}) => {
      if (paste && /[\n\r]/.test(ch) && !shellModeActive) {
        const validPaths = tryExtractFilePaths(ch, isValidPath);
        if (validPaths) {
          ch = `${validPaths.join(" ")} `;
        }
        dispatch({ type: "insert", payload: ch });
        return;
      }
      if (/[\n\r]/.test(ch)) {
        dispatch({ type: "insert", payload: ch });
        return;
      }
      const minLengthToInferAsDragDrop = 3;
      if (paste && ch.length >= minLengthToInferAsDragDrop && !shellModeActive) {
        const validPaths = tryExtractFilePaths(ch.trim(), isValidPath);
        if (validPaths) {
          ch = `${validPaths.join(" ")} `;
        }
      }
      let currentText = "";
      for (const char of toCodePoints(ch)) {
        if (char.codePointAt(0) === 127) {
          if (currentText.length > 0) {
            dispatch({ type: "insert", payload: currentText });
            currentText = "";
          }
          dispatch({ type: "backspace" });
        } else {
          currentText += char;
        }
      }
      if (currentText.length > 0) {
        dispatch({ type: "insert", payload: currentText });
      }
    },
    [dispatch, isValidPath, shellModeActive]
  );
  const newline = (0, import_react12.useCallback)(() => {
    dispatch({ type: "insert", payload: "\n" });
  }, [dispatch]);
  const backspace = (0, import_react12.useCallback)(() => {
    dispatch({ type: "backspace" });
  }, [dispatch]);
  const del = (0, import_react12.useCallback)(() => {
    dispatch({ type: "delete" });
  }, [dispatch]);
  const move = (0, import_react12.useCallback)(
    (dir) => {
      dispatch({ type: "move", payload: { dir } });
    },
    [dispatch]
  );
  const undo = (0, import_react12.useCallback)(() => {
    dispatch({ type: "undo" });
  }, [dispatch]);
  const redo = (0, import_react12.useCallback)(() => {
    dispatch({ type: "redo" });
  }, [dispatch]);
  const setText = (0, import_react12.useCallback)(
    (newText) => {
      dispatch({ type: "set_text", payload: newText });
    },
    [dispatch]
  );
  const deleteWordLeft = (0, import_react12.useCallback)(() => {
    dispatch({ type: "delete_word_left" });
  }, [dispatch]);
  const deleteWordRight = (0, import_react12.useCallback)(() => {
    dispatch({ type: "delete_word_right" });
  }, [dispatch]);
  const killLineRight = (0, import_react12.useCallback)(() => {
    dispatch({ type: "kill_line_right" });
  }, [dispatch]);
  const killLineLeft = (0, import_react12.useCallback)(() => {
    dispatch({ type: "kill_line_left" });
  }, [dispatch]);
  const vimDeleteWordForward = (0, import_react12.useCallback)(
    (count) => {
      dispatch({ type: "vim_delete_word_forward", payload: { count } });
    },
    [dispatch]
  );
  const vimDeleteWordBackward = (0, import_react12.useCallback)(
    (count) => {
      dispatch({ type: "vim_delete_word_backward", payload: { count } });
    },
    [dispatch]
  );
  const vimDeleteWordEnd = (0, import_react12.useCallback)(
    (count) => {
      dispatch({ type: "vim_delete_word_end", payload: { count } });
    },
    [dispatch]
  );
  const vimChangeWordForward = (0, import_react12.useCallback)(
    (count) => {
      dispatch({ type: "vim_change_word_forward", payload: { count } });
    },
    [dispatch]
  );
  const vimChangeWordBackward = (0, import_react12.useCallback)(
    (count) => {
      dispatch({ type: "vim_change_word_backward", payload: { count } });
    },
    [dispatch]
  );
  const vimChangeWordEnd = (0, import_react12.useCallback)(
    (count) => {
      dispatch({ type: "vim_change_word_end", payload: { count } });
    },
    [dispatch]
  );
  const vimDeleteLine = (0, import_react12.useCallback)(
    (count) => {
      dispatch({ type: "vim_delete_line", payload: { count } });
    },
    [dispatch]
  );
  const vimChangeLine = (0, import_react12.useCallback)(
    (count) => {
      dispatch({ type: "vim_change_line", payload: { count } });
    },
    [dispatch]
  );
  const vimDeleteToEndOfLine = (0, import_react12.useCallback)(() => {
    dispatch({ type: "vim_delete_to_end_of_line" });
  }, [dispatch]);
  const vimChangeToEndOfLine = (0, import_react12.useCallback)(() => {
    dispatch({ type: "vim_change_to_end_of_line" });
  }, [dispatch]);
  const vimChangeMovement = (0, import_react12.useCallback)(
    (movement, count) => {
      dispatch({ type: "vim_change_movement", payload: { movement, count } });
    },
    [dispatch]
  );
  const vimDeleteMovement = (0, import_react12.useCallback)(
    (movement, count) => {
      dispatch({ type: "vim_delete_movement", payload: { movement, count } });
    },
    [dispatch]
  );
  const vimMoveLeft = (0, import_react12.useCallback)(
    (count) => {
      dispatch({ type: "vim_move_left", payload: { count } });
    },
    [dispatch]
  );
  const vimMoveRight = (0, import_react12.useCallback)(
    (count) => {
      dispatch({ type: "vim_move_right", payload: { count } });
    },
    [dispatch]
  );
  const vimMoveUp = (0, import_react12.useCallback)(
    (count) => {
      dispatch({ type: "vim_move_up", payload: { count } });
    },
    [dispatch]
  );
  const vimMoveDown = (0, import_react12.useCallback)(
    (count) => {
      dispatch({ type: "vim_move_down", payload: { count } });
    },
    [dispatch]
  );
  const vimMoveWordForward = (0, import_react12.useCallback)(
    (count) => {
      dispatch({ type: "vim_move_word_forward", payload: { count } });
    },
    [dispatch]
  );
  const vimMoveWordBackward = (0, import_react12.useCallback)(
    (count) => {
      dispatch({ type: "vim_move_word_backward", payload: { count } });
    },
    [dispatch]
  );
  const vimMoveWordEnd = (0, import_react12.useCallback)(
    (count) => {
      dispatch({ type: "vim_move_word_end", payload: { count } });
    },
    [dispatch]
  );
  const vimDeleteChar = (0, import_react12.useCallback)(
    (count) => {
      dispatch({ type: "vim_delete_char", payload: { count } });
    },
    [dispatch]
  );
  const vimInsertAtCursor = (0, import_react12.useCallback)(() => {
    dispatch({ type: "vim_insert_at_cursor" });
  }, [dispatch]);
  const vimAppendAtCursor = (0, import_react12.useCallback)(() => {
    dispatch({ type: "vim_append_at_cursor" });
  }, [dispatch]);
  const vimOpenLineBelow = (0, import_react12.useCallback)(() => {
    dispatch({ type: "vim_open_line_below" });
  }, [dispatch]);
  const vimOpenLineAbove = (0, import_react12.useCallback)(() => {
    dispatch({ type: "vim_open_line_above" });
  }, [dispatch]);
  const vimAppendAtLineEnd = (0, import_react12.useCallback)(() => {
    dispatch({ type: "vim_append_at_line_end" });
  }, [dispatch]);
  const vimInsertAtLineStart = (0, import_react12.useCallback)(() => {
    dispatch({ type: "vim_insert_at_line_start" });
  }, [dispatch]);
  const vimMoveToLineStart = (0, import_react12.useCallback)(() => {
    dispatch({ type: "vim_move_to_line_start" });
  }, [dispatch]);
  const vimMoveToLineEnd = (0, import_react12.useCallback)(() => {
    dispatch({ type: "vim_move_to_line_end" });
  }, [dispatch]);
  const vimMoveToFirstNonWhitespace = (0, import_react12.useCallback)(() => {
    dispatch({ type: "vim_move_to_first_nonwhitespace" });
  }, [dispatch]);
  const vimMoveToFirstLine = (0, import_react12.useCallback)(() => {
    dispatch({ type: "vim_move_to_first_line" });
  }, [dispatch]);
  const vimMoveToLastLine = (0, import_react12.useCallback)(() => {
    dispatch({ type: "vim_move_to_last_line" });
  }, [dispatch]);
  const vimMoveToLine = (0, import_react12.useCallback)(
    (lineNumber) => {
      dispatch({ type: "vim_move_to_line", payload: { lineNumber } });
    },
    [dispatch]
  );
  const vimEscapeInsertMode = (0, import_react12.useCallback)(() => {
    dispatch({ type: "vim_escape_insert_mode" });
  }, [dispatch]);
  const openInExternalEditor = (0, import_react12.useCallback)(
    async (opts = {}) => {
      let tmpDir;
      let filePath;
      try {
        tmpDir = fs2.mkdtempSync(pathMod.join(os2.tmpdir(), "qwen-edit-"));
        filePath = pathMod.join(tmpDir, "buffer.txt");
      } catch (err) {
        debugLogger4.error(
          "[useTextBuffer] failed to create temp directory",
          err
        );
        return;
      }
      let editorCmd;
      let editorArgs;
      let useShell = false;
      let editorSource = "env/default";
      if (opts.editor) {
        editorCmd = opts.editor;
        editorArgs = [filePath];
        editorSource = "opts";
        if (process.platform === "win32" && /\.(cmd|bat)$/i.test(editorCmd)) {
          if (/["|%!]/.test(editorCmd)) {
            debugLogger4.error(
              `[useTextBuffer] opts.editor command contains unsafe characters: ${editorCmd}`
            );
            try {
              fs2.rmSync(tmpDir, { recursive: true, force: true });
            } catch {
            }
            return;
          }
          useShell = true;
        }
      } else {
        const resolved = preferredEditor ? getExternalEditorCommand(preferredEditor, filePath) : null;
        if (resolved) {
          editorCmd = resolved.command;
          editorArgs = resolved.args;
          useShell = resolved.needsShell;
          editorSource = "preferred";
        } else {
          if (preferredEditor) {
            debugLogger4.warn(
              `[useTextBuffer] preferred editor "${preferredEditor}" not found, falling back to env/default`
            );
          }
          editorCmd = process.env["VISUAL"] ?? process.env["EDITOR"] ?? (process.platform === "win32" ? "notepad" : "vi");
          editorArgs = [filePath];
          if (process.platform === "win32" && /\.(cmd|bat)$/i.test(editorCmd)) {
            if (/["|%!]/.test(editorCmd)) {
              debugLogger4.error(
                `[useTextBuffer] Editor command from environment contains unsafe characters: ${editorCmd}`
              );
              try {
                fs2.rmSync(tmpDir, { recursive: true, force: true });
              } catch {
              }
              return;
            }
            useShell = true;
          }
        }
      }
      if (useShell) {
        editorCmd = `"${editorCmd}"`;
        editorArgs = editorArgs.map((a) => `"${a}"`);
      }
      const wasRaw = stdin?.isRaw ?? false;
      try {
        const currentText = stateRef.current.lines.join("\n");
        fs2.writeFileSync(filePath, currentText, {
          encoding: "utf8",
          mode: 384
        });
        setRawMode?.(false);
        debugLogger4.warn(
          `[useTextBuffer] launching external editor (cmd=${editorCmd}, shell=${useShell}, source=${editorSource}, file=${filePath})`
        );
        const { status, error, signal } = spawnSync2(editorCmd, editorArgs, {
          stdio: "inherit",
          shell: useShell,
          timeout: 30 * 60 * 1e3
        });
        if (error) throw error;
        if (signal)
          throw new Error(`External editor was killed by signal ${signal}`);
        if (typeof status === "number" && status !== 0)
          throw new Error(`External editor exited with status ${status}`);
        let newText = fs2.readFileSync(filePath, "utf8");
        newText = newText.replace(/\r\n?/g, "\n");
        if (newText !== currentText) {
          dispatch({ type: "create_undo_snapshot" });
          dispatch({ type: "set_text", payload: newText, pushToUndo: false });
        }
      } catch (err) {
        debugLogger4.error(
          `[useTextBuffer] external editor error (cmd=${editorCmd}, shell=${useShell}, source=${editorSource}, file=${filePath})`,
          err
        );
      } finally {
        try {
          if (wasRaw) setRawMode?.(true);
        } catch (rawErr) {
          debugLogger4.error(
            "[useTextBuffer] failed to restore raw mode after external editor",
            rawErr
          );
        }
        try {
          fs2.rmSync(tmpDir, { recursive: true, force: true });
        } catch {
        }
      }
    },
    [dispatch, stdin, setRawMode, preferredEditor]
  );
  const handleInput = (0, import_react12.useCallback)(
    (key) => {
      const { sequence: input } = key;
      if (key.paste) {
        insert(input, { paste: key.paste });
        return;
      }
      if (key.name === "return" || input === "\r" || input === "\n" || input === "\\\r")
        newline();
      else if (key.name === "left" && !key.meta && !key.ctrl) move("left");
      else if (key.ctrl && key.name === "b") move("left");
      else if (key.name === "right" && !key.meta && !key.ctrl) move("right");
      else if (key.ctrl && key.name === "f") move("right");
      else if (key.name === "up" && !key.shift) move("up");
      else if (key.name === "down" && !key.shift) move("down");
      else if ((key.ctrl || key.meta) && key.name === "left") move("wordLeft");
      else if (key.meta && key.name === "b") move("wordLeft");
      else if ((key.ctrl || key.meta) && key.name === "right")
        move("wordRight");
      else if (key.meta && key.name === "d") deleteWordRight();
      else if (key.meta && key.name === "f") move("wordRight");
      else if (key.name === "home") move("home");
      else if (key.ctrl && key.name === "a") move("home");
      else if (key.name === "end") move("end");
      else if (key.ctrl && key.name === "e") move("end");
      else if (key.ctrl && key.name === "w") deleteWordLeft();
      else if ((key.meta || key.ctrl) && (key.name === "backspace" || input === "\x7F"))
        deleteWordLeft();
      else if ((key.meta || key.ctrl) && key.name === "delete")
        deleteWordRight();
      else if (key.name === "backspace" || input === "\x7F" || key.ctrl && key.name === "h")
        backspace();
      else if (key.name === "delete" || key.ctrl && key.name === "d") del();
      else if (key.ctrl && !key.shift && key.name === "z") undo();
      else if (key.ctrl && key.shift && key.name === "z") redo();
      else if (input && !key.ctrl && !key.meta && key.name !== "tab" && input !== "	") {
        insert(input, { paste: key.paste });
      }
    },
    [
      newline,
      move,
      deleteWordLeft,
      deleteWordRight,
      backspace,
      del,
      insert,
      undo,
      redo
    ]
  );
  const renderedVisualLines = (0, import_react12.useMemo)(
    () => visualLines.slice(visualScrollRow, visualScrollRow + viewport.height),
    [visualLines, visualScrollRow, viewport.height]
  );
  const replaceRange = (0, import_react12.useCallback)(
    (startRow, startCol, endRow, endCol, text2) => {
      dispatch({
        type: "replace_range",
        payload: { startRow, startCol, endRow, endCol, text: text2 }
      });
    },
    [dispatch]
  );
  const replaceRangeByOffset = (0, import_react12.useCallback)(
    (startOffset, endOffset, replacementText) => {
      const currentText = stateRef.current.lines.join("\n");
      const [startRow, startCol] = offsetToLogicalPos(currentText, startOffset);
      const [endRow, endCol] = offsetToLogicalPos(currentText, endOffset);
      replaceRange(startRow, startCol, endRow, endCol, replacementText);
    },
    [replaceRange]
  );
  const moveToOffset = (0, import_react12.useCallback)(
    (offset) => {
      dispatch({ type: "move_to_offset", payload: { offset } });
    },
    [dispatch]
  );
  const returnValue = (0, import_react12.useMemo)(
    () => ({
      get lines() {
        return stateRef.current.lines;
      },
      get text() {
        return stateRef.current.lines.join("\n");
      },
      get cursor() {
        return [stateRef.current.cursorRow, stateRef.current.cursorCol];
      },
      preferredCol,
      selectionAnchor,
      allVisualLines: visualLines,
      viewportVisualLines: renderedVisualLines,
      visualCursor,
      visualScrollRow,
      visualToLogicalMap,
      setText,
      insert,
      newline,
      backspace,
      del,
      move,
      undo,
      redo,
      replaceRange,
      replaceRangeByOffset,
      moveToOffset,
      deleteWordLeft,
      deleteWordRight,
      killLineRight,
      killLineLeft,
      handleInput,
      openInExternalEditor,
      // Vim-specific operations
      vimDeleteWordForward,
      vimDeleteWordBackward,
      vimDeleteWordEnd,
      vimChangeWordForward,
      vimChangeWordBackward,
      vimChangeWordEnd,
      vimDeleteLine,
      vimChangeLine,
      vimDeleteToEndOfLine,
      vimChangeToEndOfLine,
      vimChangeMovement,
      vimDeleteMovement,
      vimMoveLeft,
      vimMoveRight,
      vimMoveUp,
      vimMoveDown,
      vimMoveWordForward,
      vimMoveWordBackward,
      vimMoveWordEnd,
      vimDeleteChar,
      vimInsertAtCursor,
      vimAppendAtCursor,
      vimOpenLineBelow,
      vimOpenLineAbove,
      vimAppendAtLineEnd,
      vimInsertAtLineStart,
      vimMoveToLineStart,
      vimMoveToLineEnd,
      vimMoveToFirstNonWhitespace,
      vimMoveToFirstLine,
      vimMoveToLastLine,
      vimMoveToLine,
      vimEscapeInsertMode
    }),
    [
      preferredCol,
      selectionAnchor,
      visualLines,
      renderedVisualLines,
      visualCursor,
      visualScrollRow,
      setText,
      insert,
      newline,
      backspace,
      del,
      move,
      undo,
      redo,
      replaceRange,
      replaceRangeByOffset,
      moveToOffset,
      deleteWordLeft,
      deleteWordRight,
      killLineRight,
      killLineLeft,
      handleInput,
      openInExternalEditor,
      vimDeleteWordForward,
      vimDeleteWordBackward,
      vimDeleteWordEnd,
      vimChangeWordForward,
      vimChangeWordBackward,
      vimChangeWordEnd,
      vimDeleteLine,
      vimChangeLine,
      vimDeleteToEndOfLine,
      vimChangeToEndOfLine,
      vimChangeMovement,
      vimDeleteMovement,
      vimMoveLeft,
      vimMoveRight,
      vimMoveUp,
      vimMoveDown,
      vimMoveWordForward,
      vimMoveWordBackward,
      vimMoveWordEnd,
      vimDeleteChar,
      vimInsertAtCursor,
      vimAppendAtCursor,
      vimOpenLineBelow,
      vimOpenLineAbove,
      vimAppendAtLineEnd,
      vimInsertAtLineStart,
      vimMoveToLineStart,
      vimMoveToLineEnd,
      vimMoveToFirstNonWhitespace,
      vimMoveToFirstLine,
      vimMoveToLastLine,
      vimMoveToLine,
      vimEscapeInsertMode,
      visualToLogicalMap
    ]
  );
  return returnValue;
}
__name(useTextBuffer, "useTextBuffer");

// packages/cli/src/ui/hooks/usePreferredEditor.ts
init_esbuild_shims();
var import_react13 = __toESM(require_react(), 1);
var debugLogger5 = createDebugLogger("PREFERRED_EDITOR");
function usePreferredEditor() {
  const settings = useSettings();
  return (0, import_react13.useMemo)(() => {
    const raw = settings.merged.general?.preferredEditor ?? "";
    if (raw && !isValidEditorType(raw)) {
      debugLogger5.warn(
        `[usePreferredEditor] invalid preferredEditor value "${raw}", ignoring`
      );
      return void 0;
    }
    if (isValidEditorType(raw) && !allowEditorTypeInSandbox(raw)) {
      debugLogger5.warn(
        `[usePreferredEditor] editor "${raw}" is not allowed in sandbox mode, ignoring`
      );
      return void 0;
    }
    return isValidEditorType(raw) ? raw : void 0;
  }, [settings.merged.general?.preferredEditor]);
}
__name(usePreferredEditor, "usePreferredEditor");

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

// packages/cli/src/ui/utils/software-cursor.ts
init_esbuild_shims();
var import_chalk = __toESM(require_source(), 1);

// packages/cli/src/ui/utils/theme-background.ts
init_esbuild_shims();
var DARK_TERMINAL_BACKGROUND = "#000000";
var LIGHT_TERMINAL_BACKGROUND = "#ffffff";
function getEffectiveTerminalBackground() {
  return themeManager.getTerminalBackgroundType() === "light" ? LIGHT_TERMINAL_BACKGROUND : DARK_TERMINAL_BACKGROUND;
}
__name(getEffectiveTerminalBackground, "getEffectiveTerminalBackground");

// packages/cli/src/ui/utils/software-cursor.ts
var LIGHT_CURSOR_BACKGROUND = "#D4D4D4";
var DARK_CURSOR_BACKGROUND = "#3A3A3A";
var INK_NAME_TO_HEX = {
  black: "#000000",
  red: "#ff0000",
  green: "#00ff00",
  yellow: "#ffff00",
  blue: "#0000ff",
  cyan: "#00ffff",
  magenta: "#ff00ff",
  white: "#ffffff",
  gray: "#808080",
  grey: "#808080",
  blackbright: "#808080",
  redbright: "#ff8080",
  greenbright: "#80ff80",
  yellowbright: "#ffff80",
  bluebright: "#8080ff",
  cyanbright: "#80ffff",
  magentabright: "#ff80ff",
  whitebright: "#ffffff"
};
function toHex(color) {
  const resolved = resolveColor(color) ?? color;
  const lower = resolved.toLowerCase();
  if (/^#[0-9a-f]{3}$/.test(lower)) {
    return `#${lower.slice(1).split("").map((c) => c + c).join("")}`;
  }
  if (/^#[0-9a-f]{6}$/.test(lower)) {
    return lower;
  }
  return INK_NAME_TO_HEX[lower];
}
__name(toHex, "toHex");
function getSoftwareCursorBackground(backgroundColor = getEffectiveTerminalBackground()) {
  const hex = backgroundColor ? toHex(backgroundColor) : void 0;
  if (!hex) {
    return LIGHT_CURSOR_BACKGROUND;
  }
  const r = parseInt(hex.slice(1, 3), 16);
  const g = parseInt(hex.slice(3, 5), 16);
  const b = parseInt(hex.slice(5, 7), 16);
  const luminance = (r * 299 + g * 587 + b * 114) / 1e3;
  return luminance >= 128 ? DARK_CURSOR_BACKGROUND : LIGHT_CURSOR_BACKGROUND;
}
__name(getSoftwareCursorBackground, "getSoftwareCursorBackground");
function renderSoftwareCursor(text) {
  return import_chalk.default.bgHex(getSoftwareCursorBackground())(text || " ");
}
__name(renderSoftwareCursor, "renderSoftwareCursor");

// packages/cli/src/ui/components/shared/TextInput.tsx
var import_jsx_runtime13 = __toESM(require_jsx_runtime(), 1);
function ellipsizeMiddle(text, width) {
  if (width <= 0) return "";
  if (stringWidth(text) <= width) return text;
  if (width <= 3) return cpSlice(text, 0, width);
  const available = width - 3;
  const headLength = Math.ceil(available / 2);
  const tailLength = Math.floor(available / 2);
  return `${cpSlice(text, 0, headLength)}...${cpSlice(
    text,
    cpLen(text) - tailLength
  )}`;
}
__name(ellipsizeMiddle, "ellipsizeMiddle");
function TextInput({
  value,
  onChange,
  onSubmit,
  onTab,
  onUp,
  onDown,
  placeholder,
  height = 1,
  isActive = true,
  validationErrors = [],
  inputWidth = 80,
  initialCursorOffset,
  ellipsizeOverflow = false
}) {
  const allowMultiline = height > 1;
  const [cursorVisible, setCursorVisible] = (0, import_react14.useState)(isActive);
  const onChangeRef = (0, import_react14.useRef)(onChange);
  (0, import_react14.useEffect)(() => {
    onChangeRef.current = onChange;
  }, [onChange]);
  const stableOnChange = (0, import_react14.useCallback)((text) => {
    onChangeRef.current?.(text);
  }, []);
  const preferredEditor = usePreferredEditor();
  const { stdin, setRawMode } = use_stdin_default();
  const buffer = useTextBuffer({
    initialText: value || "",
    initialCursorOffset,
    viewport: { height, width: inputWidth },
    stdin,
    setRawMode,
    isValidPath: /* @__PURE__ */ __name(() => false, "isValidPath"),
    onChange: stableOnChange,
    preferredEditor
  });
  (0, import_react14.useEffect)(() => {
    if (!isActive) {
      setCursorVisible(false);
      return;
    }
    setCursorVisible(true);
    const interval = setInterval(() => {
      setCursorVisible((visible) => !visible);
    }, 530);
    return () => clearInterval(interval);
  }, [isActive]);
  const handleSubmit = /* @__PURE__ */ __name(() => {
    if (!onSubmit) return;
    onSubmit(buffer.text);
  }, "handleSubmit");
  useKeypress(
    (key) => {
      if (!buffer || !isActive) return;
      if (key.name === "tab" && !key.paste) {
        onTab?.(key);
        return;
      }
      if (key.name === "up" && onUp) {
        onUp();
        return;
      }
      if (key.name === "down" && onDown) {
        onDown();
        return;
      }
      if (allowMultiline && keyMatchers["newline" /* NEWLINE */](key)) {
        buffer.newline();
        return;
      }
      if (keyMatchers["submit" /* SUBMIT */](key) || !allowMultiline && key.name === "return") {
        handleSubmit();
        return;
      }
      if (keyMatchers["home" /* HOME */](key)) {
        buffer.move("home");
        return;
      }
      if (keyMatchers["end" /* END */](key)) {
        buffer.move("end");
        buffer.moveToOffset(cpLen(buffer.text));
        return;
      }
      if (keyMatchers["clearInput" /* CLEAR_INPUT */](key)) {
        if (buffer.text.length > 0) buffer.setText("");
        return;
      }
      if (keyMatchers["killLineRight" /* KILL_LINE_RIGHT */](key)) {
        buffer.killLineRight();
        return;
      }
      if (keyMatchers["killLineLeft" /* KILL_LINE_LEFT */](key)) {
        buffer.killLineLeft();
        return;
      }
      if (keyMatchers["openExternalEditor" /* OPEN_EXTERNAL_EDITOR */](key)) {
        buffer.openInExternalEditor();
        return;
      }
      buffer.handleInput(key);
    },
    { isActive }
  );
  if (!buffer) return null;
  const linesToRender = buffer.viewportVisualLines;
  const [cursorVisualRowAbsolute, cursorVisualColAbsolute] = buffer.visualCursor;
  const scrollVisualRow = buffer.visualScrollRow;
  const shouldRenderCursor = isActive && cursorVisible;
  return /* @__PURE__ */ (0, import_jsx_runtime13.jsxs)(Box_default, { flexDirection: "column", gap: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime13.jsxs)(Box_default, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(Text, { color: theme.text.accent, children: "> " }),
      /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(Box_default, { flexGrow: 1, flexDirection: "column", children: buffer.text.length === 0 && placeholder ? shouldRenderCursor ? /* @__PURE__ */ (0, import_jsx_runtime13.jsxs)(Text, { children: [
        renderSoftwareCursor(placeholder.slice(0, 1)),
        /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(Text, { color: Colors.Gray, children: placeholder.slice(1) })
      ] }) : /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(Text, { color: Colors.Gray, children: placeholder }) : ellipsizeOverflow && stringWidth(buffer.text) > inputWidth ? /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(Text, { children: ellipsizeMiddle(buffer.text, inputWidth) }) : linesToRender.map((lineText, visualIdxInRenderedSet) => {
        const cursorVisualRow = cursorVisualRowAbsolute - scrollVisualRow;
        let display = cpSlice(lineText, 0, inputWidth);
        const currentVisualWidth = stringWidth(display);
        if (currentVisualWidth < inputWidth) {
          display = display + " ".repeat(inputWidth - currentVisualWidth);
        }
        if (shouldRenderCursor && visualIdxInRenderedSet === cursorVisualRow) {
          const relativeVisualColForHighlight = cursorVisualColAbsolute;
          if (relativeVisualColForHighlight >= 0) {
            if (relativeVisualColForHighlight < cpLen(display)) {
              const charToHighlight = cpSlice(
                display,
                relativeVisualColForHighlight,
                relativeVisualColForHighlight + 1
              ) || " ";
              const highlighted = renderSoftwareCursor(charToHighlight);
              display = cpSlice(display, 0, relativeVisualColForHighlight) + highlighted + cpSlice(display, relativeVisualColForHighlight + 1);
            } else if (relativeVisualColForHighlight === cpLen(display) && cpLen(display) === inputWidth) {
              display = display + renderSoftwareCursor(" ");
            }
          }
        }
        return /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(Text, { children: display }, `line-${visualIdxInRenderedSet}`);
      }) })
    ] }),
    validationErrors.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(Box_default, { flexDirection: "column", children: validationErrors.map((error, index) => /* @__PURE__ */ (0, import_jsx_runtime13.jsxs)(Text, { color: theme.status.error, children: [
      "\u26A0 ",
      error
    ] }, index)) })
  ] });
}
__name(TextInput, "TextInput");

// packages/cli/src/ui/components/messages/AskUserQuestionDialog.tsx
var import_jsx_runtime14 = __toESM(require_jsx_runtime(), 1);
var AskUserQuestionDialog = /* @__PURE__ */ __name(({
  confirmationDetails,
  isFocused = true,
  onConfirm
}) => {
  const [currentQuestionIndex, setCurrentQuestionIndex] = (0, import_react15.useState)(0);
  const [selectedOptions, setSelectedOptions] = (0, import_react15.useState)({});
  const [customInputValues, setCustomInputValues] = (0, import_react15.useState)({});
  const customInputValuesRef = (0, import_react15.useRef)({});
  const [selectedIndex, setSelectedIndex] = (0, import_react15.useState)(0);
  const [multiSelectedOptions, setMultiSelectedOptions] = (0, import_react15.useState)({});
  const [customInputChecked, setCustomInputChecked] = (0, import_react15.useState)({});
  const hasMultipleQuestions = confirmationDetails.questions.length > 1;
  const totalTabs = hasMultipleQuestions ? confirmationDetails.questions.length + 1 : confirmationDetails.questions.length;
  const isSubmitTab = hasMultipleQuestions && currentQuestionIndex === totalTabs - 1;
  const currentQuestion = isSubmitTab ? null : confirmationDetails.questions[currentQuestionIndex];
  const isMultiSelect = currentQuestion?.multiSelect ?? false;
  const totalOptions = currentQuestion ? currentQuestion.options.length + 1 : 2;
  const isCustomInputSelected = !isSubmitTab && currentQuestion && selectedIndex === currentQuestion.options.length;
  const getCustomInputValue = /* @__PURE__ */ __name((idx) => customInputValuesRef.current[idx] ?? customInputValues[idx] ?? "", "getCustomInputValue");
  const currentCustomInputValue = getCustomInputValue(currentQuestionIndex);
  const isCustomInputAnswer = !isSubmitTab && currentQuestion && !isMultiSelect && selectedOptions[currentQuestionIndex] !== void 0 && !currentQuestion.options.some(
    (opt) => opt.label === selectedOptions[currentQuestionIndex]
  );
  const getAnswerForQuestion = /* @__PURE__ */ __name((idx) => {
    const q = confirmationDetails.questions[idx];
    if (q?.multiSelect) {
      const selections = [...multiSelectedOptions[idx] ?? []];
      const customValue = getCustomInputValue(idx).trim();
      if (customInputChecked[idx] && customValue) {
        selections.push(customValue);
      }
      return selections.length > 0 ? selections.join(", ") : void 0;
    }
    return selectedOptions[idx];
  }, "getAnswerForQuestion");
  const handleSubmit = /* @__PURE__ */ __name(async () => {
    const answers = {};
    confirmationDetails.questions.forEach((_, idx) => {
      const answer = getAnswerForQuestion(idx);
      if (answer !== void 0) {
        answers[idx] = answer;
      }
    });
    await onConfirm("proceed_once" /* ProceedOnce */, { answers });
  }, "handleSubmit");
  const selectAndAdvance = /* @__PURE__ */ __name((value) => {
    setSelectedOptions((prev) => ({ ...prev, [currentQuestionIndex]: value }));
    if (!hasMultipleQuestions) {
      void onConfirm("proceed_once" /* ProceedOnce */, {
        answers: { [currentQuestionIndex]: value }
      });
    } else if (currentQuestionIndex < totalTabs - 1) {
      setTimeout(() => {
        setCurrentQuestionIndex((prev) => Math.min(prev + 1, totalTabs - 1));
        setSelectedIndex(0);
      }, 150);
    }
  }, "selectAndAdvance");
  const getCurrentMultiSelectAnswer = /* @__PURE__ */ __name((includeCustomInput = customInputChecked[currentQuestionIndex], inputValue = currentCustomInputValue) => {
    if (!currentQuestion) return;
    const selections = [...multiSelectedOptions[currentQuestionIndex] ?? []];
    const customValue = inputValue.trim();
    if (includeCustomInput && customValue) {
      selections.push(customValue);
    }
    return selections.length > 0 ? selections.join(", ") : void 0;
  }, "getCurrentMultiSelectAnswer");
  const handleMultiSelectSubmit = /* @__PURE__ */ __name(() => {
    const answer = getCurrentMultiSelectAnswer();
    if (!answer) return;
    selectAndAdvance(answer);
  }, "handleMultiSelectSubmit");
  const handleCustomInputSubmit = /* @__PURE__ */ __name((inputValue = currentCustomInputValue) => {
    const trimmedValue = inputValue.trim();
    if (isMultiSelect) {
      setCustomInputChecked((prev) => ({
        ...prev,
        [currentQuestionIndex]: trimmedValue.length > 0
      }));
      if (trimmedValue) {
        selectAndAdvance(getCurrentMultiSelectAnswer(true, inputValue));
      }
      return;
    }
    if (!trimmedValue) return;
    selectAndAdvance(trimmedValue);
  }, "handleCustomInputSubmit");
  useKeypress(
    (key) => {
      if (isCustomInputSelected) {
        const isOptionUp = key.name === "up" || key.ctrl && key.name === "p";
        const isOptionDown = key.name === "down" || key.ctrl && key.name === "n";
        if (isOptionUp) {
          setSelectedIndex(Math.max(0, selectedIndex - 1));
          return;
        }
        if (isOptionDown) {
          setSelectedIndex(Math.min(totalOptions - 1, selectedIndex + 1));
          return;
        }
        if (key.name === "escape" || key.ctrl && key.name === "c") {
          void onConfirm("cancel" /* Cancel */);
          return;
        }
        if (key.name === "return") {
          handleCustomInputSubmit();
          return;
        }
        return;
      }
      const input = key.sequence;
      if (key.name === "left" && hasMultipleQuestions) {
        if (currentQuestionIndex > 0) {
          setCurrentQuestionIndex(currentQuestionIndex - 1);
          setSelectedIndex(0);
        }
        return;
      }
      if (key.name === "right" && hasMultipleQuestions) {
        if (currentQuestionIndex < totalTabs - 1) {
          setCurrentQuestionIndex(currentQuestionIndex + 1);
          setSelectedIndex(0);
        }
        return;
      }
      if (keyMatchers["selectionUp" /* SELECTION_UP */](key)) {
        setSelectedIndex(Math.max(0, selectedIndex - 1));
        return;
      }
      if (keyMatchers["selectionDown" /* SELECTION_DOWN */](key)) {
        setSelectedIndex(Math.min(totalOptions - 1, selectedIndex + 1));
        return;
      }
      const numKey = input && /^[1-9]\d*$/.test(input) ? Number(input) : NaN;
      if (Number.isSafeInteger(numKey) && numKey <= totalOptions) {
        const targetIndex = numKey - 1;
        setSelectedIndex(targetIndex);
        if (!isMultiSelect && !isSubmitTab && currentQuestion && targetIndex < currentQuestion.options.length) {
          const option = currentQuestion.options[targetIndex];
          if (option) {
            selectAndAdvance(option.label);
          }
        }
        return;
      }
      if (key.name === "space" && isMultiSelect && currentQuestion) {
        if (selectedIndex < currentQuestion.options.length) {
          const option = currentQuestion.options[selectedIndex];
          if (option) {
            const current = multiSelectedOptions[currentQuestionIndex] ?? [];
            const isChecked = current.includes(option.label);
            const updated = isChecked ? current.filter((l) => l !== option.label) : [...current, option.label];
            setMultiSelectedOptions((prev) => ({
              ...prev,
              [currentQuestionIndex]: updated
            }));
          }
        }
        return;
      }
      if (key.name === "return") {
        if (isSubmitTab) {
          if (selectedIndex === 0) {
            void handleSubmit();
          } else {
            void onConfirm("cancel" /* Cancel */);
          }
          return;
        }
        if (isMultiSelect && currentQuestion) {
          if (selectedIndex === currentQuestion.options.length) {
            return;
          }
          handleMultiSelectSubmit();
          return;
        }
        if (currentQuestion && selectedIndex < currentQuestion.options.length) {
          const option = currentQuestion.options[selectedIndex];
          if (option) {
            selectAndAdvance(option.label);
          }
        }
        return;
      }
      if (key.name === "escape" || key.ctrl && key.name === "c") {
        void onConfirm("cancel" /* Cancel */);
        return;
      }
    },
    { isActive: isFocused }
  );
  if (isSubmitTab) {
    return /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(Box_default, { flexDirection: "column", padding: 1, children: [
      /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(Box_default, { marginBottom: 1, flexDirection: "row", gap: 1, children: [
        confirmationDetails.questions.map((q, idx) => {
          const isAnswered = getAnswerForQuestion(idx) !== void 0;
          return /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(Text, { dimColor: true, children: [
            isAnswered ? "  " : "  ",
            q.header,
            isAnswered ? " \u2713" : ""
          ] }) }, idx);
        }),
        /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(Text, { color: theme.text.accent, bold: true, children: [
          "\u25B8 ",
          t("Submit")
        ] }) })
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(Box_default, { flexDirection: "column", marginBottom: 1, children: [
        /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(Text, { bold: true, children: t("Your answers:") }),
        confirmationDetails.questions.map((q, idx) => {
          const answer = getAnswerForQuestion(idx);
          return /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(Box_default, { marginLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(Text, { children: [
            q.header,
            ":",
            " ",
            answer ? /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(Text, { color: theme.text.accent, children: answer }) : /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(Text, { dimColor: true, children: t("(not answered)") })
          ] }) }, idx);
        })
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(Box_default, { marginTop: 1, marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(Text, { children: t("Ready to submit your answers?") }) }),
      /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(Box_default, { flexDirection: "column", children: [
        /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(
          Text,
          {
            color: selectedIndex === 0 ? theme.text.accent : theme.text.primary,
            bold: selectedIndex === 0,
            children: [
              selectedIndex === 0 ? "\u276F " : "  ",
              "1. ",
              t("Submit answers")
            ]
          }
        ) }),
        /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(
          Text,
          {
            color: selectedIndex === 1 ? theme.text.accent : theme.text.primary,
            bold: selectedIndex === 1,
            children: [
              selectedIndex === 1 ? "\u276F " : "  ",
              "2. ",
              t("Cancel")
            ]
          }
        ) })
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(Text, { dimColor: true, children: t("\u2191/\u2193: Navigate | \u2190/\u2192: Switch tabs | Enter: Select") }) })
    ] });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(Box_default, { flexDirection: "column", padding: 1, children: [
    hasMultipleQuestions && /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(Box_default, { marginBottom: 1, flexDirection: "row", gap: 1, children: [
      confirmationDetails.questions.map((q, idx) => {
        const isAnswered = getAnswerForQuestion(idx) !== void 0;
        return /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(
          Text,
          {
            color: idx === currentQuestionIndex ? theme.text.accent : theme.text.primary,
            bold: idx === currentQuestionIndex,
            dimColor: idx !== currentQuestionIndex,
            children: [
              idx === currentQuestionIndex ? "\u25B8 " : "  ",
              q.header,
              isAnswered ? " \u2713" : ""
            ]
          }
        ) }, idx);
      }),
      /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(Text, { dimColor: true, children: [
        " ",
        t("Submit")
      ] }) })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(Box_default, { flexDirection: "column", marginBottom: 1, children: [
      !hasMultipleQuestions && /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(Box_default, { marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(Text, { color: theme.text.accent, bold: true, children: currentQuestion.header }) }),
      /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(Text, { children: currentQuestion.question })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(Box_default, { flexDirection: "column", marginBottom: 1, children: [
      currentQuestion.options.map((opt, index) => {
        const isSelected = selectedIndex === index;
        const isMultiChecked = isMultiSelect && (multiSelectedOptions[currentQuestionIndex] ?? []).includes(
          opt.label
        );
        const isAnswered = !isMultiSelect && selectedOptions[currentQuestionIndex] === opt.label;
        const isHighlighted = isSelected || isAnswered || isMultiChecked;
        const prefixWidth = 2 + (isMultiSelect ? 4 : 0) + String(index + 1).length + 2;
        return /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(Box_default, { flexDirection: "column", children: [
          /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(
            Text,
            {
              color: isHighlighted ? theme.text.accent : theme.text.primary,
              bold: isHighlighted,
              children: [
                isSelected ? "\u276F " : "  ",
                isMultiSelect ? isMultiChecked ? "[\u2713] " : "[ ] " : "",
                index + 1,
                ". ",
                opt.label,
                isAnswered ? " \u2713" : ""
              ]
            }
          ) }),
          opt.description && /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(Box_default, { marginLeft: prefixWidth, children: /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(Text, { dimColor: true, children: opt.description }) })
        ] }, index);
      }),
      /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(Box_default, { flexDirection: "column", children: isCustomInputSelected ? (
        // Inline TextInput replaces the option text
        /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(Box_default, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(Text, { color: theme.text.accent, bold: true, children: [
            "\u276F",
            " ",
            isMultiSelect ? customInputChecked[currentQuestionIndex] ? "[\u2713] " : "[ ] " : "",
            currentQuestion.options.length + 1,
            ".",
            " "
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(
            TextInput,
            {
              value: currentCustomInputValue,
              initialCursorOffset: currentCustomInputValue.length,
              onChange: (value) => {
                const oldValue = customInputValuesRef.current[currentQuestionIndex] ?? customInputValues[currentQuestionIndex] ?? "";
                customInputValuesRef.current = {
                  ...customInputValuesRef.current,
                  [currentQuestionIndex]: value
                };
                if (isMultiSelect && value !== oldValue) {
                  setCustomInputChecked((prevChecked) => ({
                    ...prevChecked,
                    [currentQuestionIndex]: value.trim().length > 0
                  }));
                }
                setCustomInputValues((prev) => ({
                  ...prev,
                  [currentQuestionIndex]: value
                }));
              },
              onSubmit: handleCustomInputSubmit,
              placeholder: t("Type something..."),
              isActive: true,
              inputWidth: 50
            }
          )
        ] })
      ) : (
        // Show typed value or placeholder when not selected
        /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(
          Text,
          {
            color: isCustomInputAnswer || customInputChecked[currentQuestionIndex] ? theme.text.accent : theme.text.primary,
            bold: !!(isCustomInputAnswer || customInputChecked[currentQuestionIndex]),
            dimColor: !currentCustomInputValue && !isCustomInputAnswer && !customInputChecked[currentQuestionIndex],
            children: [
              "  ",
              isMultiSelect ? customInputChecked[currentQuestionIndex] ? "[\u2713] " : "[ ] " : "",
              currentQuestion.options.length + 1,
              ".",
              " ",
              currentCustomInputValue || t("Type something..."),
              isCustomInputAnswer ? " \u2713" : ""
            ]
          }
        ) })
      ) })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(Box_default, { flexDirection: "column", marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(Text, { dimColor: true, children: hasMultipleQuestions ? isMultiSelect ? t(
      "\u2191/\u2193: Navigate | \u2190/\u2192: Switch tabs | Space: Toggle | Enter: Confirm | Esc: Cancel"
    ) : t(
      "\u2191/\u2193: Navigate | \u2190/\u2192: Switch tabs | Enter: Select | Esc: Cancel"
    ) : isMultiSelect ? t(
      "\u2191/\u2193: Navigate | Space: Toggle | Enter: Confirm | Esc: Cancel"
    ) : t("\u2191/\u2193: Navigate | Enter: Select | Esc: Cancel") }) }) })
  ] });
}, "AskUserQuestionDialog");

// packages/cli/src/ui/components/messages/ToolConfirmationMessage.tsx
var import_jsx_runtime15 = __toESM(require_jsx_runtime(), 1);
var COMPACT_BODY_MAX_LINES = 5;
var ToolConfirmationMessage = /* @__PURE__ */ __name(({
  confirmationDetails,
  config,
  isFocused = true,
  availableTerminalHeight,
  contentWidth,
  compactMode = false
}) => {
  const { onConfirm } = confirmationDetails;
  const settings = useSettings();
  const preferredEditor = settings.merged.general?.preferredEditor;
  const [ideClient, setIdeClient] = (0, import_react16.useState)(null);
  const [isDiffingEnabled, setIsDiffingEnabled] = (0, import_react16.useState)(false);
  (0, import_react16.useEffect)(() => {
    let isMounted = true;
    if (config.getIdeMode()) {
      const getIdeClient = /* @__PURE__ */ __name(async () => {
        const client = await IdeClient.getInstance();
        if (isMounted) {
          setIdeClient(client);
          setIsDiffingEnabled(client?.isDiffingEnabled() ?? false);
        }
      }, "getIdeClient");
      getIdeClient();
    }
    return () => {
      isMounted = false;
    };
  }, [config]);
  const handleConfirm = /* @__PURE__ */ __name(async (outcome) => {
    onConfirm(outcome);
    if (confirmationDetails.type === "edit") {
      if (config.getIdeMode() && isDiffingEnabled) {
        const cliOutcome = outcome === "cancel" /* Cancel */ ? "rejected" : "accepted";
        await ideClient?.resolveDiffFromCli(
          confirmationDetails.filePath,
          cliOutcome
        );
      }
    }
  }, "handleConfirm");
  const isTrustedFolder = config.isTrustedFolder();
  useKeypress(
    (key) => {
      if (!isFocused) return;
      if (key.name === "escape" || key.ctrl && key.name === "c") {
        handleConfirm("cancel" /* Cancel */);
      }
    },
    { isActive: isFocused }
  );
  const handleSelect = /* @__PURE__ */ __name((item) => handleConfirm(item), "handleSelect");
  let bodyContent = null;
  let question;
  const options = new Array();
  function availableBodyContentHeight() {
    if (options.length === 0) {
      throw new Error("Options not provided for confirmation message");
    }
    if (availableTerminalHeight === void 0) {
      return void 0;
    }
    const PADDING_OUTER_Y = compactMode ? 0 : 2;
    const MARGIN_BODY_BOTTOM = compactMode ? 0 : 1;
    const HEIGHT_QUESTION = 1;
    const MARGIN_QUESTION_BOTTOM = compactMode ? 0 : 1;
    const HEIGHT_OPTIONS = compactMode ? 3 : options.length;
    const surroundingElementsHeight = PADDING_OUTER_Y + MARGIN_BODY_BOTTOM + HEIGHT_QUESTION + MARGIN_QUESTION_BOTTOM + HEIGHT_OPTIONS;
    return Math.max(availableTerminalHeight - surroundingElementsHeight, 1);
  }
  __name(availableBodyContentHeight, "availableBodyContentHeight");
  if (confirmationDetails.type === "edit") {
    if (confirmationDetails.isModifying) {
      return /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)(
        Box_default,
        {
          minWidth: "90%",
          borderStyle: "round",
          borderColor: theme.border.default,
          justifyContent: "space-around",
          padding: 1,
          overflow: "hidden",
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)(Text, { color: theme.text.primary, children: [
              t("Modify in progress:"),
              " "
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(Text, { color: theme.status.success, children: t("Save and close external editor to continue") })
          ]
        }
      );
    }
    question = t("Apply this change?");
    options.push({
      label: t("Yes, allow once"),
      value: "proceed_once" /* ProceedOnce */,
      key: "Yes, allow once"
    });
    if (isTrustedFolder) {
      options.push({
        label: t("Yes, allow always"),
        value: "proceed_always" /* ProceedAlways */,
        key: "Yes, allow always"
      });
    }
    if (!confirmationDetails.hideModify && (!config.getIdeMode() || !isDiffingEnabled) && preferredEditor) {
      options.push({
        label: t("Modify with external editor"),
        value: "modify_with_editor" /* ModifyWithEditor */,
        key: "Modify with external editor"
      });
    }
    options.push({
      label: t("No, suggest changes (esc)"),
      value: "cancel" /* Cancel */,
      key: "No, suggest changes (esc)"
    });
    bodyContent = /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(
      DiffRenderer,
      {
        diffContent: confirmationDetails.fileDiff,
        filename: confirmationDetails.fileName,
        availableTerminalHeight: availableBodyContentHeight(),
        contentWidth,
        settings
      }
    );
  } else if (confirmationDetails.type === "exec") {
    const executionProps = confirmationDetails;
    question = t("Allow execution of: '{{command}}'?", {
      command: executionProps.rootCommand
    });
    options.push({
      label: t("Yes, allow once"),
      value: "proceed_once" /* ProceedOnce */,
      key: "Yes, allow once"
    });
    if (isTrustedFolder && !confirmationDetails.hideAlwaysAllow) {
      const friendlyLabel = executionProps.permissionRules?.length ? ` ${buildHumanReadableRuleLabel(executionProps.permissionRules)}` : "";
      options.push({
        label: friendlyLabel ? t("Always allow {{action}} in this project", {
          action: friendlyLabel.trim()
        }) : t("Always allow in this project"),
        value: "proceed_always_project" /* ProceedAlwaysProject */,
        key: "Always allow in this project"
      });
      options.push({
        label: friendlyLabel ? t("Always allow {{action}} for this user", {
          action: friendlyLabel.trim()
        }) : t("Always allow for this user"),
        value: "proceed_always_user" /* ProceedAlwaysUser */,
        key: "Always allow for this user"
      });
    }
    options.push({
      label: t("No, suggest changes (esc)"),
      value: "cancel" /* Cancel */,
      key: "No, suggest changes (esc)"
    });
    const warningPrefixLen = 2;
    const safeWidth = Math.max(contentWidth, 1);
    const warnings = executionProps.warnings ?? [];
    const warningsCount = warnings.length;
    const wrappedWarningRows = warnings.reduce(
      (sum, w) => sum + Math.max(Math.ceil((w.length + warningPrefixLen) / safeWidth), 1),
      0
    );
    const warningsHeight = warningsCount > 0 ? wrappedWarningRows + 1 : 0;
    let bodyContentHeight = availableBodyContentHeight();
    if (bodyContentHeight !== void 0) {
      bodyContentHeight -= 2;
    }
    if (compactMode) {
      bodyContentHeight = Math.min(
        bodyContentHeight ?? COMPACT_BODY_MAX_LINES,
        COMPACT_BODY_MAX_LINES
      );
    }
    if (bodyContentHeight !== void 0 && warningsHeight > 0) {
      bodyContentHeight = Math.max(bodyContentHeight - warningsHeight, 1);
    }
    bodyContent = /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)(Box_default, { flexDirection: "column", children: [
      /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(Box_default, { paddingX: 1, marginLeft: 1, children: /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(
        MaxSizedBox,
        {
          maxHeight: bodyContentHeight,
          maxWidth: Math.max(contentWidth, 1),
          overflowDirection: "bottom",
          children: /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(Text, { color: theme.text.link, children: executionProps.command }) })
        }
      ) }),
      warningsCount > 0 ? /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(Box_default, { flexDirection: "column", paddingX: 1, marginLeft: 1, marginTop: 1, children: warnings.map((warning, idx) => /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)(Text, { color: theme.status.warning, children: [
        "\u26A0 ",
        warning
      ] }, idx)) }) : null
    ] });
  } else if (confirmationDetails.type === "plan") {
    const planProps = confirmationDetails;
    question = planProps.title;
    options.push({
      key: "restore-previous",
      label: t("Yes, restore previous mode ({{mode}})", {
        mode: planProps.prePlanMode ?? "default"
      }),
      value: "restore_previous" /* RestorePrevious */
    });
    options.push({
      key: "proceed-always",
      label: t("Yes, and auto-accept edits"),
      value: "proceed_always" /* ProceedAlways */
    });
    options.push({
      key: "proceed-once",
      label: t("Yes, and manually approve edits"),
      value: "proceed_once" /* ProceedOnce */
    });
    options.push({
      key: "cancel",
      label: t("No, keep planning (esc)"),
      value: "cancel" /* Cancel */
    });
    const planHeight = compactMode ? Math.min(
      availableBodyContentHeight() ?? COMPACT_BODY_MAX_LINES,
      COMPACT_BODY_MAX_LINES
    ) : availableBodyContentHeight();
    bodyContent = /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(Box_default, { flexDirection: "column", paddingX: 1, marginLeft: 1, children: /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(
      MarkdownDisplay,
      {
        text: planProps.plan,
        isPending: false,
        availableTerminalHeight: planHeight,
        contentWidth
      }
    ) });
  } else if (confirmationDetails.type === "info") {
    const infoProps = confirmationDetails;
    const displayUrls = infoProps.urls && !(infoProps.urls.length === 1 && infoProps.urls[0] === infoProps.prompt);
    question = t("Do you want to proceed?");
    options.push({
      label: t("Yes, allow once"),
      value: "proceed_once" /* ProceedOnce */,
      key: "Yes, allow once"
    });
    if (isTrustedFolder && !confirmationDetails.hideAlwaysAllow) {
      const friendlyLabel = "permissionRules" in infoProps && infoProps.permissionRules?.length ? ` ${buildHumanReadableRuleLabel(infoProps.permissionRules)}` : "";
      options.push({
        label: friendlyLabel ? t("Always allow {{action}} in this project", {
          action: friendlyLabel.trim()
        }) : t("Always allow in this project"),
        value: "proceed_always_project" /* ProceedAlwaysProject */,
        key: "Always allow in this project"
      });
      options.push({
        label: friendlyLabel ? t("Always allow {{action}} for this user", {
          action: friendlyLabel.trim()
        }) : t("Always allow for this user"),
        value: "proceed_always_user" /* ProceedAlwaysUser */,
        key: "Always allow for this user"
      });
    }
    options.push({
      label: t("No, suggest changes (esc)"),
      value: "cancel" /* Cancel */,
      key: "No, suggest changes (esc)"
    });
    bodyContent = /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)(Box_default, { flexDirection: "column", paddingX: 1, marginLeft: 1, children: [
      /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(Text, { color: theme.text.link, children: /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(RenderInline, { text: infoProps.prompt, textColor: theme.text.link }) }),
      displayUrls && infoProps.urls && infoProps.urls.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)(Box_default, { flexDirection: "column", marginTop: 1, children: [
        /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(Text, { color: theme.text.primary, children: t("URLs to fetch:") }),
        infoProps.urls.map((url) => /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)(Text, { children: [
          " ",
          "- ",
          /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(RenderInline, { text: url })
        ] }, url))
      ] })
    ] });
  } else if (confirmationDetails.type === "ask_user_question") {
    return /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(
      AskUserQuestionDialog,
      {
        confirmationDetails,
        isFocused,
        onConfirm
      }
    );
  } else {
    const mcpProps = confirmationDetails;
    bodyContent = /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)(Box_default, { flexDirection: "column", paddingX: 1, marginLeft: 1, children: [
      /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(Text, { color: theme.text.link, children: t("MCP Server: {{server}}", { server: mcpProps.serverName }) }),
      /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(Text, { color: theme.text.link, children: t("Tool: {{tool}}", { tool: mcpProps.toolName }) })
    ] });
    question = t(
      'Allow execution of MCP tool "{{tool}}" from server "{{server}}"?',
      {
        tool: mcpProps.toolName,
        server: mcpProps.serverName
      }
    );
    options.push({
      label: t("Yes, allow once"),
      value: "proceed_once" /* ProceedOnce */,
      key: "Yes, allow once"
    });
    if (isTrustedFolder && !confirmationDetails.hideAlwaysAllow) {
      const friendlyLabel = mcpProps.permissionRules?.length ? ` ${buildHumanReadableRuleLabel(mcpProps.permissionRules)}` : "";
      options.push({
        label: friendlyLabel ? t("Always allow {{action}} in this project", {
          action: friendlyLabel.trim()
        }) : t("Always allow in this project"),
        value: "proceed_always_project" /* ProceedAlwaysProject */,
        key: "Always allow in this project"
      });
      options.push({
        label: friendlyLabel ? t("Always allow {{action}} for this user", {
          action: friendlyLabel.trim()
        }) : t("Always allow for this user"),
        value: "proceed_always_user" /* ProceedAlwaysUser */,
        key: "Always allow for this user"
      });
    }
    options.push({
      label: t("No, suggest changes (esc)"),
      value: "cancel" /* Cancel */,
      key: "No, suggest changes (esc)"
    });
  }
  const renderedQuestion = compactMode && (confirmationDetails.type === "exec" || confirmationDetails.type === "mcp") ? t("Do you want to proceed?") : question;
  const renderedOptions = compactMode ? [
    {
      key: "proceed-once",
      label: t("Yes, allow once"),
      value: "proceed_once" /* ProceedOnce */
    },
    ...!confirmationDetails.hideAlwaysAllow ? [
      {
        key: "proceed-always",
        label: t("Allow always"),
        value: "proceed_always" /* ProceedAlways */
      }
    ] : [],
    {
      key: "cancel",
      label: t("No"),
      value: "cancel" /* Cancel */
    }
  ] : options;
  const outerPadding = compactMode ? 0 : 1;
  const sectionMargin = compactMode ? 0 : 1;
  const outerWidth = compactMode ? void 0 : contentWidth;
  return /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)(Box_default, { flexDirection: "column", padding: outerPadding, width: outerWidth, children: [
    /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(
      Box_default,
      {
        flexGrow: 1,
        flexShrink: 1,
        overflow: "hidden",
        marginBottom: sectionMargin,
        children: bodyContent
      }
    ),
    /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(Box_default, { marginBottom: sectionMargin, flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(Text, { color: theme.text.primary, wrap: "truncate", children: renderedQuestion }) }),
    /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(Box_default, { flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(
      RadioButtonSelect,
      {
        items: renderedOptions,
        onSelect: handleSelect,
        isFocused
      }
    ) })
  ] });
}, "ToolConfirmationMessage");

// packages/cli/src/ui/components/PlanSummaryDisplay.tsx
init_esbuild_shims();
var import_jsx_runtime16 = __toESM(require_jsx_runtime(), 1);
var PlanSummaryDisplay = /* @__PURE__ */ __name(({
  data,
  availableHeight,
  childWidth
}) => {
  const { message, plan, rejected } = data;
  const messageColor = rejected ? Colors.AccentYellow : Colors.AccentGreen;
  return /* @__PURE__ */ (0, import_jsx_runtime16.jsxs)(Box_default, { flexDirection: "column", children: [
    /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(Box_default, { marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(Text, { color: messageColor, wrap: "wrap", children: message }) }),
    /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(
      MarkdownDisplay,
      {
        text: plan,
        isPending: false,
        availableTerminalHeight: availableHeight,
        contentWidth: childWidth
      }
    )
  ] });
}, "PlanSummaryDisplay");

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

// packages/cli/src/ui/hooks/keyToAnsi.ts
init_esbuild_shims();
function keyToAnsi(key) {
  if (key.ctrl) {
    if (key.name >= "a" && key.name <= "z") {
      return String.fromCharCode(
        key.name.charCodeAt(0) - "a".charCodeAt(0) + 1
      );
    }
    switch (key.name) {
      case "c":
        return "";
      // ETX (End of Text), commonly used for interrupt
      // Add other special ctrl cases if needed
      default:
        break;
    }
  }
  switch (key.name) {
    case "up":
      return "\x1B[A";
    case "down":
      return "\x1B[B";
    case "right":
      return "\x1B[C";
    case "left":
      return "\x1B[D";
    case "escape":
      return "\x1B";
    case "tab":
      return "	";
    case "backspace":
      return "\x7F";
    case "delete":
      return "\x1B[3~";
    case "home":
      return "\x1B[H";
    case "end":
      return "\x1B[F";
    case "pageup":
      return "\x1B[5~";
    case "pagedown":
      return "\x1B[6~";
    default:
      break;
  }
  if (key.name === "return") {
    return "\r";
  }
  if (!key.ctrl && !key.meta && key.sequence) {
    return key.sequence;
  }
  return null;
}
__name(keyToAnsi, "keyToAnsi");

// packages/cli/src/ui/components/ShellInputPrompt.tsx
var ShellInputPrompt = /* @__PURE__ */ __name(({
  activeShellPtyId,
  focus = true
}) => {
  const handleShellInputSubmit = (0, import_react17.useCallback)(
    (input) => {
      if (activeShellPtyId) {
        ShellExecutionService.writeToPty(activeShellPtyId, input);
      }
    },
    [activeShellPtyId]
  );
  const handleInput = (0, import_react17.useCallback)(
    (key) => {
      if (!focus || !activeShellPtyId) {
        return;
      }
      if (keyMatchers["toggleShellInputFocus" /* TOGGLE_SHELL_INPUT_FOCUS */](key)) {
        return;
      }
      if (key.ctrl && key.shift && key.name === "up") {
        ShellExecutionService.scrollPty(activeShellPtyId, -1);
        return;
      }
      if (key.ctrl && key.shift && key.name === "down") {
        ShellExecutionService.scrollPty(activeShellPtyId, 1);
        return;
      }
      const ansiSequence = keyToAnsi(key);
      if (ansiSequence) {
        handleShellInputSubmit(ansiSequence);
      }
    },
    [focus, handleShellInputSubmit, activeShellPtyId]
  );
  useKeypress(handleInput, { isActive: focus });
  return null;
}, "ShellInputPrompt");

// packages/cli/src/ui/components/messages/CompactToolGroupDisplay.tsx
init_esbuild_shims();

// packages/cli/src/ui/components/shared/ToolStatusIndicator.tsx
init_esbuild_shims();

// packages/cli/src/ui/components/GeminiRespondingSpinner.tsx
init_esbuild_shims();
var import_react20 = __toESM(require_react(), 1);

// node_modules/ink-spinner/build/index.js
init_esbuild_shims();
var import_react18 = __toESM(require_react(), 1);
var import_cli_spinners = __toESM(require_cli_spinners(), 1);
function Spinner({ type = "dots" }) {
  const [frame, setFrame] = (0, import_react18.useState)(0);
  const spinner = import_cli_spinners.default[type];
  (0, import_react18.useEffect)(() => {
    const timer = setInterval(() => {
      setFrame((previousFrame) => {
        const isLastFrame = previousFrame === spinner.frames.length - 1;
        return isLastFrame ? 0 : previousFrame + 1;
      });
    }, spinner.interval);
    return () => {
      clearInterval(timer);
    };
  }, [spinner]);
  return import_react18.default.createElement(Text, null, spinner.frames[frame]);
}
__name(Spinner, "Spinner");
var build_default = Spinner;

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

// packages/cli/src/ui/components/GeminiRespondingSpinner.tsx
var import_jsx_runtime17 = __toESM(require_jsx_runtime(), 1);
var TMUX_SPINNER_INTERVAL_MS = 750;
var TMUX_SPINNER_FRAMES = [".  ", ".. ", "..."];
var GeminiRespondingSpinner = /* @__PURE__ */ __name(({ nonRespondingDisplay, spinnerType = "dots" }) => {
  const streamingState = useStreamingContext();
  const isScreenReaderEnabled = use_is_screen_reader_enabled_default();
  if (streamingState === "responding" /* Responding */) {
    return /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(
      GeminiSpinner,
      {
        spinnerType,
        altText: SCREEN_READER_RESPONDING
      }
    );
  } else if (nonRespondingDisplay) {
    return isScreenReaderEnabled ? /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(Text, { children: SCREEN_READER_LOADING }) : /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(Text, { color: theme.text.primary, children: nonRespondingDisplay });
  }
  return null;
}, "GeminiRespondingSpinner");
var GeminiSpinner = /* @__PURE__ */ __name(({
  spinnerType = "dots",
  altText
}) => {
  const isScreenReaderEnabled = use_is_screen_reader_enabled_default();
  const isTmux = Boolean(process.env["TMUX"]);
  const [tmuxFrameIndex, setTmuxFrameIndex] = (0, import_react20.useState)(0);
  (0, import_react20.useEffect)(() => {
    if (isScreenReaderEnabled || !isTmux) {
      return;
    }
    const interval = setInterval(() => {
      setTmuxFrameIndex((index) => (index + 1) % TMUX_SPINNER_FRAMES.length);
    }, TMUX_SPINNER_INTERVAL_MS);
    return () => clearInterval(interval);
  }, [isScreenReaderEnabled, isTmux]);
  if (isScreenReaderEnabled) {
    return /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(Text, { children: altText });
  }
  if (isTmux) {
    return /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(Text, { color: theme.text.primary, children: TMUX_SPINNER_FRAMES[tmuxFrameIndex] });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(Text, { color: theme.text.primary, children: /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(build_default, { type: spinnerType }) });
}, "GeminiSpinner");

// packages/cli/src/ui/components/shared/ToolStatusIndicator.tsx
var import_jsx_runtime18 = __toESM(require_jsx_runtime(), 1);
var STATUS_INDICATOR_WIDTH = 2;
var ToolStatusIndicator = /* @__PURE__ */ __name(({
  status,
  name
}) => {
  const isShell = name === SHELL_COMMAND_NAME || name === SHELL_NAME;
  const statusColor = isShell ? theme.ui.symbol : theme.status.warning;
  return /* @__PURE__ */ (0, import_jsx_runtime18.jsxs)(Box_default, { minWidth: STATUS_INDICATOR_WIDTH, children: [
    status === "Pending" /* Pending */ && /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(Text, { color: theme.status.success, children: TOOL_STATUS.PENDING }),
    status === "Executing" /* Executing */ && /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(
      GeminiRespondingSpinner,
      {
        spinnerType: "toggle",
        nonRespondingDisplay: TOOL_STATUS.EXECUTING
      }
    ),
    status === "Success" /* Success */ && /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(Text, { color: theme.status.success, "aria-label": "Success:", children: TOOL_STATUS.SUCCESS }),
    status === "Confirming" /* Confirming */ && /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(Text, { color: statusColor, "aria-label": "Confirming:", children: TOOL_STATUS.CONFIRMING }),
    status === "Canceled" /* Canceled */ && /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(Text, { color: statusColor, "aria-label": "Canceled:", bold: true, children: TOOL_STATUS.CANCELED }),
    status === "Error" /* Error */ && /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(Text, { color: theme.status.error, "aria-label": "Error:", bold: true, children: TOOL_STATUS.ERROR })
  ] });
}, "ToolStatusIndicator");

// packages/cli/src/ui/components/shared/ToolElapsedTime.tsx
init_esbuild_shims();
var import_react21 = __toESM(require_react(), 1);
var import_jsx_runtime19 = __toESM(require_jsx_runtime(), 1);
var ToolElapsedTime = /* @__PURE__ */ __name(({
  status,
  executionStartTime,
  timeoutMs
}) => {
  const [elapsedSeconds, setElapsedSeconds] = (0, import_react21.useState)(0);
  (0, import_react21.useEffect)(() => {
    if (status !== "Executing" /* Executing */ || !executionStartTime) {
      setElapsedSeconds(0);
      return;
    }
    setElapsedSeconds(Math.floor((Date.now() - executionStartTime) / 1e3));
    const interval = setInterval(() => {
      setElapsedSeconds(Math.floor((Date.now() - executionStartTime) / 1e3));
    }, 1e3);
    return () => clearInterval(interval);
  }, [status, executionStartTime]);
  if (status !== "Executing" /* Executing */) return null;
  const hasTimeout = timeoutMs != null && timeoutMs > 0;
  if (!hasTimeout && elapsedSeconds < 3) return null;
  const elapsedStr = formatDuration(elapsedSeconds * 1e3, {
    hideTrailingZeros: true
  });
  const label = hasTimeout ? `(${elapsedStr} \xB7 timeout ${formatDuration(timeoutMs, { hideTrailingZeros: true })})` : elapsedStr;
  return /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(Box_default, { flexShrink: 0, marginLeft: 1, children: /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(Text, { color: theme.text.secondary, children: label }) });
}, "ToolElapsedTime");

// packages/cli/src/ui/components/messages/CompactToolGroupDisplay.tsx
var import_jsx_runtime20 = __toESM(require_jsx_runtime(), 1);
function getOverallStatus(toolCalls) {
  if (toolCalls.some((t2) => t2.status === "Confirming" /* Confirming */))
    return "Confirming" /* Confirming */;
  if (toolCalls.some((t2) => t2.status === "Executing" /* Executing */))
    return "Executing" /* Executing */;
  if (toolCalls.some((t2) => t2.status === "Error" /* Error */))
    return "Error" /* Error */;
  if (toolCalls.some((t2) => t2.status === "Canceled" /* Canceled */))
    return "Canceled" /* Canceled */;
  if (toolCalls.some((t2) => t2.status === "Pending" /* Pending */))
    return "Pending" /* Pending */;
  return "Success" /* Success */;
}
__name(getOverallStatus, "getOverallStatus");
function getActiveTool(toolCalls) {
  return toolCalls.find((t2) => t2.status === "Confirming" /* Confirming */) ?? toolCalls.find((t2) => t2.status === "Executing" /* Executing */) ?? toolCalls[toolCalls.length - 1];
}
__name(getActiveTool, "getActiveTool");
function getShellTimeoutMs(tool) {
  const display = tool.resultDisplay;
  if (typeof display === "object" && display !== null && "ansiOutput" in display) {
    return display.timeoutMs;
  }
  return void 0;
}
__name(getShellTimeoutMs, "getShellTimeoutMs");
var TOOL_NAME_TO_CATEGORY = {
  [ToolDisplayNames.READ_FILE]: "read",
  [ToolDisplayNames.EDIT]: "edit",
  [ToolDisplayNames.WRITE_FILE]: "write",
  [ToolDisplayNames.NOTEBOOK_EDIT]: "edit",
  [ToolDisplayNames.GREP]: "search",
  [ToolDisplayNames.GLOB]: "search",
  [ToolDisplayNames.LS]: "list",
  [ToolDisplayNames.SHELL]: "command",
  [SHELL_COMMAND_NAME]: "command",
  [ToolDisplayNames.AGENT]: "agent",
  [ToolDisplayNames.WORKFLOW]: "agent",
  [ToolDisplayNames.SEND_MESSAGE]: "agent",
  "Read File": "read",
  "Read File(s)": "read",
  "Read Directory": "list",
  // Legacy display names (keys from ToolDisplayNamesMigration)
  SearchFiles: "search",
  FindFiles: "search",
  ReadFolder: "list",
  Task: "agent",
  TodoWrite: "other"
};
var CATEGORY_TEMPLATES = {
  read: {
    pastVerb: "Read",
    activeVerb: "Reading",
    singular: "file",
    plural: "files"
  },
  edit: {
    pastVerb: "Edited",
    activeVerb: "Editing",
    singular: "file",
    plural: "files"
  },
  write: {
    pastVerb: "Wrote",
    activeVerb: "Writing",
    singular: "file",
    plural: "files"
  },
  search: {
    pastVerb: "Searched",
    activeVerb: "Searching",
    singular: "pattern",
    plural: "patterns"
  },
  list: {
    pastVerb: "Listed",
    activeVerb: "Listing",
    singular: "directory",
    plural: "directories"
  },
  command: {
    pastVerb: "Ran",
    activeVerb: "Running",
    singular: "command",
    plural: "commands"
  },
  agent: {
    pastVerb: "Ran",
    activeVerb: "Running",
    singular: "agent",
    plural: "agents"
  },
  other: {
    pastVerb: "Used",
    activeVerb: "Using",
    singular: "tool",
    plural: "tools"
  }
};
var CATEGORY_ORDER = [
  "search",
  "read",
  "list",
  "command",
  "edit",
  "write",
  "agent",
  "other"
];
var COLLAPSIBLE_CATEGORIES = /* @__PURE__ */ new Set([
  "read",
  "search",
  "list"
]);
function getToolCategory(toolName) {
  return TOOL_NAME_TO_CATEGORY[toolName] ?? "other";
}
__name(getToolCategory, "getToolCategory");
function isCollapsibleTool(toolName) {
  return COLLAPSIBLE_CATEGORIES.has(getToolCategory(toolName));
}
__name(isCollapsibleTool, "isCollapsibleTool");
function buildToolSummary(toolCalls, isActive) {
  if (toolCalls.length === 0) return "";
  const counts = /* @__PURE__ */ new Map();
  for (const tool of toolCalls) {
    const cat = getToolCategory(tool.name);
    counts.set(cat, (counts.get(cat) ?? 0) + 1);
  }
  const parts = [];
  for (const cat of CATEGORY_ORDER) {
    const count = counts.get(cat);
    if (!count) continue;
    const template = CATEGORY_TEMPLATES[cat];
    const verb = isActive ? template.activeVerb : template.pastVerb;
    const lower = parts.length > 0;
    const v = lower ? verb.toLowerCase() : verb;
    if (count === 1) {
      parts.push(`${v} 1 ${template.singular}`);
    } else {
      parts.push(`${v} ${count} ${template.plural}`);
    }
  }
  return parts.join(", ");
}
__name(buildToolSummary, "buildToolSummary");
var CompactToolGroupDisplay = /* @__PURE__ */ __name(({ toolCalls, contentWidth }) => {
  if (toolCalls.length === 0) return null;
  const overallStatus = getOverallStatus(toolCalls);
  const activeTool = getActiveTool(toolCalls);
  const isActive = overallStatus === "Executing" /* Executing */ || overallStatus === "Pending" /* Pending */ || overallStatus === "Confirming" /* Confirming */;
  return /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(Box_default, { flexDirection: "column", width: contentWidth, paddingX: 1, gap: 0, children: /* @__PURE__ */ (0, import_jsx_runtime20.jsxs)(Box_default, { flexDirection: "row", children: [
    /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(ToolStatusIndicator, { status: overallStatus, name: activeTool.name }),
    /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(Box_default, { flexGrow: 1, children: /* @__PURE__ */ (0, import_jsx_runtime20.jsxs)(Text, { wrap: "truncate-end", bold: true, children: [
      buildToolSummary(toolCalls, isActive),
      isActive && /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(Text, { children: "\u2026" }, "ellipsis")
    ] }) }),
    /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(
      ToolElapsedTime,
      {
        status: overallStatus,
        executionStartTime: activeTool.executionStartTime,
        timeoutMs: getShellTimeoutMs(activeTool)
      }
    )
  ] }) });
}, "CompactToolGroupDisplay");

// packages/cli/src/ui/components/messages/ToolMessage.tsx
var import_jsx_runtime21 = __toESM(require_jsx_runtime(), 1);
var AGENT_TOOL_NAMES = /* @__PURE__ */ new Set([
  ToolNames.AGENT,
  ...Object.entries(ToolNamesMigration).filter(([, canonical]) => canonical === ToolNames.AGENT).map(([legacy]) => legacy)
]);
var STATIC_HEIGHT = 1;
var RESERVED_LINE_COUNT = 5;
var MIN_LINES_SHOWN = 2;
var DEFAULT_SHELL_OUTPUT_MAX_LINES = 5;
var MAXIMUM_RESULT_DISPLAY_CHARACTERS = 1e6;
function sliceTextForMaxHeight(text, maxHeight, maxWidth) {
  if (maxHeight === void 0) {
    return { text, hiddenLinesCount: 0 };
  }
  const targetMaxHeight = Math.max(Math.round(maxHeight), MINIMUM_MAX_HEIGHT);
  const visibleContentHeight = targetMaxHeight - 1;
  const visualWidth = Math.max(1, Math.floor(maxWidth));
  const visibleLines = [];
  let visualLineCount = 0;
  let currentLine = "";
  let currentLineWidth = 0;
  const appendVisibleLine = /* @__PURE__ */ __name((line) => {
    visualLineCount += 1;
    visibleLines.push(line);
    if (visibleLines.length > visibleContentHeight) {
      visibleLines.shift();
    }
  }, "appendVisibleLine");
  const flushCurrentLine = /* @__PURE__ */ __name(() => {
    appendVisibleLine(currentLine);
    currentLine = "";
    currentLineWidth = 0;
  }, "flushCurrentLine");
  for (const char of toCodePoints(text)) {
    if (char === "\n") {
      flushCurrentLine();
      continue;
    }
    const charWidth = Math.max(getCachedStringWidth(char), 1);
    if (currentLineWidth > 0 && currentLineWidth + charWidth > visualWidth) {
      flushCurrentLine();
    }
    currentLine += char;
    currentLineWidth += charWidth;
  }
  flushCurrentLine();
  if (visualLineCount <= targetMaxHeight) {
    return { text, hiddenLinesCount: 0 };
  }
  const hiddenLinesCount = visualLineCount - visibleContentHeight;
  return {
    text: visibleLines.join("\n"),
    hiddenLinesCount
  };
}
__name(sliceTextForMaxHeight, "sliceTextForMaxHeight");
var useResultDisplayRenderer = /* @__PURE__ */ __name((resultDisplay) => import_react22.default.useMemo(() => {
  if (!resultDisplay) {
    return { type: "none" };
  }
  if (typeof resultDisplay === "object" && resultDisplay !== null && "type" in resultDisplay && resultDisplay.type === "todo_list") {
    return {
      type: "todo",
      data: resultDisplay
    };
  }
  if (typeof resultDisplay === "object" && resultDisplay !== null && "type" in resultDisplay && resultDisplay.type === "plan_summary") {
    return {
      type: "plan",
      data: resultDisplay
    };
  }
  if (typeof resultDisplay === "object" && resultDisplay !== null && "type" in resultDisplay && resultDisplay.type === "task_execution") {
    return {
      type: "task",
      data: resultDisplay
    };
  }
  if (typeof resultDisplay === "object" && resultDisplay !== null && "fileDiff" in resultDisplay) {
    return {
      type: "diff",
      data: resultDisplay
    };
  }
  if (typeof resultDisplay === "object" && resultDisplay !== null && "type" in resultDisplay && resultDisplay.type === "mcp_tool_progress") {
    const progress = resultDisplay;
    const msg = progress.message ?? `Progress: ${progress.progress}`;
    const totalStr = progress.total != null ? `/${progress.total}` : "";
    return {
      type: "string",
      data: `\u25CC [${progress.progress}${totalStr}] ${msg}`
    };
  }
  if (typeof resultDisplay === "object" && resultDisplay !== null && "ansiOutput" in resultDisplay) {
    const display = resultDisplay;
    return {
      type: "ansi",
      data: display.ansiOutput,
      stats: {
        totalLines: display.totalLines,
        totalBytes: display.totalBytes
      }
    };
  }
  if (typeof resultDisplay === "object" && resultDisplay !== null && "type" in resultDisplay && (resultDisplay.type === "team_result" || resultDisplay.type === "task_list")) {
    return { type: "none" };
  }
  return {
    type: "string",
    data: typeof resultDisplay === "string" ? resultDisplay : JSON.stringify(resultDisplay)
  };
}, [resultDisplay]), "useResultDisplayRenderer");
var TodoResultRenderer = /* @__PURE__ */ __name(({
  data
}) => /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(TodoDisplay, { todos: data.todos }), "TodoResultRenderer");
var PlanResultRenderer = /* @__PURE__ */ __name(({ data, availableHeight, childWidth }) => /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(
  PlanSummaryDisplay,
  {
    data,
    availableHeight,
    childWidth
  }
), "PlanResultRenderer");
var SubagentExecutionRenderer = /* @__PURE__ */ __name(({ data, availableHeight, childWidth, config, isFocused }) => {
  if (data.pendingConfirmation && isFocused) {
    const agentLabel = escapeAnsiCtrlCodes(data.subagentName || "agent");
    return /* @__PURE__ */ (0, import_jsx_runtime21.jsxs)(Box_default, { flexDirection: "column", paddingLeft: 1, children: [
      /* @__PURE__ */ (0, import_jsx_runtime21.jsxs)(Box_default, { children: [
        /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(Text, { color: theme.text.secondary, children: "Approval requested by " }),
        /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(Text, { bold: true, color: theme.text.accent, children: agentLabel }),
        /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(Text, { color: theme.text.secondary, children: ":" })
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(
        ToolConfirmationMessage,
        {
          confirmationDetails: data.pendingConfirmation,
          isFocused,
          availableTerminalHeight: availableHeight,
          contentWidth: childWidth - 2,
          compactMode: true,
          config
        }
      )
    ] });
  }
  if (data.pendingConfirmation) {
    const agentLabel = escapeAnsiCtrlCodes(data.subagentName || "agent");
    return /* @__PURE__ */ (0, import_jsx_runtime21.jsxs)(Box_default, { paddingLeft: 1, children: [
      /* @__PURE__ */ (0, import_jsx_runtime21.jsxs)(Text, { color: theme.text.secondary, dimColor: true, children: [
        "\u25CC Queued approval:",
        " "
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(Text, { dimColor: true, children: agentLabel })
    ] });
  }
  if (data.status === "completed" || data.status === "failed" || data.status === "cancelled") {
    return /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(SubagentScrollbackSummary, { data });
  }
  return null;
}, "SubagentExecutionRenderer");
var SubagentScrollbackSummary = /* @__PURE__ */ __name(({ data }) => {
  const { glyph, color } = (() => {
    switch (data.status) {
      case "completed":
        return { glyph: "\u2714", color: theme.status.success };
      case "failed":
        return { glyph: "\u2716", color: theme.status.error };
      case "cancelled":
        return { glyph: "\u2716", color: theme.status.warning };
      default:
        return { glyph: "\xB7", color: theme.text.secondary };
    }
  })();
  const stats = data.executionSummary;
  const parts = [];
  if (stats?.totalToolCalls !== void 0) {
    parts.push(
      `${stats.totalToolCalls} tool${stats.totalToolCalls === 1 ? "" : "s"}`
    );
  }
  const subagentSpawns = (stats?.toolUsage ?? []).filter((tu) => AGENT_TOOL_NAMES.has(tu.name)).reduce((sum, tu) => sum + tu.success, 0);
  if (subagentSpawns > 0) {
    parts.push(`${subagentSpawns} sub-agent${subagentSpawns === 1 ? "" : "s"}`);
  }
  if (stats?.totalDurationMs !== void 0) {
    parts.push(
      formatDuration(stats.totalDurationMs, { hideTrailingZeros: true })
    );
  }
  if (stats?.outputTokens && stats.outputTokens > 0) {
    parts.push(`${formatTokenCount(stats.outputTokens)} tokens`);
  }
  const tail = parts.length > 0 ? ` \xB7 ${parts.join(" \xB7 ")}` : "";
  const typePrefix = data.subagentName ? `${escapeAnsiCtrlCodes(data.subagentName)}: ` : "";
  const safeDescription = escapeAnsiCtrlCodes(data.taskDescription ?? "");
  const reason = data.status !== "completed" && data.terminateReason ? ` \xB7 ${escapeAnsiCtrlCodes(data.terminateReason)}` : "";
  return /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(Box_default, { paddingLeft: 1, children: /* @__PURE__ */ (0, import_jsx_runtime21.jsxs)(Text, { wrap: "truncate-end", children: [
    /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(Text, { color, children: `${glyph} ` }),
    /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(Text, { bold: true, children: typePrefix }),
    /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(Text, { color: theme.text.secondary, children: safeDescription }),
    /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(Text, { color: theme.text.secondary, children: tail }),
    /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(Text, { color: theme.text.secondary, children: reason })
  ] }) });
}, "SubagentScrollbackSummary");
var StringResultRenderer = /* @__PURE__ */ __name(({ data, renderAsMarkdown, availableHeight, childWidth }) => {
  let displayData = data;
  if (displayData.length > MAXIMUM_RESULT_DISPLAY_CHARACTERS) {
    displayData = "..." + displayData.slice(-MAXIMUM_RESULT_DISPLAY_CHARACTERS);
  }
  if (renderAsMarkdown) {
    return /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(Box_default, { flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(
      MarkdownDisplay,
      {
        text: displayData,
        isPending: false,
        availableTerminalHeight: availableHeight,
        contentWidth: childWidth
      }
    ) });
  }
  const sliced = sliceTextForMaxHeight(
    displayData,
    availableHeight,
    childWidth
  );
  return /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(
    MaxSizedBox,
    {
      maxHeight: availableHeight,
      maxWidth: childWidth,
      additionalHiddenLinesCount: sliced.hiddenLinesCount,
      children: /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(Text, { wrap: "wrap", color: theme.text.primary, children: sliced.text }) })
    }
  );
}, "StringResultRenderer");
var DiffResultRenderer = /* @__PURE__ */ __name(({ data, availableHeight, childWidth, settings }) => {
  const diffHeight = data.truncatedForSession && availableHeight !== void 0 ? Math.max(1, availableHeight - 1) : availableHeight;
  return /* @__PURE__ */ (0, import_jsx_runtime21.jsxs)(Box_default, { flexDirection: "column", children: [
    data.truncatedForSession && /* @__PURE__ */ (0, import_jsx_runtime21.jsxs)(Text, { color: theme.status.warning, wrap: "wrap", children: [
      data.fileDiffTruncated ? "Saved session preview only; full diff omitted from JSONL" : "Saved session preview only; full file contents truncated in JSONL",
      data.fileDiffTruncated && typeof data.fileDiffLength === "number" ? ` (${data.fileDiffLength} chars).` : "."
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(
      DiffRenderer,
      {
        diffContent: data.fileDiff,
        filename: data.fileName,
        availableTerminalHeight: diffHeight,
        contentWidth: childWidth,
        settings
      }
    )
  ] });
}, "DiffResultRenderer");
var ToolMessage = /* @__PURE__ */ __name(({
  name,
  description,
  resultDisplay,
  status,
  availableTerminalHeight,
  contentWidth,
  emphasis = "medium",
  renderOutputAsMarkdown = true,
  activeShellPtyId,
  embeddedShellFocused,
  ptyId,
  config,
  forceShowResult,
  isFocused,
  isPending,
  executionStartTime
}) => {
  const settings = useSettings();
  const isThisShellFocused = (name === SHELL_COMMAND_NAME || name === SHELL_NAME) && status === "Executing" /* Executing */ && ptyId === activeShellPtyId && embeddedShellFocused;
  const [lastUpdateTime, setLastUpdateTime] = import_react22.default.useState(null);
  const [userHasFocused, setUserHasFocused] = import_react22.default.useState(false);
  const [showFocusHint, setShowFocusHint] = import_react22.default.useState(false);
  import_react22.default.useEffect(() => {
    if (resultDisplay) {
      setLastUpdateTime(/* @__PURE__ */ new Date());
    }
  }, [resultDisplay]);
  const shellTimeoutMs = import_react22.default.useMemo(() => {
    if (typeof resultDisplay === "object" && resultDisplay !== null && "ansiOutput" in resultDisplay) {
      return resultDisplay.timeoutMs;
    }
    return void 0;
  }, [resultDisplay]);
  import_react22.default.useEffect(() => {
    if (!lastUpdateTime) {
      return;
    }
    const timer = setTimeout(() => {
      setShowFocusHint(true);
    }, 5e3);
    return () => clearTimeout(timer);
  }, [lastUpdateTime]);
  import_react22.default.useEffect(() => {
    if (isThisShellFocused) {
      setUserHasFocused(true);
    }
  }, [isThisShellFocused]);
  const isThisShellFocusable = (name === SHELL_COMMAND_NAME || name === SHELL_NAME) && status === "Executing" /* Executing */ && config?.getShouldUseNodePtyShell();
  const shouldShowFocusHint = isThisShellFocusable && (showFocusHint || userHasFocused);
  const availableHeight = availableTerminalHeight ? Math.max(
    availableTerminalHeight - STATIC_HEIGHT - RESERVED_LINE_COUNT,
    MIN_LINES_SHOWN + 1
    // enforce minimum lines shown
  ) : void 0;
  const isShellTool = name === SHELL_COMMAND_NAME || name === SHELL_NAME;
  const rawShellCap = settings.merged.ui?.shellOutputMaxLines ?? DEFAULT_SHELL_OUTPUT_MAX_LINES;
  const shellOutputMaxLines = Math.max(0, Math.floor(rawShellCap || 0));
  const isCappingShell = isShellTool && shellOutputMaxLines > 0 && !forceShowResult && !isThisShellFocused;
  const shellCapHeight = isCappingShell ? Math.min(availableHeight ?? shellOutputMaxLines, shellOutputMaxLines) : availableHeight;
  const shellStringCapHeight = isCappingShell && shellCapHeight !== void 0 ? shellCapHeight + 1 : availableHeight;
  const innerWidth = contentWidth - STATUS_INDICATOR_WIDTH;
  if (availableHeight) {
    renderOutputAsMarkdown = false;
  }
  const effectiveDisplayRenderer = useResultDisplayRenderer(resultDisplay);
  const shouldCollapseResult = !forceShowResult && status === "Success" /* Success */ && isCollapsibleTool(name) && (effectiveDisplayRenderer.type === "string" || effectiveDisplayRenderer.type === "ansi");
  return /* @__PURE__ */ (0, import_jsx_runtime21.jsxs)(Box_default, { paddingX: 1, paddingY: 0, flexDirection: "column", children: [
    /* @__PURE__ */ (0, import_jsx_runtime21.jsxs)(Box_default, { minHeight: 1, children: [
      /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(ToolStatusIndicator, { status, name }),
      /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(
        ToolInfo,
        {
          name,
          status,
          description,
          emphasis
        }
      ),
      shouldShowFocusHint && /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(Box_default, { marginLeft: 1, flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(Text, { color: theme.text.accent, children: isThisShellFocused ? "(Focused)" : "(ctrl+f to focus)" }) }),
      /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(
        ToolElapsedTime,
        {
          status,
          executionStartTime,
          timeoutMs: shellTimeoutMs
        }
      ),
      emphasis === "high" && /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(TrailingIndicator, {})
    ] }),
    effectiveDisplayRenderer.type !== "none" && !shouldCollapseResult && /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(Box_default, { paddingLeft: STATUS_INDICATOR_WIDTH, width: "100%", children: /* @__PURE__ */ (0, import_jsx_runtime21.jsxs)(Box_default, { flexDirection: "column", children: [
      effectiveDisplayRenderer.type === "todo" && /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(TodoResultRenderer, { data: effectiveDisplayRenderer.data }),
      effectiveDisplayRenderer.type === "plan" && /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(
        PlanResultRenderer,
        {
          data: effectiveDisplayRenderer.data,
          availableHeight,
          childWidth: innerWidth
        }
      ),
      effectiveDisplayRenderer.type === "task" && config && /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(
        SubagentExecutionRenderer,
        {
          data: effectiveDisplayRenderer.data,
          availableHeight,
          childWidth: innerWidth,
          config,
          isFocused,
          isPending
        }
      ),
      effectiveDisplayRenderer.type === "diff" && /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(
        DiffResultRenderer,
        {
          data: effectiveDisplayRenderer.data,
          availableHeight,
          childWidth: innerWidth,
          settings
        }
      ),
      effectiveDisplayRenderer.type === "ansi" && /* @__PURE__ */ (0, import_jsx_runtime21.jsxs)(import_jsx_runtime21.Fragment, { children: [
        /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(
          AnsiOutputText,
          {
            data: effectiveDisplayRenderer.data,
            availableTerminalHeight: shellCapHeight,
            maxWidth: innerWidth
          }
        ),
        effectiveDisplayRenderer.stats && /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(
          ShellStatsBar,
          {
            ...effectiveDisplayRenderer.stats,
            displayHeight: shellCapHeight
          }
        )
      ] }),
      effectiveDisplayRenderer.type === "string" && /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(
        StringResultRenderer,
        {
          data: effectiveDisplayRenderer.data,
          renderAsMarkdown: renderOutputAsMarkdown,
          availableHeight: shellStringCapHeight,
          childWidth: innerWidth
        }
      )
    ] }) }),
    isThisShellFocused && config && /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(Box_default, { paddingLeft: STATUS_INDICATOR_WIDTH, marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(
      ShellInputPrompt,
      {
        activeShellPtyId: activeShellPtyId ?? null,
        focus: embeddedShellFocused
      }
    ) })
  ] });
}, "ToolMessage");
var ToolInfo = /* @__PURE__ */ __name(({
  name,
  description,
  status,
  emphasis
}) => {
  const nameColor = import_react22.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]);
  return /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(Box_default, { flexGrow: 1, children: /* @__PURE__ */ (0, import_jsx_runtime21.jsxs)(Text, { wrap: "wrap", strikethrough: status === "Canceled" /* Canceled */, children: [
    /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(Text, { color: nameColor, bold: true, children: localizeToolDisplayName(name) }),
    " ",
    /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(Text, { color: theme.text.secondary, children: description })
  ] }) });
}, "ToolInfo");
var TrailingIndicator = /* @__PURE__ */ __name(() => /* @__PURE__ */ (0, import_jsx_runtime21.jsxs)(Text, { color: theme.text.primary, wrap: "truncate", children: [
  " ",
  "\u2190"
] }), "TrailingIndicator");

// packages/cli/src/ui/components/messages/InlineParallelAgentsDisplay.tsx
init_esbuild_shims();
var import_react23 = __toESM(require_react(), 1);
var import_jsx_runtime22 = __toESM(require_jsx_runtime(), 1);
function deriveAgentId(toolCall, resultDisplay) {
  return `${resultDisplay.subagentName}-${toolCall.callId}`;
}
__name(deriveAgentId, "deriveAgentId");
function isAgentResult(rd) {
  return typeof rd === "object" && rd !== null && "type" in rd && rd.type === "task_execution";
}
__name(isAgentResult, "isAgentResult");
var TOOL_DISPLAY_BY_NAME = Object.fromEntries(
  Object.keys(ToolNames).map((key) => [
    ToolNames[key],
    ToolDisplayNames[key]
  ])
);
function activityLabel(row) {
  const last = row.recentActivity;
  if (!last) return "";
  const display = localizeToolDisplayName(
    TOOL_DISPLAY_BY_NAME[last.name] ?? last.name
  );
  const desc = last.description?.replace(/\s*\n\s*/g, " ").trim();
  return desc ? `${display} ${desc}` : display;
}
__name(activityLabel, "activityLabel");
function statusGlyph(status) {
  switch (status) {
    case "running":
    case "background":
      return { glyph: "\u25CB", color: theme.status.warning };
    case "completed":
      return { glyph: "\u2714", color: theme.status.success };
    case "failed":
      return { glyph: "\u2716", color: theme.status.error };
    case "cancelled":
      return { glyph: "\u2716", color: theme.status.warning };
    default:
      return { glyph: "\xB7", color: theme.text.secondary };
  }
}
__name(statusGlyph, "statusGlyph");
function elapsedLabel(row, now) {
  let ms;
  if (row.startTime !== void 0) {
    const end = row.endTime ?? now;
    ms = Math.max(0, end - row.startTime);
  } else if (row.fallbackElapsedMs !== void 0) {
    ms = Math.max(0, row.fallbackElapsedMs);
  }
  if (ms === void 0) return "";
  return formatDuration(Math.floor(ms / 1e3) * 1e3, {
    hideTrailingZeros: true
  });
}
__name(elapsedLabel, "elapsedLabel");
var NAME_COL_WIDTH = 26;
function truncateMiddle(input, max) {
  if (input.length <= max) return input;
  if (max <= 1) return input.slice(0, max);
  const keep = max - 1;
  const head = Math.ceil(keep / 2);
  const tail = Math.floor(keep / 2);
  return `${input.slice(0, head)}\u2026${input.slice(input.length - tail)}`;
}
__name(truncateMiddle, "truncateMiddle");
var InlineParallelAgentsDisplay = /* @__PURE__ */ __name(({ toolCalls, contentWidth, totalAgentCount, availableTerminalHeight }) => {
  const config = (0, import_react23.useContext)(ConfigContext);
  const agentEntries = (0, import_react23.useMemo)(() => {
    const out = [];
    for (const tc of toolCalls) {
      if (isAgentResult(tc.resultDisplay)) {
        out.push({ toolCall: tc, result: tc.resultDisplay });
      }
    }
    return out;
  }, [toolCalls]);
  const [now, setNow] = (0, import_react23.useState)(() => Date.now());
  const hasLiveAgent = (0, import_react23.useMemo)(
    () => agentEntries.some(
      (e) => e.result.status === "running" || e.result.status === "background"
    ),
    [agentEntries]
  );
  (0, import_react23.useEffect)(() => {
    if (!hasLiveAgent) return;
    const id = setInterval(() => setNow(Date.now()), 1e3);
    return () => clearInterval(id);
  }, [hasLiveAgent]);
  const rows = (0, import_react23.useMemo)(() => {
    const registry = config?.getBackgroundTaskRegistry();
    void now;
    return agentEntries.map(({ toolCall, result }) => {
      const agentId = deriveAgentId(toolCall, result);
      const live = registry?.get(agentId);
      const recent = live?.recentActivities?.at(-1);
      return {
        agentId,
        callId: toolCall.callId,
        name: result.taskDescription || result.subagentName,
        status: result.status,
        startTime: live?.startTime,
        endTime: live?.endTime,
        fallbackElapsedMs: result.executionSummary?.totalDurationMs,
        recentActivity: recent ? { name: recent.name, description: recent.description } : void 0,
        tokenCount: result.tokenCount ?? live?.stats?.outputTokens ?? result.executionSummary?.outputTokens
      };
    });
  }, [agentEntries, config, now]);
  if (rows.length === 0) return null;
  const doneCount = rows.filter(
    (r) => r.status === "completed" || r.status === "failed" || r.status === "cancelled"
  ).length;
  const total = totalAgentCount ?? rows.length;
  const headerLabel = `Parallel agents \xB7 ${total} \xB7 ${doneCount}/${total} done`;
  const hasBudget = availableTerminalHeight != null && availableTerminalHeight > 0;
  let overflowCount = 0;
  let visibleRows = rows;
  if (hasBudget && rows.length + 1 > availableTerminalHeight) {
    if (availableTerminalHeight >= 2) {
      const rowsFit = availableTerminalHeight - 2;
      overflowCount = rows.length - rowsFit;
      visibleRows = rowsFit > 0 ? rows.slice(rows.length - rowsFit) : [];
    } else {
      visibleRows = [];
    }
  }
  return /* @__PURE__ */ (0, import_jsx_runtime22.jsxs)(Box_default, { flexDirection: "column", width: contentWidth, paddingX: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime22.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime22.jsx)(Text, { bold: true, color: theme.text.accent, wrap: "truncate-end", children: headerLabel }) }),
    overflowCount > 0 && /* @__PURE__ */ (0, import_jsx_runtime22.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime22.jsxs)(Text, { color: theme.text.secondary, wrap: "truncate-end", children: [
      "\u2026 +",
      overflowCount,
      " more ",
      overflowCount === 1 ? "agent" : "agents"
    ] }) }),
    visibleRows.map((row) => /* @__PURE__ */ (0, import_jsx_runtime22.jsx)(AgentRow, { row, now }, row.agentId))
  ] });
}, "InlineParallelAgentsDisplay");
var AgentRow = /* @__PURE__ */ __name(({ row, now }) => {
  const { glyph, color } = statusGlyph(row.status);
  const safeName = escapeAnsiCtrlCodes(row.name);
  const displayName = truncateMiddle(safeName, NAME_COL_WIDTH);
  const activity = escapeAnsiCtrlCodes(activityLabel(row));
  const elapsed = elapsedLabel(row, now);
  const tokens = row.tokenCount && row.tokenCount > 0 ? formatTokenCount(row.tokenCount) : "";
  const trailingParts = [];
  if (elapsed) trailingParts.push(elapsed);
  if (tokens) trailingParts.push(`${tokens} tok`);
  const trailing = trailingParts.join(" \xB7 ");
  return /* @__PURE__ */ (0, import_jsx_runtime22.jsxs)(Box_default, { flexDirection: "row", children: [
    /* @__PURE__ */ (0, import_jsx_runtime22.jsx)(Box_default, { flexShrink: 0, marginRight: 1, children: /* @__PURE__ */ (0, import_jsx_runtime22.jsx)(Text, { color, wrap: "truncate-end", children: glyph }) }),
    /* @__PURE__ */ (0, import_jsx_runtime22.jsx)(Box_default, { flexShrink: 0, marginRight: 1, width: NAME_COL_WIDTH, children: /* @__PURE__ */ (0, import_jsx_runtime22.jsx)(Text, { wrap: "truncate-end", children: displayName }) }),
    /* @__PURE__ */ (0, import_jsx_runtime22.jsx)(Box_default, { flexShrink: 1, flexGrow: 1, marginRight: 1, children: /* @__PURE__ */ (0, import_jsx_runtime22.jsx)(Text, { color: theme.text.secondary, wrap: "truncate-end", children: activity }) }),
    /* @__PURE__ */ (0, import_jsx_runtime22.jsx)(Box_default, { flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime22.jsx)(Text, { color: theme.text.secondary, wrap: "truncate-end", children: trailing }) })
  ] });
}, "AgentRow");

// packages/cli/src/ui/components/messages/ToolGroupMessage.tsx
var import_jsx_runtime23 = __toESM(require_jsx_runtime(), 1);
function isAgentWithPendingConfirmation(rd) {
  return typeof rd === "object" && rd !== null && "type" in rd && rd.type === "task_execution" && rd.pendingConfirmation !== void 0;
}
__name(isAgentWithPendingConfirmation, "isAgentWithPendingConfirmation");
function isRunningAgent(rd) {
  return typeof rd === "object" && rd !== null && "type" in rd && rd.type === "task_execution" && rd.status === "running";
}
__name(isRunningAgent, "isRunningAgent");
function isSubagentToolEntry(tool) {
  const rd = tool.resultDisplay;
  return typeof rd === "object" && rd !== null && "type" in rd && rd.type === "task_execution";
}
__name(isSubagentToolEntry, "isSubagentToolEntry");
function isPanelOwnedSubagentTool(tool) {
  if (!isSubagentToolEntry(tool)) return false;
  const status = tool.resultDisplay.status;
  return status === "running" || status === "background";
}
__name(isPanelOwnedSubagentTool, "isPanelOwnedSubagentTool");
function isPureParallelAgentGroup(toolCalls) {
  return toolCalls.length >= 2 && toolCalls.every(isSubagentToolEntry);
}
__name(isPureParallelAgentGroup, "isPureParallelAgentGroup");
function isTerminalSubagentTool(tool) {
  if (!isSubagentToolEntry(tool)) return false;
  const status = tool.resultDisplay.status;
  return status === "completed" || status === "failed" || status === "cancelled";
}
__name(isTerminalSubagentTool, "isTerminalSubagentTool");
var ToolGroupMessage = /* @__PURE__ */ __name(({
  toolCalls,
  availableTerminalHeight,
  contentWidth,
  isFocused = true,
  isPending = false,
  activeShellPtyId,
  embeddedShellFocused,
  memoryWriteCount,
  memoryReadCount,
  isUserInitiated
}) => {
  const config = useConfig();
  const hasConfirmingTool = toolCalls.some(
    (t2) => t2.status === "Confirming" /* Confirming */
  );
  const hasErrorTool = toolCalls.some((t2) => t2.status === "Error" /* Error */);
  const isEmbeddedShellFocused = embeddedShellFocused && toolCalls.some(
    (t2) => t2.ptyId === activeShellPtyId && t2.status === "Executing" /* Executing */
  );
  const toolAwaitingApproval = (0, import_react24.useMemo)(
    () => toolCalls.find((tc) => tc.status === "Confirming" /* Confirming */),
    [toolCalls]
  );
  const isMemoryOnlyGroup = (0, import_react24.useMemo)(
    () => toolCalls.length > 0 && toolCalls.every((t2) => t2.isMemoryOp != null),
    [toolCalls]
  );
  const inlineToolCalls = (0, import_react24.useMemo)(
    () => isPending ? toolCalls.filter(
      (tool) => !isPanelOwnedSubagentTool(tool) || isAgentWithPendingConfirmation(tool.resultDisplay)
    ) : toolCalls,
    [isPending, toolCalls]
  );
  const subagentsAwaitingApproval = (0, import_react24.useMemo)(
    () => toolCalls.filter(
      (tc) => isAgentWithPendingConfirmation(tc.resultDisplay)
    ),
    [toolCalls]
  );
  const focusedSubagentRef = (0, import_react24.useRef)(null);
  const stillPending = subagentsAwaitingApproval.some(
    (tc) => tc.callId === focusedSubagentRef.current
  );
  if (!stillPending) {
    focusedSubagentRef.current = subagentsAwaitingApproval[0]?.callId ?? null;
  }
  const focusedSubagentCallId = focusedSubagentRef.current;
  const runningSubagentCallId = (0, import_react24.useMemo)(
    () => toolCalls.find((tc) => isRunningAgent(tc.resultDisplay))?.callId ?? null,
    [toolCalls]
  );
  const keyboardFocusedSubagentCallId = focusedSubagentCallId ?? runningSubagentCallId;
  const hasSubagentPendingConfirmation = subagentsAwaitingApproval.length > 0;
  if (isPureParallelAgentGroup(toolCalls) && !hasSubagentPendingConfirmation) {
    if (inlineToolCalls.length === 0) {
      return null;
    }
    return /* @__PURE__ */ (0, import_jsx_runtime23.jsx)(
      InlineParallelAgentsDisplay,
      {
        toolCalls: inlineToolCalls,
        contentWidth,
        totalAgentCount: toolCalls.length,
        availableTerminalHeight: isPending ? availableTerminalHeight : void 0
      }
    );
  }
  if (isPending && inlineToolCalls.length === 0) {
    return null;
  }
  const allMemOpsComplete = isMemoryOnlyGroup && !hasErrorTool && toolCalls.every((t2) => t2.status === "Success" /* Success */);
  if (allMemOpsComplete) {
    const readCount = memoryReadCount ?? 0;
    const writeCount = memoryWriteCount ?? 0;
    return /* @__PURE__ */ (0, import_jsx_runtime23.jsxs)(Box_default, { flexDirection: "column", width: contentWidth, children: [
      readCount > 0 && /* @__PURE__ */ (0, import_jsx_runtime23.jsx)(Box_default, { paddingLeft: 1, children: /* @__PURE__ */ (0, import_jsx_runtime23.jsxs)(Text, { dimColor: true, children: [
        "\u25CF ",
        "Recalled ",
        readCount,
        " ",
        readCount === 1 ? "memory" : "memories"
      ] }) }),
      writeCount > 0 && /* @__PURE__ */ (0, import_jsx_runtime23.jsx)(Box_default, { paddingLeft: 1, children: /* @__PURE__ */ (0, import_jsx_runtime23.jsxs)(Text, { dimColor: true, children: [
        "\u25CF ",
        "Wrote ",
        writeCount,
        " ",
        writeCount === 1 ? "memory" : "memories"
      ] }) })
    ] });
  }
  const hasTerminalSubagent = inlineToolCalls.some(isTerminalSubagentTool);
  const forceExpandAll = hasConfirmingTool || hasSubagentPendingConfirmation || hasErrorTool || isEmbeddedShellFocused || isUserInitiated || hasTerminalSubagent;
  const collapsibleTools = forceExpandAll ? [] : inlineToolCalls.filter(
    (t2) => isCollapsibleTool(t2.name) && t2.status !== "Canceled" /* Canceled */
  );
  const nonCollapsibleTools = forceExpandAll ? inlineToolCalls : inlineToolCalls.filter(
    (t2) => !isCollapsibleTool(t2.name) || t2.status === "Canceled" /* Canceled */
  );
  const hasMemoryBadge = !isMemoryOnlyGroup && ((memoryWriteCount ?? 0) > 0 || (memoryReadCount ?? 0) > 0);
  const memoryBadge = hasMemoryBadge ? /* @__PURE__ */ (0, import_jsx_runtime23.jsx)(Box_default, { paddingLeft: 1, children: /* @__PURE__ */ (0, import_jsx_runtime23.jsxs)(Text, { dimColor: true, children: [
    "\u25CF ",
    [
      (memoryReadCount ?? 0) > 0 && `Recalled ${memoryReadCount} ${memoryReadCount === 1 ? "memory" : "memories"}`,
      (memoryWriteCount ?? 0) > 0 && `Wrote ${memoryWriteCount} ${memoryWriteCount === 1 ? "memory" : "memories"}`
    ].filter(Boolean).join(", ")
  ] }) }) : null;
  if (collapsibleTools.length > 0 && nonCollapsibleTools.length === 0) {
    return /* @__PURE__ */ (0, import_jsx_runtime23.jsxs)(Box_default, { flexDirection: "column", width: contentWidth, children: [
      /* @__PURE__ */ (0, import_jsx_runtime23.jsx)(
        CompactToolGroupDisplay,
        {
          toolCalls: collapsibleTools,
          contentWidth
        }
      ),
      memoryBadge
    ] });
  }
  const collapsibleSummaryHeight = collapsibleTools.length > 0 ? 1 : 0;
  const memoryBadgeHeight = hasMemoryBadge ? 1 : 0;
  const staticHeight = (
    /* marginBottom */
    1 + collapsibleSummaryHeight + memoryBadgeHeight
  );
  const innerWidth = contentWidth - 2;
  let countToolCallsWithResults = 0;
  for (const tool of nonCollapsibleTools) {
    if (tool.resultDisplay !== void 0 && tool.resultDisplay !== "") {
      countToolCallsWithResults++;
    }
  }
  const countOneLineToolCalls = nonCollapsibleTools.length - countToolCallsWithResults;
  const availableTerminalHeightPerToolMessage = availableTerminalHeight ? Math.max(
    Math.floor(
      (availableTerminalHeight - staticHeight - countOneLineToolCalls) / Math.max(1, countToolCallsWithResults)
    ),
    1
  ) : void 0;
  return /* @__PURE__ */ (0, import_jsx_runtime23.jsxs)(Box_default, { flexDirection: "column", width: contentWidth, gap: 0, children: [
    collapsibleTools.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime23.jsx)(
      CompactToolGroupDisplay,
      {
        toolCalls: collapsibleTools,
        contentWidth
      }
    ),
    memoryBadge,
    nonCollapsibleTools.map((tool) => {
      const isConfirming = toolAwaitingApproval?.callId === tool.callId;
      const isSubagentFocused = isFocused && !toolAwaitingApproval && keyboardFocusedSubagentCallId === tool.callId;
      return /* @__PURE__ */ (0, import_jsx_runtime23.jsxs)(Box_default, { flexDirection: "column", minHeight: 1, children: [
        /* @__PURE__ */ (0, import_jsx_runtime23.jsx)(Box_default, { flexDirection: "row", alignItems: "center", children: /* @__PURE__ */ (0, import_jsx_runtime23.jsx)(
          ToolMessage,
          {
            ...tool,
            availableTerminalHeight: availableTerminalHeightPerToolMessage,
            contentWidth: innerWidth,
            emphasis: isConfirming ? "high" : toolAwaitingApproval ? "low" : "medium",
            activeShellPtyId,
            embeddedShellFocused,
            config,
            forceShowResult: isUserInitiated || tool.status === "Confirming" /* Confirming */ || tool.status === "Error" /* Error */ || isAgentWithPendingConfirmation(tool.resultDisplay) || isTerminalSubagentTool(tool),
            isFocused: isSubagentFocused,
            isPending
          }
        ) }),
        tool.status === "Confirming" /* Confirming */ && isConfirming && tool.confirmationDetails && /* @__PURE__ */ (0, import_jsx_runtime23.jsx)(
          ToolConfirmationMessage,
          {
            confirmationDetails: tool.confirmationDetails,
            config,
            isFocused,
            availableTerminalHeight: availableTerminalHeightPerToolMessage,
            contentWidth: innerWidth
          }
        )
      ] }, tool.callId);
    })
  ] });
}, "ToolGroupMessage");

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

// packages/cli/src/ui/components/messages/SummaryMessage.tsx
init_esbuild_shims();
var import_jsx_runtime25 = __toESM(require_jsx_runtime(), 1);
var SummaryMessage = /* @__PURE__ */ __name(({ summary }) => {
  const getText = /* @__PURE__ */ __name(() => {
    if (summary.isPending) {
      switch (summary.stage) {
        case "generating":
          return t("Generating project summary...");
        case "saving":
          return t("Saving project summary...");
        default:
          return t("Processing summary...");
      }
    }
    const baseMessage = t("Project summary generated and saved successfully!");
    if (summary.filePath) {
      return `${baseMessage} ${t("Saved to: {{filePath}}", {
        filePath: summary.filePath
      })}`;
    }
    return baseMessage;
  }, "getText");
  const getIcon = /* @__PURE__ */ __name(() => {
    if (summary.isPending) {
      return /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(build_default, { type: "dots" });
    }
    return /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(Text, { color: Colors.AccentGreen, children: "\u2713" });
  }, "getIcon");
  return /* @__PURE__ */ (0, import_jsx_runtime25.jsxs)(Box_default, { flexDirection: "row", children: [
    /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(Box_default, { marginRight: 1, children: getIcon() }),
    /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(
      Text,
      {
        color: summary.isPending ? Colors.AccentPurple : Colors.AccentGreen,
        children: getText()
      }
    ) })
  ] });
}, "SummaryMessage");

// packages/cli/src/ui/components/messages/StatusMessages.tsx
init_esbuild_shims();

// node_modules/ink-link/dist/index.js
init_esbuild_shims();
var import_react25 = __toESM(require_react(), 1);
var import_prop_types = __toESM(require_prop_types(), 1);

// node_modules/ink-link/node_modules/terminal-link/index.js
init_esbuild_shims();

// node_modules/ink-link/node_modules/ansi-escapes/index.js
init_esbuild_shims();
var ESC2 = "\x1B[";
var OSC = "\x1B]";
var BEL = "\x07";
var SEP = ";";
var isTerminalApp = process.env.TERM_PROGRAM === "Apple_Terminal";
var ansiEscapes = {};
ansiEscapes.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) + ";" + (x + 1) + "H";
};
ansiEscapes.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;
};
ansiEscapes.cursorUp = (count = 1) => ESC2 + count + "A";
ansiEscapes.cursorDown = (count = 1) => ESC2 + count + "B";
ansiEscapes.cursorForward = (count = 1) => ESC2 + count + "C";
ansiEscapes.cursorBackward = (count = 1) => ESC2 + count + "D";
ansiEscapes.cursorLeft = ESC2 + "G";
ansiEscapes.cursorSavePosition = isTerminalApp ? "\x1B7" : ESC2 + "s";
ansiEscapes.cursorRestorePosition = isTerminalApp ? "\x1B8" : ESC2 + "u";
ansiEscapes.cursorGetPosition = ESC2 + "6n";
ansiEscapes.cursorNextLine = ESC2 + "E";
ansiEscapes.cursorPrevLine = ESC2 + "F";
ansiEscapes.cursorHide = ESC2 + "?25l";
ansiEscapes.cursorShow = ESC2 + "?25h";
ansiEscapes.eraseLines = (count) => {
  let clear = "";
  for (let i = 0; i < count; i++) {
    clear += ansiEscapes.eraseLine + (i < count - 1 ? ansiEscapes.cursorUp() : "");
  }
  if (count) {
    clear += ansiEscapes.cursorLeft;
  }
  return clear;
};
ansiEscapes.eraseEndLine = ESC2 + "K";
ansiEscapes.eraseStartLine = ESC2 + "1K";
ansiEscapes.eraseLine = ESC2 + "2K";
ansiEscapes.eraseDown = ESC2 + "J";
ansiEscapes.eraseUp = ESC2 + "1J";
ansiEscapes.eraseScreen = ESC2 + "2J";
ansiEscapes.scrollUp = ESC2 + "S";
ansiEscapes.scrollDown = ESC2 + "T";
ansiEscapes.clearScreen = "\x1Bc";
ansiEscapes.clearTerminal = process.platform === "win32" ? `${ansiEscapes.eraseScreen}${ESC2}0f` : (
  // 1. Erases the screen (Only done in case `2` is not supported)
  // 2. Erases the whole screen including scrollback buffer
  // 3. Moves cursor to the top-left position
  // More info: https://www.real-world-systems.com/docs/ANSIcode.html
  `${ansiEscapes.eraseScreen}${ESC2}3J${ESC2}H`
);
ansiEscapes.beep = BEL;
ansiEscapes.link = (text, url) => {
  return [
    OSC,
    "8",
    SEP,
    SEP,
    url,
    BEL,
    text,
    OSC,
    "8",
    SEP,
    SEP,
    BEL
  ].join("");
};
ansiEscapes.image = (buffer, 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";
  }
  return returnValue + ":" + buffer.toString("base64") + BEL;
};
ansiEscapes.iTerm = {
  setCwd: /* @__PURE__ */ __name((cwd2 = process.cwd()) => `${OSC}50;CurrentDir=${cwd2}${BEL}`, "setCwd"),
  annotation: /* @__PURE__ */ __name((message, options = {}) => {
    let returnValue = `${OSC}1337;`;
    const hasX = typeof options.x !== "undefined";
    const hasY = typeof options.y !== "undefined";
    if ((hasX || hasY) && !(hasX && hasY && typeof options.length !== "undefined")) {
      throw new Error("`x`, `y` and `length` must be defined when `x` or `y` is defined");
    }
    message = message.replace(/\|/g, "");
    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 returnValue + BEL;
  }, "annotation")
};
var ansi_escapes_default = ansiEscapes;

// node_modules/ink-link/node_modules/terminal-link/index.js
var import_supports_hyperlinks = __toESM(require_supports_hyperlinks(), 1);
function terminalLink(text, url, { target = "stdout", ...options } = {}) {
  if (!import_supports_hyperlinks.default[target]) {
    if (options.fallback === false) {
      return text;
    }
    return typeof options.fallback === "function" ? options.fallback(text, url) : `${text} (\u200B${url}\u200B)`;
  }
  return ansi_escapes_default.link(text, url);
}
__name(terminalLink, "terminalLink");
terminalLink.isSupported = import_supports_hyperlinks.default.stdout;
terminalLink.stderr = (text, url, options = {}) => terminalLink(text, url, { target: "stderr", ...options });
terminalLink.stderr.isSupported = import_supports_hyperlinks.default.stderr;

// node_modules/ink-link/dist/index.js
var Link = /* @__PURE__ */ __name(({ children, url, fallback = true }) => (
  // eslint-disable-line react/function-component-definition
  import_react25.default.createElement(
    Transform,
    { transform: /* @__PURE__ */ __name((children2) => terminalLink(children2, url, { fallback }), "transform") },
    import_react25.default.createElement(Text, null, children)
  )
), "Link");
Link.propTypes = {
  children: import_prop_types.default.oneOfType([
    import_prop_types.default.arrayOf(import_prop_types.default.node),
    import_prop_types.default.node
  ]).isRequired,
  url: import_prop_types.default.string.isRequired,
  fallback: import_prop_types.default.bool
  // eslint-disable-line react/boolean-prop-naming
};
var dist_default = Link;

// packages/cli/src/ui/components/messages/StatusMessages.tsx
var import_jsx_runtime26 = __toESM(require_jsx_runtime(), 1);
var StatusMessage = /* @__PURE__ */ __name(({
  text,
  prefix,
  prefixColor,
  textColor,
  children,
  footer
}) => {
  if ((!text || text.trim() === "") && !footer) {
    return null;
  }
  const prefixWidth = stringWidth(prefix) + 1;
  return /* @__PURE__ */ (0, import_jsx_runtime26.jsxs)(Box_default, { flexDirection: "row", children: [
    /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(Box_default, { width: prefixWidth, flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(Text, { color: prefixColor, children: prefix }) }),
    /* @__PURE__ */ (0, import_jsx_runtime26.jsxs)(Box_default, { flexGrow: 1, flexDirection: "column", children: [
      text && text.trim() !== "" && /* @__PURE__ */ (0, import_jsx_runtime26.jsxs)(Text, { wrap: "wrap", color: textColor, children: [
        /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(RenderInline, { text }),
        children
      ] }),
      footer
    ] })
  ] });
}, "StatusMessage");
var InfoMessage = /* @__PURE__ */ __name(({
  text,
  linkUrl,
  linkText
}) => /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(
  StatusMessage,
  {
    text,
    prefix: "\u25CF",
    prefixColor: theme.text.primary,
    textColor: theme.text.primary,
    footer: linkUrl && /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(dist_default, { url: linkUrl, children: /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(Text, { color: theme.text.link, underline: true, children: linkText ?? linkUrl }) })
  }
), "InfoMessage");
var SuccessMessage = /* @__PURE__ */ __name(({ text }) => /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(
  StatusMessage,
  {
    text,
    prefix: "\u2713",
    prefixColor: theme.status.success,
    textColor: theme.status.success
  }
), "SuccessMessage");
var WarningMessage = /* @__PURE__ */ __name(({ text }) => /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(
  StatusMessage,
  {
    text,
    prefix: "\u25B3",
    prefixColor: theme.status.warning,
    textColor: theme.status.warning
  }
), "WarningMessage");
var ErrorMessage = /* @__PURE__ */ __name(({
  text,
  hint
}) => /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(
  StatusMessage,
  {
    text,
    prefix: "\u2715",
    prefixColor: theme.status.error,
    textColor: theme.status.error,
    children: hint && /* @__PURE__ */ (0, import_jsx_runtime26.jsxs)(Text, { color: theme.text.secondary, children: [
      " (",
      hint,
      ")"
    ] })
  }
), "ErrorMessage");
var RetryCountdownMessage = /* @__PURE__ */ __name(({ text }) => /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(
  StatusMessage,
  {
    text,
    prefix: "\u21BB",
    prefixColor: theme.text.secondary,
    textColor: theme.text.secondary
  }
), "RetryCountdownMessage");
var VisionNoticeMessage = /* @__PURE__ */ __name(({ text }) => /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(
  StatusMessage,
  {
    text,
    prefix: "\u25CE",
    prefixColor: theme.text.secondary,
    textColor: theme.text.secondary
  }
), "VisionNoticeMessage");
var AwayRecapMessage = /* @__PURE__ */ __name(({ text }) => /* @__PURE__ */ (0, import_jsx_runtime26.jsxs)(Box_default, { flexDirection: "row", children: [
  /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(Box_default, { width: 2, flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(Text, { color: theme.text.secondary, children: "\u203B" }) }),
  /* @__PURE__ */ (0, import_jsx_runtime26.jsxs)(Text, { wrap: "wrap", children: [
    /* @__PURE__ */ (0, import_jsx_runtime26.jsxs)(Text, { color: theme.text.secondary, bold: true, children: [
      "recap:",
      " "
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(Text, { color: theme.text.secondary, italic: true, children: text })
  ] })
] }), "AwayRecapMessage");

// packages/cli/src/ui/components/AboutBox.tsx
init_esbuild_shims();
var import_jsx_runtime27 = __toESM(require_jsx_runtime(), 1);
var AboutBox = /* @__PURE__ */ __name(({ width, ...props }) => {
  const fields = getSystemInfoFields(props);
  return /* @__PURE__ */ (0, import_jsx_runtime27.jsxs)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: theme.border.default,
      flexDirection: "column",
      padding: 1,
      width,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(Box_default, { marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(Text, { bold: true, color: theme.text.accent, children: t("Status") }) }),
        fields.map((field) => /* @__PURE__ */ (0, import_jsx_runtime27.jsxs)(
          Box_default,
          {
            flexDirection: "row",
            marginTop: field.label === t("Auth") ? 1 : 0,
            children: [
              /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(Box_default, { width: "35%", children: /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(Text, { bold: true, color: theme.text.link, children: field.label }) }),
              /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(Text, { color: theme.text.primary, children: field.value }) })
            ]
          },
          field.label
        ))
      ]
    }
  );
}, "AboutBox");

// packages/cli/src/ui/components/StatsDisplay.tsx
init_esbuild_shims();

// node_modules/ink-gradient/dist/index.js
init_esbuild_shims();
var import_react26 = __toESM(require_react(), 1);
var import_prop_types2 = __toESM(require_prop_types(), 1);
var import_gradient_string = __toESM(require_gradient_string(), 1);
var Gradient = /* @__PURE__ */ __name((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 = /* @__PURE__ */ __name((text) => gradient.multiline(stripAnsi(text)), "applyGradient");
  return import_react26.default.createElement(Transform, { transform: applyGradient }, props.children);
}, "Gradient");
Gradient.propTypes = {
  children: import_prop_types2.default.oneOfType([
    import_prop_types2.default.arrayOf(import_prop_types2.default.node),
    import_prop_types2.default.node
  ]).isRequired,
  name: import_prop_types2.default.oneOf([
    "cristal",
    "teen",
    "mind",
    "morning",
    "vice",
    "passion",
    "fruit",
    "instagram",
    "atlas",
    "retro",
    "summer",
    "pastel",
    "rainbow"
  ]),
  colors: import_prop_types2.default.arrayOf(import_prop_types2.default.oneOfType([
    import_prop_types2.default.string,
    import_prop_types2.default.object
  ]))
};
var dist_default2 = Gradient;

// packages/cli/src/ui/utils/gradientUtils.ts
init_esbuild_shims();
function getRenderableGradientColors(...candidates) {
  return candidates.find(
    (colors) => Array.isArray(colors) && colors.length >= 2 && colors.every(
      (color) => typeof color === "string" && color.trim().length > 0
    )
  );
}
__name(getRenderableGradientColors, "getRenderableGradientColors");

// packages/cli/src/ui/utils/modelsBySource.ts
init_esbuild_shims();
function flattenModelsBySource(models) {
  const sessionHasNonMainSource = Object.values(models).some(
    (modelMetrics) => Object.keys(modelMetrics.bySource).some((source) => source !== MAIN_SOURCE)
  );
  const result = [];
  for (const [modelName, modelMetrics] of Object.entries(models)) {
    if (modelMetrics.api.totalRequests <= 0) continue;
    const displayName = normalizeModelName(modelName);
    const sourceNames = Object.keys(modelMetrics.bySource);
    if (sourceNames.length === 0) {
      result.push({
        key: modelName,
        label: displayName,
        metrics: modelMetrics
      });
      continue;
    }
    if (!sessionHasNonMainSource) {
      result.push({
        key: modelName,
        label: displayName,
        metrics: modelMetrics.bySource[MAIN_SOURCE] ?? modelMetrics
      });
      continue;
    }
    const sortedSources = sortSources(sourceNames);
    for (const source of sortedSources) {
      result.push({
        key: `${modelName}::${source}`,
        label: `${displayName} (${source})`,
        metrics: modelMetrics.bySource[source]
      });
    }
  }
  return result;
}
__name(flattenModelsBySource, "flattenModelsBySource");
function normalizeModelName(modelName) {
  return modelName.replace("-001", "");
}
__name(normalizeModelName, "normalizeModelName");
function sortSources(sources) {
  const main = [];
  const rest = [];
  for (const source of sources) {
    if (source === MAIN_SOURCE) {
      main.push(source);
    } else {
      rest.push(source);
    }
  }
  rest.sort((a, b) => a.localeCompare(b));
  return [...main, ...rest];
}
__name(sortSources, "sortSources");

// packages/cli/src/ui/components/StatsDisplay.tsx
var import_jsx_runtime28 = __toESM(require_jsx_runtime(), 1);
var StatRow = /* @__PURE__ */ __name(({ title, children }) => /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(Box_default, { children: [
  /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Box_default, { width: 28, children: /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Text, { color: theme.text.link, children: title }) }),
  /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Box_default, { flexGrow: 1, children })
] }), "StatRow");
var SubStatRow = /* @__PURE__ */ __name(({ title, children }) => /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(Box_default, { paddingLeft: 2, children: [
  /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Box_default, { width: 26, children: /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(Text, { color: theme.text.secondary, children: [
    "\xBB ",
    title
  ] }) }),
  /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Box_default, { flexGrow: 1, children })
] }), "SubStatRow");
var Section = /* @__PURE__ */ __name(({ title, children }) => /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(Box_default, { flexDirection: "column", width: "100%", marginBottom: 1, children: [
  /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Text, { bold: true, color: theme.text.primary, children: title }),
  children
] }), "Section");
var ModelUsageTable = /* @__PURE__ */ __name(({ models, totalCachedTokens, cacheEfficiency }) => {
  const nameWidth = 35;
  const requestsWidth = 8;
  const inputTokensWidth = 15;
  const outputTokensWidth = 15;
  const entries = flattenModelsBySource(models);
  return /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(Box_default, { flexDirection: "column", marginTop: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(Box_default, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Box_default, { width: nameWidth, children: /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Text, { bold: true, color: theme.text.primary, children: t("Model Usage") }) }),
      /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Box_default, { width: requestsWidth, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Text, { bold: true, color: theme.text.primary, children: t("Reqs") }) }),
      /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Box_default, { width: inputTokensWidth, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Text, { bold: true, color: theme.text.primary, children: t("Input Tokens") }) }),
      /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Box_default, { width: outputTokensWidth, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Text, { bold: true, color: theme.text.primary, children: t("Output Tokens") }) })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(
      Box_default,
      {
        borderStyle: "round",
        borderBottom: true,
        borderTop: false,
        borderLeft: false,
        borderRight: false,
        borderColor: theme.border.default,
        width: nameWidth + requestsWidth + inputTokensWidth + outputTokensWidth
      }
    ),
    entries.map(({ key, label, metrics }) => /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(Box_default, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Box_default, { width: nameWidth, children: /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Text, { color: theme.text.primary, children: label }) }),
      /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Box_default, { width: requestsWidth, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Text, { color: theme.text.primary, children: metrics.api.totalRequests }) }),
      /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Box_default, { width: inputTokensWidth, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Text, { color: theme.status.warning, children: metrics.tokens.prompt.toLocaleString() }) }),
      /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Box_default, { width: outputTokensWidth, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Text, { color: theme.status.warning, children: metrics.tokens.candidates.toLocaleString() }) })
    ] }, key)),
    cacheEfficiency > 0 && /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(Box_default, { flexDirection: "column", marginTop: 1, children: [
      /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(Text, { color: theme.text.primary, children: [
        /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Text, { color: theme.status.success, children: t("Savings Highlight:") }),
        " ",
        totalCachedTokens.toLocaleString(),
        " (",
        cacheEfficiency.toFixed(1),
        "%)",
        " ",
        t("of input tokens were served from the cache, reducing costs.")
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Box_default, { height: 1 }),
      /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(Text, { color: theme.text.secondary, children: [
        "\xBB ",
        t("Tip: For a full token breakdown, run `/stats model`.")
      ] })
    ] })
  ] });
}, "ModelUsageTable");
var StatsDisplay = /* @__PURE__ */ __name(({
  duration,
  title,
  width
}) => {
  const { stats } = useSessionStats();
  const { metrics } = stats;
  const { models, tools, files } = metrics;
  const computed = computeSessionStats(metrics);
  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 = /* @__PURE__ */ __name(() => {
    if (title) {
      const gradientColors = getRenderableGradientColors(theme.ui.gradient);
      return gradientColors ? /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(dist_default2, { colors: gradientColors, children: /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Text, { bold: true, color: theme.text.primary, children: title }) }) : /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Text, { bold: true, color: theme.text.accent, children: title });
    }
    return /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Text, { bold: true, color: theme.text.accent, children: t("Session Stats") });
  }, "renderTitle");
  return /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: theme.border.default,
      flexDirection: "column",
      paddingY: 1,
      paddingX: 2,
      width,
      children: [
        renderTitle(),
        /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Box_default, { height: 1 }),
        /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(Section, { title: t("Interaction Summary"), children: [
          /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(StatRow, { title: t("Session ID:"), children: /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Text, { color: theme.text.primary, children: stats.sessionId }) }),
          /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(StatRow, { title: t("Tool Calls:"), children: /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(Text, { color: theme.text.primary, children: [
            tools.totalCalls,
            " (",
            " ",
            /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(Text, { color: theme.status.success, children: [
              "\u2713 ",
              tools.totalSuccess
            ] }),
            " ",
            /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(Text, { color: theme.status.error, children: [
              "x ",
              tools.totalFail
            ] }),
            " )"
          ] }) }),
          /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(StatRow, { title: t("Success Rate:"), children: /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(Text, { color: successColor, children: [
            computed.successRate.toFixed(1),
            "%"
          ] }) }),
          computed.totalDecisions > 0 && /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(StatRow, { title: t("User Agreement:"), children: /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(Text, { color: agreementColor, children: [
            computed.agreementRate.toFixed(1),
            "%",
            " ",
            /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(Text, { color: theme.text.secondary, children: [
              "(",
              computed.totalDecisions,
              " ",
              t("reviewed"),
              ")"
            ] })
          ] }) }),
          files && (files.totalLinesAdded > 0 || files.totalLinesRemoved > 0) && /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(StatRow, { title: t("Code Changes:"), children: /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(Text, { color: theme.text.primary, children: [
            /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(Text, { color: theme.status.success, children: [
              "+",
              files.totalLinesAdded
            ] }),
            " ",
            /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(Text, { color: theme.status.error, children: [
              "-",
              files.totalLinesRemoved
            ] })
          ] }) })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(Section, { title: t("Performance"), children: [
          /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(StatRow, { title: t("Wall Time:"), children: /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Text, { color: theme.text.primary, children: duration }) }),
          /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(StatRow, { title: t("Agent Active:"), children: /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Text, { color: theme.text.primary, children: formatDuration(computed.agentActiveTime) }) }),
          /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(SubStatRow, { title: t("API Time:"), children: /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(Text, { color: theme.text.primary, children: [
            formatDuration(computed.totalApiTime),
            " ",
            /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(Text, { color: theme.text.secondary, children: [
              "(",
              computed.apiTimePercent.toFixed(1),
              "%)"
            ] })
          ] }) }),
          /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(SubStatRow, { title: t("Tool Time:"), children: /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(Text, { color: theme.text.primary, children: [
            formatDuration(computed.totalToolTime),
            " ",
            /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(Text, { color: theme.text.secondary, children: [
              "(",
              computed.toolTimePercent.toFixed(1),
              "%)"
            ] })
          ] }) })
        ] }),
        Object.keys(models).length > 0 && /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(
          ModelUsageTable,
          {
            models,
            totalCachedTokens: computed.totalCachedTokens,
            cacheEfficiency: computed.cacheEfficiency
          }
        )
      ]
    }
  );
}, "StatsDisplay");

// packages/cli/src/ui/components/ModelStatsDisplay.tsx
init_esbuild_shims();
var import_jsx_runtime29 = __toESM(require_jsx_runtime(), 1);
var METRIC_COL_WIDTH = 28;
var MODEL_COL_WIDTH = 24;
var PANEL_HORIZONTAL_CHROME_WIDTH = 6;
var StatRow2 = /* @__PURE__ */ __name(({
  title,
  values,
  modelColWidth,
  isSubtle = false,
  isSection = false
}) => /* @__PURE__ */ (0, import_jsx_runtime29.jsxs)(Box_default, { children: [
  /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(Box_default, { width: METRIC_COL_WIDTH, children: /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(
    Text,
    {
      bold: isSection,
      color: isSection ? theme.text.primary : theme.text.link,
      children: isSubtle ? `  \u21B3 ${title}` : title
    }
  ) }),
  values.map((value, index) => /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(Box_default, { width: modelColWidth, children: /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(Text, { color: theme.text.primary, children: value }) }, index))
] }), "StatRow");
var ModelStatsDisplay = /* @__PURE__ */ __name(({
  width
}) => {
  const { stats } = useSessionStats();
  const { models } = stats.metrics;
  const entries = flattenModelsBySource(models);
  const settings = useSettings();
  const modelPricing = settings.merged.modelPricing;
  if (entries.length === 0) {
    return /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(
      Box_default,
      {
        borderStyle: "round",
        borderColor: theme.border.default,
        paddingY: 1,
        paddingX: 2,
        width,
        children: /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(Text, { color: theme.text.primary, children: t("No API calls have been made in this session.") })
      }
    );
  }
  const getModelValues = /* @__PURE__ */ __name((getter) => entries.map(({ metrics }) => getter(metrics)), "getModelValues");
  const hasThoughts = entries.some(
    ({ metrics }) => metrics.tokens.thoughts > 0
  );
  const hasCached = entries.some(({ metrics }) => metrics.tokens.cached > 0);
  const modelColWidth = entries.length === 1 && width ? Math.max(
    MODEL_COL_WIDTH,
    width - PANEL_HORIZONTAL_CHROME_WIDTH - METRIC_COL_WIDTH
  ) : MODEL_COL_WIDTH;
  const getModelName = /* @__PURE__ */ __name((key) => key.split("::")[0], "getModelName");
  const hasPricing = entries.some(
    ({ key, metrics }) => calculateCost({
      inputTokens: metrics.tokens.prompt,
      outputTokens: metrics.tokens.candidates + metrics.tokens.thoughts,
      pricing: modelPricing?.[getModelName(key)]
    }) != null
  );
  return /* @__PURE__ */ (0, import_jsx_runtime29.jsxs)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: theme.border.default,
      flexDirection: "column",
      paddingY: 1,
      paddingX: 2,
      width,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(Text, { bold: true, color: theme.text.accent, children: t("Model Stats For Nerds") }),
        /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(Box_default, { height: 1 }),
        /* @__PURE__ */ (0, import_jsx_runtime29.jsxs)(Box_default, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(Box_default, { width: METRIC_COL_WIDTH, children: /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(Text, { bold: true, color: theme.text.primary, children: t("Metric") }) }),
          entries.map(({ key, label }) => /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(Box_default, { width: modelColWidth, children: /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(Text, { bold: true, color: theme.text.primary, children: label }) }, key))
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(
          Box_default,
          {
            borderStyle: "single",
            borderBottom: true,
            borderTop: false,
            borderLeft: false,
            borderRight: false,
            borderColor: theme.border.default
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(
          StatRow2,
          {
            title: t("API"),
            values: [],
            modelColWidth,
            isSection: true
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(
          StatRow2,
          {
            title: t("Requests"),
            values: getModelValues((m) => m.api.totalRequests.toLocaleString()),
            modelColWidth
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(
          StatRow2,
          {
            title: t("Errors"),
            values: getModelValues((m) => {
              const errorRate = calculateErrorRate(m);
              return /* @__PURE__ */ (0, import_jsx_runtime29.jsxs)(
                Text,
                {
                  color: m.api.totalErrors > 0 ? theme.status.error : theme.text.primary,
                  children: [
                    m.api.totalErrors.toLocaleString(),
                    " (",
                    errorRate.toFixed(1),
                    "%)"
                  ]
                }
              );
            }),
            modelColWidth
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(
          StatRow2,
          {
            title: t("Avg Latency"),
            values: getModelValues((m) => {
              const avgLatency = calculateAverageLatency(m);
              return formatDuration(avgLatency);
            }),
            modelColWidth
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(Box_default, { height: 1 }),
        /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(
          StatRow2,
          {
            title: t("Tokens"),
            values: [],
            modelColWidth,
            isSection: true
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(
          StatRow2,
          {
            title: t("Total"),
            values: getModelValues((m) => /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(Text, { color: theme.status.warning, children: m.tokens.total.toLocaleString() })),
            modelColWidth
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(
          StatRow2,
          {
            title: t("Prompt"),
            isSubtle: true,
            values: getModelValues((m) => m.tokens.prompt.toLocaleString()),
            modelColWidth
          }
        ),
        hasCached && /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(
          StatRow2,
          {
            title: t("Cached"),
            isSubtle: true,
            values: getModelValues((m) => {
              const cacheHitRate = calculateCacheHitRate(m);
              return /* @__PURE__ */ (0, import_jsx_runtime29.jsxs)(Text, { color: theme.status.success, children: [
                m.tokens.cached.toLocaleString(),
                " (",
                cacheHitRate.toFixed(1),
                "%)"
              ] });
            }),
            modelColWidth
          }
        ),
        hasThoughts && /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(
          StatRow2,
          {
            title: t("Thoughts"),
            isSubtle: true,
            values: getModelValues((m) => m.tokens.thoughts.toLocaleString()),
            modelColWidth
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(
          StatRow2,
          {
            title: t("Output"),
            isSubtle: true,
            values: getModelValues((m) => m.tokens.candidates.toLocaleString()),
            modelColWidth
          }
        ),
        hasPricing && /* @__PURE__ */ (0, import_jsx_runtime29.jsxs)(import_jsx_runtime29.Fragment, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(Box_default, { height: 1 }),
          /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(
            StatRow2,
            {
              title: t("Cost"),
              values: [],
              modelColWidth,
              isSection: true
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(
            StatRow2,
            {
              title: t("Estimated"),
              values: entries.map(({ key, metrics }) => {
                const cost = calculateCost({
                  inputTokens: metrics.tokens.prompt,
                  outputTokens: metrics.tokens.candidates + metrics.tokens.thoughts,
                  pricing: modelPricing?.[getModelName(key)]
                });
                return cost != null ? `$${cost.toFixed(4)}` : "N/A";
              }),
              modelColWidth
            }
          )
        ] })
      ]
    }
  );
}, "ModelStatsDisplay");

// packages/cli/src/ui/components/ToolStatsDisplay.tsx
init_esbuild_shims();
var import_jsx_runtime30 = __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 StatRow3 = /* @__PURE__ */ __name(({ 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_runtime30.jsxs)(Box_default, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Box_default, { width: TOOL_NAME_COL_WIDTH, children: /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Text, { color: theme.text.link, children: name }) }),
    /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Box_default, { width: CALLS_COL_WIDTH, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Text, { color: theme.text.primary, children: stats.count }) }),
    /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Box_default, { width: SUCCESS_RATE_COL_WIDTH, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime30.jsxs)(Text, { color: successColor, children: [
      successRate.toFixed(1),
      "%"
    ] }) }),
    /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Box_default, { width: AVG_DURATION_COL_WIDTH, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Text, { color: theme.text.primary, children: formatDuration(avgDuration) }) })
  ] });
}, "StatRow");
var ToolStatsDisplay = /* @__PURE__ */ __name(({
  width
}) => {
  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_runtime30.jsx)(
      Box_default,
      {
        borderStyle: "round",
        borderColor: theme.border.default,
        paddingY: 1,
        paddingX: 2,
        width,
        children: /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Text, { color: theme.text.primary, children: t("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_runtime30.jsxs)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: theme.border.default,
      flexDirection: "column",
      paddingY: 1,
      paddingX: 2,
      width,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Text, { bold: true, color: theme.text.accent, children: t("Tool Stats For Nerds") }),
        /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Box_default, { height: 1 }),
        /* @__PURE__ */ (0, import_jsx_runtime30.jsxs)(Box_default, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Box_default, { width: TOOL_NAME_COL_WIDTH, children: /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Text, { bold: true, color: theme.text.primary, children: t("Tool Name") }) }),
          /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Box_default, { width: CALLS_COL_WIDTH, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Text, { bold: true, color: theme.text.primary, children: t("Calls") }) }),
          /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Box_default, { width: SUCCESS_RATE_COL_WIDTH, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Text, { bold: true, color: theme.text.primary, children: t("Success Rate") }) }),
          /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Box_default, { width: AVG_DURATION_COL_WIDTH, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Text, { bold: true, color: theme.text.primary, children: t("Avg Duration") }) })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime30.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_runtime30.jsx)(StatRow3, { name, stats: stats2 }, name)),
        /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Box_default, { height: 1 }),
        /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Text, { bold: true, color: theme.text.primary, children: t("User Decision Summary") }),
        /* @__PURE__ */ (0, import_jsx_runtime30.jsxs)(Box_default, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(
            Box_default,
            {
              width: TOOL_NAME_COL_WIDTH + CALLS_COL_WIDTH + SUCCESS_RATE_COL_WIDTH,
              children: /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Text, { color: theme.text.link, children: t("Total Reviewed Suggestions:") })
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Box_default, { width: AVG_DURATION_COL_WIDTH, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Text, { color: theme.text.primary, children: totalReviewed }) })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime30.jsxs)(Box_default, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(
            Box_default,
            {
              width: TOOL_NAME_COL_WIDTH + CALLS_COL_WIDTH + SUCCESS_RATE_COL_WIDTH,
              children: /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Text, { color: theme.text.primary, children: t(" \xBB Accepted:") })
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Box_default, { width: AVG_DURATION_COL_WIDTH, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Text, { color: theme.status.success, children: totalDecisions.accept }) })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime30.jsxs)(Box_default, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(
            Box_default,
            {
              width: TOOL_NAME_COL_WIDTH + CALLS_COL_WIDTH + SUCCESS_RATE_COL_WIDTH,
              children: /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Text, { color: theme.text.primary, children: t(" \xBB Rejected:") })
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Box_default, { width: AVG_DURATION_COL_WIDTH, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Text, { color: theme.status.error, children: totalDecisions.reject }) })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime30.jsxs)(Box_default, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(
            Box_default,
            {
              width: TOOL_NAME_COL_WIDTH + CALLS_COL_WIDTH + SUCCESS_RATE_COL_WIDTH,
              children: /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Text, { color: theme.text.primary, children: t(" \xBB Modified:") })
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Box_default, { width: AVG_DURATION_COL_WIDTH, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Text, { color: theme.status.warning, children: totalDecisions.modify }) })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(
          Box_default,
          {
            borderStyle: "single",
            borderBottom: true,
            borderTop: false,
            borderLeft: false,
            borderRight: false,
            borderColor: theme.border.default,
            width: "100%"
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime30.jsxs)(Box_default, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(
            Box_default,
            {
              width: TOOL_NAME_COL_WIDTH + CALLS_COL_WIDTH + SUCCESS_RATE_COL_WIDTH,
              children: /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Text, { color: theme.text.primary, children: t(" Overall Agreement Rate:") })
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Box_default, { width: AVG_DURATION_COL_WIDTH, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(Text, { bold: true, color: totalReviewed > 0 ? agreementColor : void 0, children: totalReviewed > 0 ? `${agreementRate.toFixed(1)}%` : "--" }) })
        ] })
      ]
    }
  );
}, "ToolStatsDisplay");

// packages/cli/src/ui/components/SkillStatsDisplay.tsx
init_esbuild_shims();
var import_jsx_runtime31 = __toESM(require_jsx_runtime(), 1);
var SKILL_NAME_COL_WIDTH = 30;
var CALLS_COL_WIDTH2 = 8;
var SUCCESS_COL_WIDTH = 8;
var FAIL_COL_WIDTH = 8;
var SUCCESS_RATE_COL_WIDTH2 = 15;
var StatRow4 = /* @__PURE__ */ __name(({ name, stats }) => {
  const successRate = stats.count > 0 ? stats.success / stats.count * 100 : 0;
  const successColor = getStatusColor(successRate, {
    green: TOOL_SUCCESS_RATE_HIGH,
    yellow: TOOL_SUCCESS_RATE_MEDIUM
  });
  return /* @__PURE__ */ (0, import_jsx_runtime31.jsxs)(Box_default, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Box_default, { width: SKILL_NAME_COL_WIDTH, children: /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Text, { color: theme.text.link, children: name }) }),
    /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Box_default, { width: CALLS_COL_WIDTH2, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Text, { color: theme.text.primary, children: stats.count }) }),
    /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Box_default, { width: SUCCESS_COL_WIDTH, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Text, { color: theme.status.success, children: stats.success }) }),
    /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Box_default, { width: FAIL_COL_WIDTH, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Text, { color: stats.fail > 0 ? theme.status.error : theme.text.primary, children: stats.fail }) }),
    /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Box_default, { width: SUCCESS_RATE_COL_WIDTH2, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime31.jsxs)(Text, { color: successColor, children: [
      successRate.toFixed(1),
      "%"
    ] }) })
  ] });
}, "StatRow");
var SkillStatsDisplay = /* @__PURE__ */ __name(({
  width
}) => {
  const { stats } = useSessionStats();
  const skills = stats.metrics.skills ?? {
    totalCalls: 0,
    totalSuccess: 0,
    totalFail: 0,
    byName: {}
  };
  const activeSkills = Object.entries(skills.byName).filter(([, metrics]) => metrics.count > 0).sort(([leftName, left], [rightName, right]) => {
    const countDelta = right.count - left.count;
    return countDelta !== 0 ? countDelta : leftName.localeCompare(rightName);
  });
  if (activeSkills.length === 0) {
    return /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(
      Box_default,
      {
        borderStyle: "round",
        borderColor: theme.border.default,
        paddingY: 1,
        paddingX: 2,
        width,
        children: /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Text, { color: theme.text.primary, children: t("No skill calls have been made in this session.") })
      }
    );
  }
  return /* @__PURE__ */ (0, import_jsx_runtime31.jsxs)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: theme.border.default,
      flexDirection: "column",
      paddingY: 1,
      paddingX: 2,
      width,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Text, { bold: true, color: theme.text.accent, children: t("Skill Stats For Nerds") }),
        /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Box_default, { height: 1 }),
        /* @__PURE__ */ (0, import_jsx_runtime31.jsxs)(Box_default, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Box_default, { width: SKILL_NAME_COL_WIDTH, children: /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Text, { bold: true, color: theme.text.primary, children: t("Skill Name") }) }),
          /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Box_default, { width: CALLS_COL_WIDTH2, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Text, { bold: true, color: theme.text.primary, children: t("Calls") }) }),
          /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Box_default, { width: SUCCESS_COL_WIDTH, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Text, { bold: true, color: theme.text.primary, children: t("OK") }) }),
          /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Box_default, { width: FAIL_COL_WIDTH, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Text, { bold: true, color: theme.text.primary, children: t("Fail") }) }),
          /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Box_default, { width: SUCCESS_RATE_COL_WIDTH2, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(Text, { bold: true, color: theme.text.primary, children: t("Success Rate") }) })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(
          Box_default,
          {
            borderStyle: "single",
            borderBottom: true,
            borderTop: false,
            borderLeft: false,
            borderRight: false,
            borderColor: theme.border.default,
            width: "100%"
          }
        ),
        activeSkills.map(([name, skillStats]) => /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(StatRow4, { name, stats: skillStats }, name))
      ]
    }
  );
}, "SkillStatsDisplay");

// packages/cli/src/ui/components/SessionSummaryDisplay.tsx
init_esbuild_shims();
var import_jsx_runtime32 = __toESM(require_jsx_runtime(), 1);
var SessionSummaryDisplay = /* @__PURE__ */ __name(({
  duration,
  width
}) => {
  const config = useConfig();
  const { stats } = useSessionStats();
  const hasMessages = stats.promptCount > 0;
  const canResume = !!config.getChatRecordingService();
  return /* @__PURE__ */ (0, import_jsx_runtime32.jsxs)(import_jsx_runtime32.Fragment, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime32.jsx)(
      StatsDisplay,
      {
        title: t("Agent powering down. Goodbye!"),
        duration,
        width
      }
    ),
    hasMessages && canResume && /* @__PURE__ */ (0, import_jsx_runtime32.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime32.jsxs)(Text, { color: theme.text.secondary, children: [
      t("To continue this session, run"),
      " ",
      /* @__PURE__ */ (0, import_jsx_runtime32.jsxs)(Text, { color: theme.text.accent, children: [
        "qwen --resume ",
        stats.sessionId
      ] })
    ] }) })
  ] });
}, "SessionSummaryDisplay");

// packages/cli/src/ui/components/Help.tsx
init_esbuild_shims();
var import_react27 = __toESM(require_react(), 1);
var import_jsx_runtime33 = __toESM(require_jsx_runtime(), 1);
var DEFAULT_WIDTH = 100;
var KEY_COL_WIDTH = 20;
var COMMAND_LIST_VISIBLE_LINES = 18;
var TAB_DEFS = [
  { tab: "general", labelKey: "general" },
  { tab: "commands", labelKey: "commands" },
  { tab: "custom-commands", labelKey: "custom-commands" }
];
var DOCS_URL = "https://qwenlm.github.io/qwen-code-docs/";
var Help = /* @__PURE__ */ __name(({
  commands,
  width = DEFAULT_WIDTH,
  activeTab = "general",
  onTabChange,
  onClose,
  isInteractive = false
}) => {
  const safeWidth = Math.max(72, width);
  const bodyWidth = safeWidth - 6;
  const handleTabChange = (0, import_react27.useCallback)(
    (direction) => {
      const currentIndex = TAB_DEFS.findIndex((tab) => tab.tab === activeTab);
      const nextIndex = (currentIndex + direction + TAB_DEFS.length) % TAB_DEFS.length;
      onTabChange?.(TAB_DEFS[nextIndex].tab);
    },
    [activeTab, onTabChange]
  );
  useKeypress(
    (key) => {
      if (key.name === "escape") {
        onClose?.();
        return;
      }
      if (key.name === "tab") {
        handleTabChange(key.shift ? -1 : 1);
      }
    },
    { isActive: isInteractive }
  );
  return /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(Box_default, { flexDirection: "column", width: safeWidth, children: /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
    Box_default,
    {
      borderColor: theme.border.default,
      borderStyle: "single",
      width: safeWidth,
      children: /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)(
        Box_default,
        {
          flexDirection: "column",
          paddingX: 2,
          paddingY: 1,
          width: safeWidth - 2,
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(HelpTabs, { activeTab }),
            /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)(Box_default, { marginTop: 1, children: [
              activeTab === "general" && /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(GeneralHelp, { width: bodyWidth }),
              activeTab === "commands" && /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
                CommandsHelp,
                {
                  commands,
                  width: bodyWidth,
                  customOnly: false,
                  isInteractive
                }
              ),
              activeTab === "custom-commands" && /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
                CommandsHelp,
                {
                  commands,
                  width: bodyWidth,
                  customOnly: true,
                  isInteractive
                }
              )
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)(Text, { color: theme.text.secondary, children: [
              t("For more help:"),
              " ",
              /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(Text, { underline: true, children: DOCS_URL })
            ] }) }),
            /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(Text, { italic: true, color: theme.text.secondary, children: t("Tab/Shift+Tab to switch tabs  \xB7  Esc to cancel") }) })
          ]
        }
      )
    }
  ) });
}, "Help");
var HelpTabs = /* @__PURE__ */ __name(({ activeTab }) => /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)(Box_default, { flexDirection: "row", children: [
  /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(Text, { bold: true, color: theme.text.accent, children: "Qwen Code" }),
  /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(Text, { color: theme.text.secondary, children: " " }),
  TAB_DEFS.map(({ tab, labelKey }) => {
    const active = tab === activeTab;
    return /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(Box_default, { marginLeft: 1, children: /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
      Text,
      {
        color: active ? theme.background.primary : theme.text.primary,
        backgroundColor: active ? theme.text.accent : void 0,
        children: ` ${t(labelKey)} `
      }
    ) }, tab);
  })
] }), "HelpTabs");
var GeneralHelp = /* @__PURE__ */ __name(({ width }) => {
  const shortcuts = [
    ["@", t("Add files or folders as context")],
    ["!", t("Run shell commands")],
    ["/", t("Open command menu")],
    ["Tab", t("Accept ghost text or completion")],
    ["Esc Esc", t("Clear input or cancel operation")],
    ["Ctrl+L", t("Clear the screen")],
    [
      process.platform === "win32" ? "Ctrl+Enter" : "Ctrl+J",
      t("Insert a newline")
    ],
    [
      process.platform === "win32" ? "Tab" : "Shift+Tab",
      t("Cycle approval modes")
    ],
    ["Alt+\u2190/\u2192", t("Jump through words")],
    ["\u2191/\u2193", t("Cycle prompt history")]
  ];
  const left = shortcuts.slice(0, Math.ceil(shortcuts.length / 2));
  const right = shortcuts.slice(Math.ceil(shortcuts.length / 2));
  const colWidth = Math.floor((width - 2) / 2);
  return /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)(Box_default, { flexDirection: "column", children: [
    /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(Box_default, { marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(Text, { color: theme.text.primary, children: t(
      "Qwen Code understands your codebase, makes edits with your permission, and executes commands right from your terminal."
    ) }) }),
    /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(Text, { bold: true, color: theme.text.primary, children: t("Shortcuts") }),
    /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)(Box_default, { flexDirection: "row", gap: 2, children: [
      /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(Box_default, { flexDirection: "column", width: colWidth, children: left.map(([key, desc]) => /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
        ShortcutRow,
        {
          shortcutKey: key,
          desc,
          width: colWidth
        },
        key
      )) }),
      /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(Box_default, { flexDirection: "column", width: colWidth, children: right.map(([key, desc]) => /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
        ShortcutRow,
        {
          shortcutKey: key,
          desc,
          width: colWidth
        },
        key
      )) })
    ] })
  ] });
}, "GeneralHelp");
var ShortcutRow = /* @__PURE__ */ __name(({ shortcutKey, desc, width }) => /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)(Box_default, { flexDirection: "row", width, children: [
  /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(Box_default, { width: KEY_COL_WIDTH, flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(Text, { color: theme.text.accent, children: shortcutKey }) }),
  /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(Text, { color: theme.text.primary, wrap: "truncate", children: truncateText2(desc, width - KEY_COL_WIDTH - 1) })
] }), "ShortcutRow");
var CommandsHelp = /* @__PURE__ */ __name(({ commands, width, customOnly, isInteractive }) => {
  const groups = (0, import_react27.useMemo)(
    () => groupCommands(commands, customOnly),
    [commands, customOnly]
  );
  const lines = (0, import_react27.useMemo)(
    () => renderCommandLines(groups, width),
    [groups, width]
  );
  const maxScroll = Math.max(0, lines.length - COMMAND_LIST_VISIBLE_LINES);
  const [scrollOffset, setScrollOffset] = (0, import_react27.useState)(0);
  (0, import_react27.useEffect)(() => {
    setScrollOffset(0);
  }, [customOnly, commands]);
  (0, import_react27.useEffect)(() => {
    setScrollOffset((offset) => Math.min(offset, maxScroll));
  }, [maxScroll]);
  useKeypress(
    (key) => {
      if (key.name === "up") {
        setScrollOffset((offset) => Math.max(0, offset - 1));
      } else if (key.name === "down") {
        setScrollOffset((offset) => Math.min(maxScroll, offset + 1));
      } else if (key.name === "pageup") {
        setScrollOffset(
          (offset) => Math.max(0, offset - COMMAND_LIST_VISIBLE_LINES)
        );
      } else if (key.name === "pagedown") {
        setScrollOffset(
          (offset) => Math.min(maxScroll, offset + COMMAND_LIST_VISIBLE_LINES)
        );
      }
    },
    { isActive: isInteractive }
  );
  if (groups.length === 0) {
    return /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(Text, { color: theme.text.secondary, children: customOnly ? t("No custom commands are currently available.") : t("No commands are currently available.") });
  }
  const visibleLines = lines.slice(
    scrollOffset,
    scrollOffset + COMMAND_LIST_VISIBLE_LINES
  );
  return /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)(Box_default, { flexDirection: "column", children: [
    /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(Box_default, { marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(Text, { color: theme.text.primary, children: customOnly ? t("Browse custom, skill, plugin, and MCP commands:") : t("Browse built-in commands:") }) }),
    /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(Box_default, { flexDirection: "column", height: COMMAND_LIST_VISIBLE_LINES, children: visibleLines.map((line, index) => {
      const stableKey = line.type === "blank" ? `blank:${index}` : `${line.type}:${line.text}:${index}`;
      return /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(CommandLine, { line }, stableKey);
    }) }),
    maxScroll > 0 && (() => {
      const totalCommands = lines.filter(
        (l) => l.type === "signature"
      ).length;
      const visibleSignatures = visibleLines.filter(
        (l) => l.type === "signature"
      );
      const firstCmd = visibleSignatures.length > 0 ? visibleSignatures[0].commandIndex + 1 : 0;
      const lastCmd = visibleSignatures.length > 0 ? visibleSignatures[visibleSignatures.length - 1].commandIndex + 1 : 0;
      const range = firstCmd === lastCmd ? `${firstCmd}` : `${firstCmd}-${lastCmd}`;
      return /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)(Text, { color: theme.text.secondary, children: [
        t("Use \u2191/\u2193 to scroll"),
        " ",
        `(${range}/${totalCommands})`
      ] }) });
    })()
  ] });
}, "CommandsHelp");
var CommandLine = /* @__PURE__ */ __name(({ line }) => {
  switch (line.type) {
    case "group":
      return /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)(Text, { bold: true, color: theme.text.primary, children: [
        line.text,
        " ",
        /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(Text, { color: theme.text.secondary, children: `(${line.count})` })
      ] });
    case "signature":
      return /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)(Box_default, { flexDirection: "row", children: [
        /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)(Text, { color: theme.text.accent, children: [
          " ",
          line.text
        ] }),
        line.meta && /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)(Text, { color: theme.text.secondary, children: [
          " ",
          line.meta
        ] })
      ] });
    case "description":
      return /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(Box_default, { paddingLeft: 4, children: /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(Text, { color: theme.text.primary, wrap: "truncate", children: line.text }) });
    case "subcommands":
      return /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(Box_default, { paddingLeft: 4, children: /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(Text, { color: theme.text.secondary, wrap: "truncate", children: line.text }) });
    case "blank":
      return /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(Text, { children: " " });
    default:
      return null;
  }
}, "CommandLine");
function renderCommandLines(groups, width) {
  const lines = [];
  let commandIndex = 0;
  groups.forEach((group, groupIndex) => {
    lines.push({
      type: "group",
      text: group.title,
      count: group.commands.length
    });
    group.commands.forEach((cmd) => {
      const sigLine = getCommandSignatureLine(cmd, width);
      lines.push({ ...sigLine, commandIndex: commandIndex++ });
      const descriptionLine = getCommandDescriptionLine(cmd, width);
      if (descriptionLine) {
        lines.push(descriptionLine);
      }
      const subcommandsLine = getCommandSubcommandsLine(cmd, width);
      if (subcommandsLine) {
        lines.push(subcommandsLine);
      }
    });
    if (groupIndex < groups.length - 1) {
      lines.push({ type: "blank" });
    }
  });
  return lines;
}
__name(renderCommandLines, "renderCommandLines");
function getCommandSignatureLine(command, width) {
  const badge = getCommandSourceBadge(command);
  const name = getCommandDisplayName(command, {
    prefix: "/",
    includeAliases: false
  });
  const signature = [name, command.argumentHint].filter(Boolean).join(" ");
  const meta = [
    badge,
    formatSupportedModes(command),
    command.modelInvocable ? "[model]" : void 0
  ].filter(Boolean).join(" ");
  return {
    type: "signature",
    text: truncateText2(signature, Math.floor(width * 0.42)),
    meta,
    commandIndex: -1
    // assigned by renderCommandLines
  };
}
__name(getCommandSignatureLine, "getCommandSignatureLine");
function getCommandDescriptionLine(command, width) {
  if (!command.description) {
    return null;
  }
  return {
    type: "description",
    text: truncateText2(command.description, Math.max(20, width - 4))
  };
}
__name(getCommandDescriptionLine, "getCommandDescriptionLine");
function getCommandSubcommandsLine(command, width) {
  const subcommands = getCommandSubcommandNames(command);
  if (subcommands.length === 0) {
    return null;
  }
  const descWidth = Math.max(20, width - 4);
  return {
    type: "subcommands",
    text: `${t("subcommands:")} ${truncateText2(subcommands.join(", "), descWidth - 13)}`
  };
}
__name(getCommandSubcommandsLine, "getCommandSubcommandsLine");
function groupCommands(commands, customOnly) {
  const groups = /* @__PURE__ */ new Map();
  commands.filter((cmd) => cmd.description && !cmd.hidden).forEach((cmd) => {
    const group = getCommandSourceGroup(cmd);
    if (customOnly ? group.key === "built-in" : group.key !== "built-in") {
      return;
    }
    const existing = groups.get(group.key);
    if (existing) {
      existing.commands.push(cmd);
    } else {
      groups.set(group.key, {
        key: group.key,
        title: group.title,
        order: group.order,
        commands: [cmd]
      });
    }
  });
  return Array.from(groups.values()).sort((a, b) => a.order - b.order).map((group) => ({
    ...group,
    commands: group.commands.sort((a, b) => a.name.localeCompare(b.name))
  }));
}
__name(groupCommands, "groupCommands");
function truncateText2(text, maxLength) {
  if (maxLength <= 1 || text.length <= maxLength) return text;
  return `${text.slice(0, maxLength - 1)}\u2026`;
}
__name(truncateText2, "truncateText");

// packages/cli/src/ui/components/views/ExtensionsList.tsx
init_esbuild_shims();

// packages/cli/src/ui/contexts/UIStateContext.tsx
init_esbuild_shims();
var import_react34 = __toESM(require_react(), 1);

// packages/cli/src/ui/hooks/useHistoryManager.ts
init_esbuild_shims();
var import_react28 = __toESM(require_react(), 1);
import process2 from "node:process";
var debugLogger6 = createDebugLogger("HISTORY_MANAGER");
var UI_COMPACT_CLEARED_MESSAGE = "[Old tool result content cleared]";
var UI_COMPACT_KEEP_RECENT = 20;
function useHistory() {
  const [history, setHistory] = (0, import_react28.useState)([]);
  const messageIdCounterRef = (0, import_react28.useRef)(0);
  const getNextMessageId = (0, import_react28.useCallback)((baseTimestamp) => {
    messageIdCounterRef.current += 1;
    return baseTimestamp + messageIdCounterRef.current;
  }, []);
  const loadHistory = (0, import_react28.useCallback)((newHistory) => {
    setHistory(newHistory);
  }, []);
  const addItem = (0, import_react28.useCallback)(
    (itemData, baseTimestamp) => {
      const id = getNextMessageId(baseTimestamp);
      const newItem = { ...itemData, id };
      setHistory((prevHistory) => {
        if (prevHistory.length > 0) {
          const lastItem = prevHistory[prevHistory.length - 1];
          if (lastItem.type === "user" && newItem.type === "user" && lastItem.text === newItem.text) {
            return prevHistory;
          }
        }
        const newHistory = [...prevHistory, newItem];
        if (debugLogger6.isEnabled()) {
          const textSize = newItem.text?.length ?? 0;
          debugLogger6.debug(
            `[ADD_ITEM] type=${newItem.type}, textSize=${textSize}, historyLength=${newHistory.length}`
          );
        }
        return newHistory;
      });
      return id;
    },
    [getNextMessageId]
  );
  const updateItem = (0, import_react28.useCallback)(
    (id, updates) => {
      setHistory((prevHistory) => {
        let updated = false;
        const nextHistory = prevHistory.map((item) => {
          if (item.id === id) {
            updated = true;
            const newUpdates = typeof updates === "function" ? updates(item) : updates;
            return { ...item, ...newUpdates };
          }
          return item;
        });
        if (!updated) {
          debugLogger6.debug(
            `Skipped history update; item ${id} was not found.`
          );
          return prevHistory;
        }
        return nextHistory;
      });
    },
    []
  );
  const clearItems = (0, import_react28.useCallback)(() => {
    if (debugLogger6.isEnabled()) {
      debugLogger6.debug(
        `[CLEAR_HISTORY] Clearing history, memory before=${(process2.memoryUsage().heapUsed / 1024 / 1024).toFixed(1)}MB`
      );
    }
    setHistory([]);
    messageIdCounterRef.current = 0;
  }, []);
  const truncateToItem = (0, import_react28.useCallback)((itemId) => {
    setHistory((prev) => {
      const index = prev.findIndex((h) => h.id === itemId);
      return index === -1 ? prev : prev.slice(0, index);
    });
  }, []);
  const compactOldItems = (0, import_react28.useCallback)(() => {
    setHistory((prev) => {
      if (prev.length === 0) return prev;
      let thoughtRemoved = 0;
      let toolGroupsCompacted = 0;
      let totalThoughts = 0;
      let totalToolGroupsWithOutput = 0;
      for (const item of prev) {
        if (item.type === "gemini_thought" || item.type === "gemini_thought_content") {
          totalThoughts++;
        } else if (item.type === "tool_group" && item.tools.some(
          (t2) => t2.resultDisplay != null && t2.resultDisplay !== UI_COMPACT_CLEARED_MESSAGE
        )) {
          totalToolGroupsWithOutput++;
        }
      }
      const thoughtsToDrop = Math.max(
        0,
        totalThoughts - UI_COMPACT_KEEP_RECENT
      );
      const toolGroupsToCompact = Math.max(
        0,
        totalToolGroupsWithOutput - UI_COMPACT_KEEP_RECENT
      );
      let thoughtsDropped = 0;
      let toolGroupsSeen = 0;
      const next = prev.filter((item) => {
        if (item.type === "gemini_thought" || item.type === "gemini_thought_content") {
          if (thoughtsDropped < thoughtsToDrop) {
            thoughtsDropped++;
            thoughtRemoved++;
            return false;
          }
        }
        return true;
      }).map((item) => {
        if (item.type !== "tool_group") return item;
        const hasOldOutput = item.tools.some(
          (t2) => t2.resultDisplay != null && t2.resultDisplay !== UI_COMPACT_CLEARED_MESSAGE
        );
        if (!hasOldOutput) return item;
        toolGroupsSeen++;
        if (toolGroupsSeen > toolGroupsToCompact) return item;
        toolGroupsCompacted++;
        return {
          ...item,
          tools: item.tools.map((t2) => {
            if (t2.resultDisplay != null && t2.resultDisplay !== UI_COMPACT_CLEARED_MESSAGE) {
              return { ...t2, resultDisplay: UI_COMPACT_CLEARED_MESSAGE };
            }
            return t2;
          })
        };
      });
      if (thoughtRemoved > 0 || toolGroupsCompacted > 0) {
        if (debugLogger6.isEnabled()) {
          debugLogger6.debug(
            `[COMPACT_UI_HISTORY] removed ${thoughtRemoved} thought item(s), compacted ${toolGroupsCompacted} tool group(s), historyLength ${prev.length} -> ${next.length}, memory=${(process2.memoryUsage().heapUsed / 1024 / 1024).toFixed(1)}MB`
          );
        }
      }
      return thoughtRemoved > 0 || toolGroupsCompacted > 0 ? next : prev;
    });
  }, []);
  return (0, import_react28.useMemo)(
    () => ({
      history,
      addItem,
      updateItem,
      clearItems,
      loadHistory,
      truncateToItem,
      compactOldItems
    }),
    [
      history,
      addItem,
      updateItem,
      clearItems,
      loadHistory,
      truncateToItem,
      compactOldItems
    ]
  );
}
__name(useHistory, "useHistory");

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

// packages/cli/src/ui/IdeIntegrationNudge.tsx
init_esbuild_shims();
var import_jsx_runtime34 = __toESM(require_jsx_runtime(), 1);
function IdeIntegrationNudge({
  ide,
  onComplete
}) {
  useKeypress(
    (key) => {
      if (key.name === "escape") {
        onComplete({
          userSelection: "no",
          isExtensionPreInstalled: false
        });
      }
    },
    { isActive: true }
  );
  const { displayName: ideName } = ide;
  const isInSandbox = !!process.env["SANDBOX"];
  const isExtensionPreInstalled = !!process.env["QWEN_CODE_IDE_SERVER_PORT"] && !!process.env["QWEN_CODE_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 = isInSandbox ? `Note: In sandbox environments, IDE integration requires manual setup on the host system. If you select Yes, you'll receive instructions on how to set this up.` : isExtensionPreInstalled ? `If you select Yes, the CLI will connect to your ${ideName ?? "editor"} and have access to your open files and display diffs directly.` : `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_runtime34.jsxs)(
    Box_default,
    {
      flexDirection: "column",
      borderStyle: "round",
      borderColor: theme.status.warning,
      padding: 1,
      width: "100%",
      marginLeft: 1,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime34.jsxs)(Box_default, { marginBottom: 1, flexDirection: "column", children: [
          /* @__PURE__ */ (0, import_jsx_runtime34.jsxs)(Text, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(Text, { color: theme.status.warning, children: "> " }),
            `Do you want to connect ${ideName ?? "your editor"} to Qwen Code?`
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(Text, { color: theme.text.secondary, children: installText })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(RadioButtonSelect, { items: OPTIONS, onSelect: onComplete })
      ]
    }
  );
}
__name(IdeIntegrationNudge, "IdeIntegrationNudge");

// packages/cli/src/ui/CommandFormatMigrationNudge.tsx
init_esbuild_shims();
var import_jsx_runtime35 = __toESM(require_jsx_runtime(), 1);
function CommandFormatMigrationNudge({
  tomlFiles,
  onComplete
}) {
  useKeypress(
    (key) => {
      if (key.name === "escape") {
        onComplete({
          userSelection: "no"
        });
      }
    },
    { isActive: true }
  );
  const OPTIONS = [
    {
      label: t("Yes"),
      value: {
        userSelection: "yes"
      },
      key: "Yes"
    },
    {
      label: t("No (esc)"),
      value: {
        userSelection: "no"
      },
      key: "No (esc)"
    }
  ];
  const count = tomlFiles.length;
  const fileList = count <= 3 ? tomlFiles.map((f) => `  \u2022 ${f}`).join("\n") : `  \u2022 ${tomlFiles.slice(0, 2).join("\n  \u2022 ")}
  \u2022 ${t("... and {{count}} more", { count: String(count - 2) })}`;
  return /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(
    Box_default,
    {
      flexDirection: "column",
      borderStyle: "round",
      borderColor: theme.status.warning,
      padding: 1,
      width: "100%",
      marginLeft: 1,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Box_default, { marginBottom: 1, flexDirection: "column", children: [
          /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(Text, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Text, { color: theme.status.warning, children: "\u26A0  " }),
            /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Text, { bold: true, children: t("Command Format Migration") })
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Text, { color: theme.text.secondary, children: count > 1 ? t("Found {{count}} TOML command files:", { count: String(count) }) : t("Found {{count}} TOML command file:", { count: String(count) }) }),
          /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Text, { color: theme.text.secondary, children: fileList }),
          /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Text, { children: "" }),
          /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Text, { color: theme.text.secondary, children: t(
            "The TOML format is deprecated. Would you like to migrate them to Markdown format?"
          ) }),
          /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Text, { color: theme.text.secondary, children: t("(Backups will be created and original files will be preserved)") })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(RadioButtonSelect, { items: OPTIONS, onSelect: onComplete })
      ]
    }
  );
}
__name(CommandFormatMigrationNudge, "CommandFormatMigrationNudge");

// packages/cli/src/ui/components/FolderTrustDialog.tsx
init_esbuild_shims();
var import_react29 = __toESM(require_react(), 1);
import * as process3 from "node:process";
import * as path2 from "node:path";
var import_jsx_runtime36 = __toESM(require_jsx_runtime(), 1);
var FolderTrustDialog = /* @__PURE__ */ __name(({
  onSelect,
  isRestarting
}) => {
  (0, import_react29.useEffect)(() => {
    const doRelaunch = /* @__PURE__ */ __name(async () => {
      if (isRestarting) {
        setTimeout(async () => {
          await relaunchApp();
        }, 250);
      }
    }, "doRelaunch");
    doRelaunch();
  }, [isRestarting]);
  useKeypress(
    (key) => {
      if (key.name === "escape") {
        onSelect("do_not_trust" /* DO_NOT_TRUST */);
      }
    },
    { isActive: !isRestarting }
  );
  const dirName = path2.basename(process3.cwd());
  const parentFolder = path2.basename(path2.dirname(process3.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 (esc)",
      value: "do_not_trust" /* DO_NOT_TRUST */,
      key: "Don't trust (esc)"
    }
  ];
  return /* @__PURE__ */ (0, import_jsx_runtime36.jsxs)(Box_default, { flexDirection: "column", children: [
    /* @__PURE__ */ (0, import_jsx_runtime36.jsxs)(
      Box_default,
      {
        flexDirection: "column",
        borderStyle: "round",
        borderColor: theme.status.warning,
        padding: 1,
        width: "100%",
        marginLeft: 1,
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime36.jsxs)(Box_default, { flexDirection: "column", marginBottom: 1, children: [
            /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(Text, { bold: true, color: theme.text.primary, children: "Do you trust this folder?" }),
            /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(Text, { color: theme.text.primary, children: "Trusting a folder allows Qwen Code to execute commands it suggests. This is a security feature to prevent accidental execution in untrusted directories." })
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(
            RadioButtonSelect,
            {
              items: options,
              onSelect,
              isFocused: !isRestarting
            }
          )
        ]
      }
    ),
    isRestarting && /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(Box_default, { marginLeft: 1, marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(Text, { color: theme.status.warning, children: "Qwen Code is restarting to apply the trust changes..." }) })
  ] });
}, "FolderTrustDialog");

// packages/cli/src/ui/components/mcp/MCPServerApprovalDialog.tsx
init_esbuild_shims();
var import_jsx_runtime37 = __toESM(require_jsx_runtime(), 1);
var MCPServerApprovalDialog = /* @__PURE__ */ __name(({ serverName, summary, source, pendingServers, remaining, onSelect }) => {
  useKeypress(
    (key) => {
      if (key.name === "escape") {
        onSelect("reject" /* REJECT */);
      }
    },
    { isActive: true }
  );
  const options = [
    {
      label: "Approve this server",
      value: "approve" /* APPROVE */,
      key: "approve"
    },
    {
      label: "Approve all pending servers in this workspace",
      value: "approve_all" /* APPROVE_ALL */,
      key: "approve_all"
    },
    {
      label: "Reject (esc)",
      value: "reject" /* REJECT */,
      key: "reject"
    }
  ];
  return /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(Box_default, { flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime37.jsxs)(
    Box_default,
    {
      flexDirection: "column",
      borderStyle: "round",
      borderColor: theme.status.warning,
      padding: 1,
      width: "100%",
      marginLeft: 1,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime37.jsxs)(Box_default, { flexDirection: "column", marginBottom: 1, children: [
          /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(Text, { bold: true, color: theme.text.primary, children: `Untrusted MCP server in ${source}` }),
          /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(Text, { color: theme.text.primary, children: `This workspace declares an MCP server. Approving lets Qwen Code start it and run its tools. Approval is bound to this exact configuration \u2014 if ${source} changes, you will be asked again.` })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime37.jsxs)(Box_default, { flexDirection: "column", marginBottom: 1, children: [
          /* @__PURE__ */ (0, import_jsx_runtime37.jsxs)(Text, { color: theme.text.primary, children: [
            /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(Text, { bold: true, children: serverName }),
            `  ${summary}`
          ] }),
          remaining > 0 && /* @__PURE__ */ (0, import_jsx_runtime37.jsxs)(Box_default, { flexDirection: "column", marginTop: 1, children: [
            /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(Text, { color: theme.text.secondary, children: "Approve all will trust these servers:" }),
            pendingServers.map((server) => /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(Text, { color: theme.text.secondary, children: `  ${server.name}  ${server.summary}` }, server.name))
          ] })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime37.jsx)(RadioButtonSelect, { items: options, onSelect, isFocused: true })
      ]
    }
  ) });
}, "MCPServerApprovalDialog");

// packages/cli/src/ui/hooks/useArenaCommand.ts
init_esbuild_shims();
var import_react30 = __toESM(require_react(), 1);
function useArenaCommand() {
  const [activeArenaDialog, setActiveArenaDialog] = (0, import_react30.useState)(null);
  const openArenaDialog = (0, import_react30.useCallback)(
    (type) => {
      setActiveArenaDialog(type);
    },
    []
  );
  const closeArenaDialog = (0, import_react30.useCallback)(() => {
    setActiveArenaDialog(null);
  }, []);
  return {
    activeArenaDialog,
    openArenaDialog,
    closeArenaDialog
  };
}
__name(useArenaCommand, "useArenaCommand");

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

// packages/cli/src/ui/hooks/useIdeTrustListener.ts
init_esbuild_shims();
var import_react32 = __toESM(require_react(), 1);
function useIdeTrustListener() {
  const settings = useSettings();
  const [connectionStatus, setConnectionStatus] = (0, import_react32.useState)(
    "disconnected" /* Disconnected */
  );
  const previousTrust = (0, import_react32.useRef)(void 0);
  const [restartReason, setRestartReason] = (0, import_react32.useState)("NONE");
  const [needsRestart, setNeedsRestart] = (0, import_react32.useState)(false);
  const subscribe = (0, import_react32.useCallback)((onStoreChange) => {
    const handleStatusChange = /* @__PURE__ */ __name((state) => {
      setConnectionStatus(state.status);
      setRestartReason("CONNECTION_CHANGE");
      onStoreChange();
    }, "handleStatusChange");
    const handleTrustChange = /* @__PURE__ */ __name(() => {
      setRestartReason("TRUST_CHANGE");
      onStoreChange();
    }, "handleTrustChange");
    (async () => {
      const ideClient = await IdeClient.getInstance();
      ideClient.addTrustChangeListener(handleTrustChange);
      ideClient.addStatusChangeListener(handleStatusChange);
      setConnectionStatus(ideClient.getConnectionStatus().status);
    })();
    return () => {
      (async () => {
        const ideClient = await IdeClient.getInstance();
        ideClient.removeTrustChangeListener(handleTrustChange);
        ideClient.removeStatusChangeListener(handleStatusChange);
      })();
    };
  }, []);
  const getSnapshot = /* @__PURE__ */ __name(() => {
    if (connectionStatus !== "connected" /* Connected */) {
      return void 0;
    }
    return ideContextStore.get()?.workspaceState?.isTrusted;
  }, "getSnapshot");
  const isIdeTrusted = (0, import_react32.useSyncExternalStore)(subscribe, getSnapshot);
  (0, import_react32.useEffect)(() => {
    const currentTrust = isWorkspaceTrusted(settings.merged).isTrusted;
    if (previousTrust.current !== void 0 && previousTrust.current !== currentTrust) {
      setNeedsRestart(true);
    }
    previousTrust.current = currentTrust;
  }, [isIdeTrusted, settings.merged]);
  return { isIdeTrusted, needsRestart, restartReason };
}
__name(useIdeTrustListener, "useIdeTrustListener");

// packages/cli/src/ui/hooks/useProviderUpdates.ts
init_esbuild_shims();
var import_react33 = __toESM(require_react(), 1);
function getProviderMetadata(settings, metadataKey) {
  const mergedSettings = settings.merged;
  const ns = mergedSettings[PROVIDER_METADATA_NS];
  if (!ns) return {};
  const metadata = ns[metadataKey];
  return metadata && typeof metadata === "object" ? metadata : {};
}
__name(getProviderMetadata, "getProviderMetadata");
var LEGACY_KEY_MAP = {
  codingPlan: "coding-plan",
  tokenPlan: "token-plan"
};
function migrateProviderMetadata(settings) {
  const mergedSettings = settings.merged;
  const persistScope = getPersistScopeForModelSelection(settings);
  let migrated = false;
  const migrateKey = /* @__PURE__ */ __name((oldKey, newKey) => {
    const data = mergedSettings[oldKey];
    if (!data || typeof data !== "object") return;
    const entries = data;
    for (const [field, value] of Object.entries(entries)) {
      if (value !== void 0) {
        settings.setValue(
          persistScope,
          `${PROVIDER_METADATA_NS}.${newKey}.${field}`,
          value
        );
      }
    }
    settings.setValue(persistScope, oldKey, void 0);
    migrated = true;
  }, "migrateKey");
  for (const [oldKey, newKey] of Object.entries(LEGACY_KEY_MAP)) {
    migrateKey(oldKey, newKey);
  }
  for (const provider of ALL_PROVIDERS) {
    const key = resolveMetadataKey(provider);
    if (!key) continue;
    if (mergedSettings[key] && typeof mergedSettings[key] === "object") {
      migrateKey(key, key);
    }
  }
  if (migrated) {
    console.log(
      "[info] Migrated provider metadata to providerMetadata namespace."
    );
  }
}
__name(migrateProviderMetadata, "migrateProviderMetadata");
function computeModelDiff(existingModelIds, newModelIds, currentModel) {
  const existingSet = new Set(existingModelIds);
  const newSet = new Set(newModelIds);
  const added = newModelIds.filter((id) => !existingSet.has(id));
  const removed = existingModelIds.filter((id) => !newSet.has(id));
  const currentModelAffected = removed.includes(currentModel);
  const fallbackModel = currentModelAffected ? newModelIds[0] : void 0;
  return { added, removed, currentModelAffected, fallbackModel };
}
__name(computeModelDiff, "computeModelDiff");
function readInstalledOwnedIds(settings, provider) {
  const protocol = provider.protocol;
  if (!protocol) return [];
  const mergedSettings = settings.merged;
  const modelProviders = mergedSettings["modelProviders"];
  if (!modelProviders) return [];
  const allModels = modelProviders[protocol] ?? [];
  const ownsFn = resolveOwnsModel(provider);
  return ownsFn ? allModels.filter(ownsFn).map((m) => m.id) : allModels.map((m) => m.id);
}
__name(readInstalledOwnedIds, "readInstalledOwnedIds");
function getInstalledOwnedModelIds(settings, provider) {
  const builtinIds = new Set(getDefaultModelIds(provider));
  return readInstalledOwnedIds(settings, provider).filter(
    (id) => builtinIds.has(id)
  );
}
__name(getInstalledOwnedModelIds, "getInstalledOwnedModelIds");
function findAllPendingUpdates(settings, currentModel) {
  const results = [];
  for (const provider of ALL_PROVIDERS) {
    const metadataKey = resolveMetadataKey(provider);
    if (!metadataKey) continue;
    const metadata = getProviderMetadata(settings, metadataKey);
    if (!metadata.version) continue;
    const baseUrl = metadata.baseUrl || resolveBaseUrl(provider);
    const currentTemplate = buildProviderTemplate(provider, baseUrl);
    const currentVersion = computeModelListVersion(currentTemplate);
    if (metadata.version === currentVersion) continue;
    if (metadata.ignoredVersion === currentVersion) continue;
    const existingModelIds = getInstalledOwnedModelIds(settings, provider);
    const newModelIds = provider.models.map((s) => s.id);
    const diff = computeModelDiff(existingModelIds, newModelIds, currentModel);
    results.push({ provider, metadataKey, baseUrl, currentVersion, diff });
  }
  return results;
}
__name(findAllPendingUpdates, "findAllPendingUpdates");
function useProviderUpdates(settings, config, addItem) {
  const [updateRequest, setUpdateRequest] = (0, import_react33.useState)();
  const migrated = (0, import_react33.useRef)(false);
  const executeUpdate = (0, import_react33.useCallback)(
    async (providerCfg, baseUrl) => {
      try {
        const resolved = resolveBaseUrl(providerCfg, baseUrl);
        const defaultIds = getDefaultModelIds(providerCfg);
        const customIds = readInstalledOwnedIds(settings, providerCfg).filter(
          (id) => !defaultIds.includes(id)
        );
        const installPlan = buildInstallPlan(providerCfg, {
          baseUrl: resolved,
          apiKey: "",
          modelIds: [...defaultIds, ...customIds]
        });
        delete installPlan.env;
        const previousModel = config.getModel();
        const newConfigs = installPlan.modelProviders?.[0]?.models ?? [];
        const previousModelStillAvailable = newConfigs.some(
          (cfg) => cfg.id === previousModel
        );
        if (previousModelStillAvailable) {
          delete installPlan.modelSelection;
        }
        await applyProviderInstallPlan(installPlan, {
          settings: createLoadedSettingsAdapter(settings),
          reloadModelProviders: /* @__PURE__ */ __name((mp) => config.reloadModelProvidersConfig(mp), "reloadModelProviders"),
          syncAuthState: /* @__PURE__ */ __name((authType, modelId, baseUrl2) => config.getModelsConfig().syncAfterAuthRefresh(authType, modelId, baseUrl2), "syncAuthState"),
          refreshAuth: /* @__PURE__ */ __name((authType) => config.refreshAuth(authType), "refreshAuth"),
          doRefreshAuth: false
        });
        const activeModel = config.getModel();
        const displayName = t(providerCfg.label);
        if (previousModelStillAvailable && activeModel === previousModel) {
          addItem(
            {
              type: "info",
              text: t("{{plan}} configuration updated successfully.", {
                plan: displayName
              })
            },
            Date.now()
          );
        } else {
          addItem(
            {
              type: "info",
              text: t(
                '{{plan}} configuration updated successfully. Model switched to "{{model}}".',
                { plan: displayName, model: activeModel }
              )
            },
            Date.now()
          );
        }
        addItem(
          {
            type: "info",
            text: t(
              "Tip: Use /model to switch between available {{plan}} models.",
              { plan: displayName }
            )
          },
          Date.now()
        );
        return true;
      } catch (error) {
        const errorMessage = error instanceof Error ? error.message : String(error);
        addItem(
          {
            type: "error",
            text: t("Failed to update provider configuration: {{message}}", {
              message: errorMessage
            })
          },
          Date.now()
        );
        return false;
      }
    },
    [settings, config, addItem]
  );
  const checkForUpdates = (0, import_react33.useCallback)(() => {
    if (!migrated.current) {
      migrated.current = true;
      migrateProviderMetadata(settings);
    }
    const currentModel = config.getModel();
    const pendingList = findAllPendingUpdates(settings, currentModel);
    if (pendingList.length === 0) return;
    const entries = pendingList.map((p) => ({
      providerLabel: t(p.provider.label),
      diff: p.diff
    }));
    setUpdateRequest({
      entries,
      onConfirm: /* @__PURE__ */ __name(async (choice) => {
        setUpdateRequest(void 0);
        if (choice === "update") {
          for (const p of pendingList) {
            await executeUpdate(p.provider, p.baseUrl);
          }
        } else if (choice === "skip") {
          const persistScope = getPersistScopeForModelSelection(settings);
          for (const p of pendingList) {
            settings.setValue(
              persistScope,
              `${PROVIDER_METADATA_NS}.${p.metadataKey}.ignoredVersion`,
              p.currentVersion
            );
          }
        }
      }, "onConfirm")
    });
  }, [settings, config, executeUpdate]);
  (0, import_react33.useEffect)(() => {
    checkForUpdates();
  }, [checkForUpdates]);
  const dismissProviderUpdate = (0, import_react33.useCallback)(() => {
    setUpdateRequest(void 0);
  }, []);
  return {
    providerUpdateRequest: updateRequest,
    dismissProviderUpdate
  };
}
__name(useProviderUpdates, "useProviderUpdates");

// packages/cli/src/ui/contexts/UIStateContext.tsx
var UIStateContext = (0, import_react34.createContext)(null);
var useUIState = /* @__PURE__ */ __name(() => {
  const context = (0, import_react34.useContext)(UIStateContext);
  if (!context) {
    throw new Error("useUIState must be used within a UIStateProvider");
  }
  return context;
}, "useUIState");

// packages/cli/src/ui/state/extensions.ts
init_esbuild_shims();
var initialExtensionUpdatesState = {
  extensionStatuses: /* @__PURE__ */ new Map(),
  batchChecksInProgress: 0
};
function extensionUpdatesReducer(state, action) {
  switch (action.type) {
    case "SET_STATE": {
      const existing = state.extensionStatuses.get(action.payload.name);
      if (existing?.status === action.payload.state) {
        return state;
      }
      const newStatuses = new Map(state.extensionStatuses);
      newStatuses.set(action.payload.name, {
        status: action.payload.state,
        processed: false
      });
      return { ...state, extensionStatuses: newStatuses };
    }
    case "SET_PROCESSED": {
      const existing = state.extensionStatuses.get(action.payload.name);
      if (!existing || existing.processed === action.payload.processed) {
        return state;
      }
      const newStatuses = new Map(state.extensionStatuses);
      newStatuses.set(action.payload.name, {
        ...existing,
        processed: action.payload.processed
      });
      return { ...state, extensionStatuses: newStatuses };
    }
    case "BATCH_CHECK_START":
      return {
        ...state,
        batchChecksInProgress: state.batchChecksInProgress + 1
      };
    case "BATCH_CHECK_END":
      return {
        ...state,
        batchChecksInProgress: state.batchChecksInProgress - 1
      };
    default:
      checkExhaustive(action);
  }
}
__name(extensionUpdatesReducer, "extensionUpdatesReducer");

// packages/cli/src/ui/components/views/ExtensionsList.tsx
var import_jsx_runtime38 = __toESM(require_jsx_runtime(), 1);
var debugLogger7 = createDebugLogger("EXTENSIONS_LIST");
var ExtensionsList = /* @__PURE__ */ __name(() => {
  const { extensionsUpdateState, commandContext } = useUIState();
  const extensions = commandContext.services.config?.getExtensions() || [];
  if (extensions.length === 0) {
    return /* @__PURE__ */ (0, import_jsx_runtime38.jsx)(Text, { children: "No extensions installed." });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime38.jsxs)(Box_default, { flexDirection: "column", marginTop: 1, marginBottom: 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime38.jsx)(Text, { children: "Installed extensions:" }),
    /* @__PURE__ */ (0, import_jsx_runtime38.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;
        default:
          debugLogger7.error(`Unhandled ExtensionUpdateState ${state}`);
          break;
      }
      return /* @__PURE__ */ (0, import_jsx_runtime38.jsxs)(Box_default, { flexDirection: "column", marginBottom: 1, children: [
        /* @__PURE__ */ (0, import_jsx_runtime38.jsxs)(Text, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime38.jsx)(Text, { color: "cyan", children: `${getExtensionDisplayName(ext, getCurrentLanguage())} (v${ext.version})` }),
          /* @__PURE__ */ (0, import_jsx_runtime38.jsx)(Text, { color: activeColor, children: ` - ${activeString}` }),
          /* @__PURE__ */ (0, import_jsx_runtime38.jsx)(Text, { color: stateColor, children: ` (${stateText})` })
        ] }),
        ext.resolvedSettings && ext.resolvedSettings.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime38.jsxs)(Box_default, { flexDirection: "column", paddingLeft: 2, children: [
          /* @__PURE__ */ (0, import_jsx_runtime38.jsx)(Text, { children: "settings:" }),
          ext.resolvedSettings.map((setting) => /* @__PURE__ */ (0, import_jsx_runtime38.jsxs)(Text, { children: [
            "- ",
            setting.name,
            ": ",
            setting.value
          ] }, setting.name))
        ] })
      ] }, ext.name);
    }) })
  ] });
}, "ExtensionsList");

// packages/cli/src/ui/components/views/SkillsList.tsx
init_esbuild_shims();
var import_jsx_runtime39 = __toESM(require_jsx_runtime(), 1);
var NAME_COLUMN = 24;
function truncate(text, max) {
  if (text.length <= max) return text;
  return `${text.slice(0, Math.max(0, max - 1))}\u2026`;
}
__name(truncate, "truncate");
var SkillsList = /* @__PURE__ */ __name(({ skills }) => /* @__PURE__ */ (0, import_jsx_runtime39.jsxs)(Box_default, { flexDirection: "column", marginBottom: 1, children: [
  /* @__PURE__ */ (0, import_jsx_runtime39.jsx)(Text, { bold: true, color: theme.text.primary, children: t("Available skills:") }),
  /* @__PURE__ */ (0, import_jsx_runtime39.jsx)(Box_default, { height: 1 }),
  skills.length > 0 ? skills.map((skill) => /* @__PURE__ */ (0, import_jsx_runtime39.jsxs)(Box_default, { flexDirection: "row", children: [
    /* @__PURE__ */ (0, import_jsx_runtime39.jsxs)(Text, { color: theme.text.primary, children: [
      "  ",
      "- "
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime39.jsx)(Text, { bold: true, color: theme.text.accent, children: skill.description ? truncate(skill.name, NAME_COLUMN).padEnd(NAME_COLUMN) : skill.name }),
    skill.description && /* @__PURE__ */ (0, import_jsx_runtime39.jsxs)(Text, { color: theme.text.secondary, children: [
      " ",
      truncate(skill.description, 80)
    ] }),
    skill.level && /* @__PURE__ */ (0, import_jsx_runtime39.jsxs)(Text, { color: theme.text.secondary, children: [
      "  ",
      "(",
      levelLabel(skill.level),
      ")"
    ] })
  ] }, skill.name)) : /* @__PURE__ */ (0, import_jsx_runtime39.jsxs)(Text, { color: theme.text.primary, children: [
    " ",
    t("No skills available")
  ] })
] }), "SkillsList");

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

// packages/cli/src/ui/components/views/McpStatus.tsx
init_esbuild_shims();
var import_jsx_runtime41 = __toESM(require_jsx_runtime(), 1);
var McpStatus = /* @__PURE__ */ __name(({
  servers,
  tools,
  prompts,
  blockedServers,
  serverStatus,
  authStatus,
  discoveryInProgress,
  connectingServers,
  showDescriptions,
  showSchema,
  showTips
}) => {
  const serverNames = Object.keys(servers);
  if (serverNames.length === 0 && blockedServers.length === 0) {
    return /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Box_default, { flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Text, { children: t("No MCP servers configured.") }) });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime41.jsxs)(Box_default, { flexDirection: "column", children: [
    discoveryInProgress && /* @__PURE__ */ (0, import_jsx_runtime41.jsxs)(Box_default, { flexDirection: "column", marginBottom: 1, children: [
      /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Text, { color: theme.status.warning, children: t("\u25CC MCP servers are starting up ({{count}} initializing)...", {
        count: String(connectingServers.length)
      }) }),
      /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Text, { color: theme.text.primary, children: t(
        "Note: First startup may take longer. Tool availability will update automatically."
      ) })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Text, { bold: true, children: t("Configured MCP servers:") }),
    /* @__PURE__ */ (0, import_jsx_runtime41.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 originalStatus = serverStatus(serverName);
      const hasCachedItems = serverTools.length > 0 || serverPrompts.length > 0;
      const status = originalStatus === "disconnected" /* DISCONNECTED */ && hasCachedItems ? "connected" /* CONNECTED */ : originalStatus;
      let statusIndicator = "";
      let statusText = "";
      let statusColor = theme.text.primary;
      switch (status) {
        case "connected" /* CONNECTED */:
          statusIndicator = "\u25CF";
          statusText = t("Ready");
          statusColor = theme.status.success;
          break;
        case "connecting" /* CONNECTING */:
          statusIndicator = "\u25D0";
          statusText = t("Starting... (first startup may take longer)");
          statusColor = theme.status.warning;
          break;
        case "disconnected" /* DISCONNECTED */:
        default:
          statusIndicator = "\u25CF";
          statusText = t("Disconnected");
          statusColor = theme.status.error;
          break;
      }
      let serverDisplayName = serverName;
      if (server.extensionName) {
        serverDisplayName += ` ${t("(from {{extensionName}})", {
          extensionName: server.extensionName
        })}`;
      }
      const toolCount = serverTools.length;
      const promptCount = serverPrompts.length;
      const parts = [];
      if (toolCount > 0) {
        parts.push(
          toolCount === 1 ? t("{{count}} tool", { count: String(toolCount) }) : t("{{count}} tools", { count: String(toolCount) })
        );
      }
      if (promptCount > 0) {
        parts.push(
          promptCount === 1 ? t("{{count}} prompt", { count: String(promptCount) }) : t("{{count}} prompts", { count: String(promptCount) })
        );
      }
      const serverAuthStatus = authStatus[serverName];
      let authStatusNode = null;
      if (serverAuthStatus === "authenticated") {
        authStatusNode = /* @__PURE__ */ (0, import_jsx_runtime41.jsxs)(Text, { children: [
          " (",
          t("OAuth"),
          ")"
        ] });
      } else if (serverAuthStatus === "expired") {
        authStatusNode = /* @__PURE__ */ (0, import_jsx_runtime41.jsxs)(Text, { color: theme.status.error, children: [
          " (",
          t("OAuth expired"),
          ")"
        ] });
      } else if (serverAuthStatus === "unauthenticated") {
        authStatusNode = /* @__PURE__ */ (0, import_jsx_runtime41.jsxs)(Text, { color: theme.status.warning, children: [
          " ",
          "(",
          t("OAuth not authenticated"),
          ")"
        ] });
      }
      return /* @__PURE__ */ (0, import_jsx_runtime41.jsxs)(Box_default, { flexDirection: "column", marginBottom: 1, children: [
        /* @__PURE__ */ (0, import_jsx_runtime41.jsxs)(Box_default, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime41.jsxs)(Text, { color: statusColor, children: [
            statusIndicator,
            " "
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Text, { bold: true, children: serverDisplayName }),
          /* @__PURE__ */ (0, import_jsx_runtime41.jsxs)(Text, { children: [
            " - ",
            statusText,
            status === "connected" /* CONNECTED */ && parts.length > 0 && ` (${parts.join(", ")})`
          ] }),
          authStatusNode
        ] }),
        status === "connecting" /* CONNECTING */ && /* @__PURE__ */ (0, import_jsx_runtime41.jsxs)(Text, { children: [
          " (",
          t("tools and prompts will appear when ready"),
          ")"
        ] }),
        status === "disconnected" /* DISCONNECTED */ && toolCount > 0 && /* @__PURE__ */ (0, import_jsx_runtime41.jsxs)(Text, { children: [
          "(",
          t("{{count}} tools cached", { count: String(toolCount) }),
          ")"
        ] }),
        showDescriptions && server?.description && /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Text, { color: theme.text.secondary, children: server.description.trim() }),
        serverTools.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime41.jsxs)(Box_default, { flexDirection: "column", marginLeft: 2, children: [
          /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Text, { color: theme.text.primary, children: t("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_runtime41.jsxs)(Box_default, { flexDirection: "column", children: [
              /* @__PURE__ */ (0, import_jsx_runtime41.jsxs)(Text, { children: [
                "- ",
                /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Text, { color: theme.text.primary, children: tool.name })
              ] }),
              showDescriptions && tool.description && /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Box_default, { marginLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Text, { color: theme.text.secondary, children: tool.description.trim() }) }),
              schemaContent && /* @__PURE__ */ (0, import_jsx_runtime41.jsxs)(Box_default, { flexDirection: "column", marginLeft: 4, children: [
                /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Text, { color: theme.text.secondary, children: t("Parameters:") }),
                /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Text, { color: theme.text.secondary, children: schemaContent })
              ] })
            ] }, tool.name);
          })
        ] }),
        serverPrompts.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime41.jsxs)(Box_default, { flexDirection: "column", marginLeft: 2, children: [
          /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Text, { color: theme.text.primary, children: t("Prompts:") }),
          serverPrompts.map((prompt) => /* @__PURE__ */ (0, import_jsx_runtime41.jsxs)(Box_default, { flexDirection: "column", children: [
            /* @__PURE__ */ (0, import_jsx_runtime41.jsxs)(Text, { children: [
              "- ",
              /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Text, { color: theme.text.primary, children: prompt.name })
            ] }),
            showDescriptions && prompt.description && /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Box_default, { marginLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Text, { color: theme.text.primary, children: prompt.description.trim() }) })
          ] }, prompt.name))
        ] })
      ] }, serverName);
    }),
    blockedServers.map((server) => /* @__PURE__ */ (0, import_jsx_runtime41.jsxs)(Box_default, { marginBottom: 1, children: [
      /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Text, { color: theme.status.error, children: "\u25CF " }),
      /* @__PURE__ */ (0, import_jsx_runtime41.jsxs)(Text, { bold: true, children: [
        server.name,
        server.extensionName ? ` ${t("(from {{extensionName}})", {
          extensionName: server.extensionName
        })}` : ""
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime41.jsxs)(Text, { children: [
        " - ",
        t("Blocked")
      ] })
    ] }, server.name)),
    showTips && /* @__PURE__ */ (0, import_jsx_runtime41.jsxs)(Box_default, { flexDirection: "column", marginTop: 1, children: [
      /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Text, { color: theme.text.accent, children: t("\u2605 Tips:") }),
      /* @__PURE__ */ (0, import_jsx_runtime41.jsxs)(Text, { children: [
        "  ",
        "- ",
        t("Use"),
        " ",
        /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Text, { color: theme.text.accent, children: "/mcp desc" }),
        " ",
        t("to show server and tool descriptions")
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime41.jsxs)(Text, { children: [
        "  ",
        "- ",
        t("Use"),
        " ",
        /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Text, { color: theme.text.accent, children: "/mcp schema" }),
        " ",
        t("to show tool parameter schemas")
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime41.jsxs)(Text, { children: [
        "  ",
        "- ",
        t("Use"),
        " ",
        /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Text, { color: theme.text.accent, children: "/mcp nodesc" }),
        " ",
        t("to hide descriptions")
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime41.jsxs)(Text, { children: [
        "  ",
        "- ",
        t("Use"),
        " ",
        /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Text, { color: theme.text.accent, children: "/mcp" }),
        " ",
        t("to authenticate with OAuth-enabled servers")
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime41.jsxs)(Text, { children: [
        "  ",
        "- ",
        t("Press"),
        " ",
        /* @__PURE__ */ (0, import_jsx_runtime41.jsx)(Text, { color: theme.text.accent, children: "Ctrl+T" }),
        " ",
        t("to toggle tool descriptions on/off")
      ] })
    ] })
  ] });
}, "McpStatus");

// packages/cli/src/ui/components/views/ContextUsage.tsx
init_esbuild_shims();
var import_jsx_runtime42 = __toESM(require_jsx_runtime(), 1);
var FILLED = "\u2588";
var BUFFER = "\u2592";
var EMPTY = "\u2591";
var CONTENT_WIDTH = 56;
function truncateName(name, maxLen) {
  if (name.length <= maxLen) return name;
  return name.slice(0, maxLen - 1) + "\u2026";
}
__name(truncateName, "truncateName");
function formatTokens(tokens) {
  if (tokens >= 1e3) {
    return `${(tokens / 1e3).toFixed(1)}k`;
  }
  return `${tokens}`;
}
__name(formatTokens, "formatTokens");
var ProgressBar = /* @__PURE__ */ __name(({ usedPercentage, bufferPercentage, width }) => {
  const usedCount = Math.round(Math.min(usedPercentage, 100) / 100 * width);
  const bufferCount = Math.round(
    Math.min(bufferPercentage, 100 - usedPercentage) / 100 * width
  );
  const freeCount = Math.max(0, width - usedCount - bufferCount);
  const usedStr = FILLED.repeat(Math.max(0, usedCount));
  const freeStr = EMPTY.repeat(Math.max(0, freeCount));
  const bufferStr = BUFFER.repeat(Math.max(0, bufferCount));
  let usedColor = theme.text.accent;
  if (usedPercentage > 80) {
    usedColor = theme.status.error;
  } else if (usedPercentage > 60) {
    usedColor = theme.status.warning;
  }
  return /* @__PURE__ */ (0, import_jsx_runtime42.jsxs)(Text, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(Text, { color: usedColor, children: usedStr }),
    /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(Text, { color: theme.text.secondary, children: freeStr }),
    /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(Text, { color: theme.status.warning, children: bufferStr })
  ] });
}, "ProgressBar");
function formatPercentage(tokens, contextWindowSize) {
  if (contextWindowSize <= 0) return "0.0";
  const percentage = tokens / contextWindowSize * 100;
  if (percentage > 100) {
    return ">100";
  }
  return percentage.toFixed(1);
}
__name(formatPercentage, "formatPercentage");
var CategoryRow = /* @__PURE__ */ __name(({
  symbol,
  label,
  tokens,
  contextWindowSize,
  symbolColor,
  isOverLimit
}) => {
  const percentageStr = formatPercentage(tokens, contextWindowSize);
  const tokenStr = `${formatTokens(tokens)} ${t("tokens")} (${percentageStr}%)`;
  return /* @__PURE__ */ (0, import_jsx_runtime42.jsxs)(Box_default, { width: CONTENT_WIDTH, children: [
    /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(Box_default, { width: 2, children: /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(Text, { color: symbolColor || theme.text.secondary, children: symbol }) }),
    /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(Box_default, { width: 24, children: /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(Text, { color: theme.text.primary, children: label }) }),
    /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(Box_default, { flexGrow: 1, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(Text, { color: isOverLimit ? theme.status.error : theme.text.secondary, children: tokenStr }) })
  ] });
}, "CategoryRow");
var ThresholdRow = /* @__PURE__ */ __name(({ label, tokens, isCurrent, hint }) => {
  const tokenStr = `${formatTokens(tokens)} ${t("tokens")}`;
  return /* @__PURE__ */ (0, import_jsx_runtime42.jsxs)(Box_default, { width: CONTENT_WIDTH, children: [
    /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(Box_default, { width: 2, children: /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(Text, { color: isCurrent ? theme.status.warning : theme.text.secondary, children: isCurrent ? "\u25B6" : " " }) }),
    /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(Box_default, { width: 22, children: /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(Text, { color: theme.text.primary, children: label }) }),
    /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(Box_default, { flexGrow: 1, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime42.jsxs)(Text, { color: theme.text.secondary, children: [
      tokenStr,
      hint ? `  ${hint}` : ""
    ] }) })
  ] });
}, "ThresholdRow");
function tierColor(tier) {
  switch (tier) {
    case "safe":
      return theme.status.success;
    case "warn":
      return theme.status.warning;
    case "auto":
      return theme.status.warning;
    case "hard":
      return theme.status.error;
    default:
      return theme.text.secondary;
  }
}
__name(tierColor, "tierColor");
var CompactionThresholds = /* @__PURE__ */ __name(({ thresholds, currentTier }) => /* @__PURE__ */ (0, import_jsx_runtime42.jsxs)(Box_default, { flexDirection: "column", marginTop: 1, children: [
  /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(Text, { bold: true, color: theme.text.primary, children: t("Compaction thresholds") }),
  /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(
    ThresholdRow,
    {
      label: t("Effective window"),
      tokens: thresholds.effectiveWindow
    }
  ),
  /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(
    ThresholdRow,
    {
      label: t("Warn threshold"),
      tokens: thresholds.warn,
      isCurrent: currentTier === "warn"
    }
  ),
  /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(
    ThresholdRow,
    {
      label: t("Auto threshold"),
      tokens: thresholds.auto,
      isCurrent: currentTier === "auto"
    }
  ),
  /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(
    ThresholdRow,
    {
      label: t("Hard threshold"),
      tokens: thresholds.hard,
      isCurrent: currentTier === "hard"
    }
  ),
  /* @__PURE__ */ (0, import_jsx_runtime42.jsxs)(Box_default, { width: CONTENT_WIDTH, children: [
    /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(Box_default, { width: 2, children: /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(Text, { children: " " }) }),
    /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(Box_default, { width: 22, children: /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(Text, { color: theme.text.primary, children: t("Current tier") }) }),
    /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(Box_default, { flexGrow: 1, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(Text, { bold: true, color: tierColor(currentTier), children: currentTier }) })
  ] })
] }), "CompactionThresholds");
var DETAIL_NAME_MAX_LEN = 30;
var DetailRow = /* @__PURE__ */ __name(({ name, tokens }) => {
  const tokenStr = tokens > 0 ? `${formatTokens(tokens)} ${t("tokens")}` : `0 ${t("tokens")}`;
  return /* @__PURE__ */ (0, import_jsx_runtime42.jsxs)(Box_default, { width: CONTENT_WIDTH, paddingLeft: 2, children: [
    /* @__PURE__ */ (0, import_jsx_runtime42.jsxs)(Text, { color: theme.text.secondary, children: [
      "\u2514",
      " "
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(Box_default, { width: 32, children: /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(Text, { color: theme.text.link, children: truncateName(name, DETAIL_NAME_MAX_LEN) }) }),
    /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(Box_default, { flexGrow: 1, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(Text, { color: theme.text.secondary, children: tokenStr }) })
  ] });
}, "DetailRow");
var ContextUsage = /* @__PURE__ */ __name(({
  modelName,
  totalTokens,
  contextWindowSize,
  breakdown,
  builtinTools,
  mcpTools,
  memoryFiles,
  skills,
  isEstimated,
  showDetails = false
}) => {
  const percentage = contextWindowSize > 0 ? totalTokens / contextWindowSize * 100 : 0;
  const isOverLimit = percentage > 100;
  const sortedBuiltinTools = [...builtinTools].sort(
    (a, b) => b.tokens - a.tokens
  );
  const sortedMcpTools = [...mcpTools].sort((a, b) => b.tokens - a.tokens);
  const sortedMemoryFiles = [...memoryFiles].sort(
    (a, b) => b.tokens - a.tokens
  );
  const sortedSkills = [...skills].sort((a, b) => {
    if (a.loaded !== b.loaded) return a.loaded ? -1 : 1;
    const aTotal = a.tokens + (a.bodyTokens ?? 0);
    const bTotal = b.tokens + (b.bodyTokens ?? 0);
    return bTotal - aTotal;
  });
  return /* @__PURE__ */ (0, import_jsx_runtime42.jsxs)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: theme.border.default,
      flexDirection: "column",
      paddingY: 1,
      paddingX: 2,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(Text, { bold: true, color: theme.text.accent, children: t("Context Usage") }),
        /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(Box_default, { height: 1 }),
        isEstimated ? /* @__PURE__ */ (0, import_jsx_runtime42.jsxs)(import_jsx_runtime42.Fragment, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(Box_default, { marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(Text, { color: theme.status.warning, italic: true, children: t("No API response yet. Send a message to see actual usage.") }) }),
          /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(Text, { bold: true, color: theme.text.primary, children: t("Estimated pre-conversation overhead") }),
          /* @__PURE__ */ (0, import_jsx_runtime42.jsxs)(Text, { color: theme.text.secondary, children: [
            t("Model"),
            ": ",
            modelName,
            "  ",
            t("Context window"),
            ": ",
            formatTokens(contextWindowSize),
            " ",
            t("tokens")
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(Box_default, { height: 1 })
        ] }) : /* @__PURE__ */ (0, import_jsx_runtime42.jsxs)(import_jsx_runtime42.Fragment, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime42.jsxs)(Box_default, { width: CONTENT_WIDTH, marginBottom: 1, children: [
            /* @__PURE__ */ (0, import_jsx_runtime42.jsxs)(Text, { color: theme.text.secondary, children: [
              t("Model"),
              ": ",
              modelName
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(Box_default, { flexGrow: 1, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime42.jsxs)(Text, { color: theme.text.secondary, children: [
              t("Context window"),
              ": ",
              formatTokens(contextWindowSize),
              " ",
              t("tokens")
            ] }) })
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(Box_default, { width: CONTENT_WIDTH, children: /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(
            ProgressBar,
            {
              usedPercentage: Math.min(percentage, 100),
              bufferPercentage: contextWindowSize > 0 ? breakdown.autocompactBuffer / contextWindowSize * 100 : 0,
              width: CONTENT_WIDTH
            }
          ) }),
          isOverLimit && /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(Box_default, { marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(Text, { color: theme.status.error, children: t("Context exceeds limit! Use /compress or /clear to reduce.") }) }),
          /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(Box_default, { height: 1 }),
          /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(
            CategoryRow,
            {
              symbol: FILLED,
              label: t("Used"),
              tokens: totalTokens,
              contextWindowSize,
              symbolColor: isOverLimit ? theme.status.error : theme.text.accent,
              isOverLimit
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(
            CategoryRow,
            {
              symbol: EMPTY,
              label: t("Free"),
              tokens: breakdown.freeSpace,
              contextWindowSize,
              symbolColor: theme.text.secondary
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(
            CategoryRow,
            {
              symbol: BUFFER,
              label: t("Autocompact buffer"),
              tokens: breakdown.autocompactBuffer,
              contextWindowSize,
              symbolColor: theme.status.warning
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(Box_default, { height: 1 }),
          /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(Text, { bold: true, color: theme.text.primary, children: t("Usage by category") })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(
          CategoryRow,
          {
            symbol: FILLED,
            label: t("System prompt"),
            tokens: breakdown.systemPrompt,
            contextWindowSize,
            symbolColor: theme.text.accent
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(
          CategoryRow,
          {
            symbol: FILLED,
            label: t("Built-in tools"),
            tokens: breakdown.builtinTools,
            contextWindowSize,
            symbolColor: theme.text.accent
          }
        ),
        breakdown.mcpTools > 0 && /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(
          CategoryRow,
          {
            symbol: FILLED,
            label: t("MCP tools"),
            tokens: breakdown.mcpTools,
            contextWindowSize,
            symbolColor: theme.text.accent
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(
          CategoryRow,
          {
            symbol: FILLED,
            label: t("Memory files"),
            tokens: breakdown.memoryFiles,
            contextWindowSize,
            symbolColor: theme.text.accent
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(
          CategoryRow,
          {
            symbol: FILLED,
            label: t("Skills"),
            tokens: breakdown.skills,
            contextWindowSize,
            symbolColor: theme.text.accent
          }
        ),
        !isEstimated && /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(
          CategoryRow,
          {
            symbol: FILLED,
            label: t("Messages"),
            tokens: breakdown.messages,
            contextWindowSize,
            symbolColor: theme.text.accent
          }
        ),
        breakdown.thresholds && breakdown.currentTier && /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(
          CompactionThresholds,
          {
            thresholds: breakdown.thresholds,
            currentTier: breakdown.currentTier
          }
        ),
        showDetails ? /* @__PURE__ */ (0, import_jsx_runtime42.jsxs)(import_jsx_runtime42.Fragment, { children: [
          sortedBuiltinTools.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime42.jsxs)(Box_default, { flexDirection: "column", marginTop: 1, children: [
            /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(Text, { bold: true, color: theme.text.primary, children: t("Built-in tools") }),
            sortedBuiltinTools.map((tool) => /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(
              DetailRow,
              {
                name: tool.name,
                tokens: tool.tokens
              },
              tool.name
            ))
          ] }),
          sortedMcpTools.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime42.jsxs)(Box_default, { flexDirection: "column", marginTop: 1, children: [
            /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(Text, { bold: true, color: theme.text.primary, children: t("MCP tools") }),
            sortedMcpTools.map((tool) => /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(
              DetailRow,
              {
                name: tool.name,
                tokens: tool.tokens
              },
              tool.name
            ))
          ] }),
          sortedMemoryFiles.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime42.jsxs)(Box_default, { flexDirection: "column", marginTop: 1, children: [
            /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(Text, { bold: true, color: theme.text.primary, children: t("Memory files") }),
            sortedMemoryFiles.map((file) => /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(
              DetailRow,
              {
                name: file.path,
                tokens: file.tokens
              },
              file.path
            ))
          ] }),
          sortedSkills.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime42.jsxs)(Box_default, { flexDirection: "column", marginTop: 1, children: [
            /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(Text, { bold: true, color: theme.text.primary, children: t("Skills") }),
            sortedSkills.map((skill) => /* @__PURE__ */ (0, import_jsx_runtime42.jsxs)(Box_default, { flexDirection: "column", children: [
              /* @__PURE__ */ (0, import_jsx_runtime42.jsxs)(Box_default, { width: CONTENT_WIDTH, paddingLeft: 2, children: [
                /* @__PURE__ */ (0, import_jsx_runtime42.jsxs)(Text, { color: theme.text.secondary, children: [
                  "\u2514",
                  " "
                ] }),
                /* @__PURE__ */ (0, import_jsx_runtime42.jsxs)(Box_default, { width: 32, children: [
                  /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(Text, { color: theme.text.link, children: truncateName(skill.name, DETAIL_NAME_MAX_LEN) }),
                  skill.loaded && /* @__PURE__ */ (0, import_jsx_runtime42.jsxs)(Text, { color: theme.status.success, children: [
                    " ",
                    t("active")
                  ] })
                ] }),
                /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(Box_default, { flexGrow: 1, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime42.jsxs)(Text, { color: theme.text.secondary, children: [
                  formatTokens(skill.tokens),
                  " ",
                  t("tokens")
                ] }) })
              ] }),
              skill.loaded && skill.bodyTokens != null && skill.bodyTokens > 0 && /* @__PURE__ */ (0, import_jsx_runtime42.jsxs)(Box_default, { width: CONTENT_WIDTH, paddingLeft: 4, children: [
                /* @__PURE__ */ (0, import_jsx_runtime42.jsxs)(Text, { color: theme.text.secondary, children: [
                  "  \u2514",
                  " "
                ] }),
                /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(Box_default, { width: 30, children: /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(Text, { color: theme.text.secondary, italic: true, children: t("body loaded") }) }),
                /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(Box_default, { flexGrow: 1, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime42.jsxs)(Text, { color: theme.status.success, children: [
                  "+",
                  formatTokens(skill.bodyTokens),
                  " ",
                  t("tokens")
                ] }) })
              ] })
            ] }, skill.name))
          ] })
        ] }) : /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime42.jsx)(Text, { color: theme.text.secondary, italic: true, children: t("Run /context detail for per-item breakdown.") }) })
      ]
    }
  );
}, "ContextUsage");

// packages/cli/src/ui/components/views/DoctorReport.tsx
init_esbuild_shims();
var import_jsx_runtime43 = __toESM(require_jsx_runtime(), 1);
var STATUS_ICONS2 = {
  pass: "\u2713",
  // checkmark
  warn: "\u26A0",
  // warning triangle
  fail: "\u2717"
  // X mark
};
function getStatusColor2(status) {
  switch (status) {
    case "pass":
      return theme.status.success;
    case "warn":
      return theme.status.warning;
    case "fail":
      return theme.status.error;
    default:
      return theme.text.primary;
  }
}
__name(getStatusColor2, "getStatusColor");
function groupByCategory(checks) {
  const groups = /* @__PURE__ */ new Map();
  for (const check of checks) {
    const group = groups.get(check.category);
    if (group) {
      group.push(check);
    } else {
      groups.set(check.category, [check]);
    }
  }
  return groups;
}
__name(groupByCategory, "groupByCategory");
var DoctorReport = /* @__PURE__ */ __name(({
  checks,
  summary,
  width
}) => {
  const groups = groupByCategory(checks);
  const categoryEntries = Array.from(groups.entries());
  const nameColWidth = Math.max(20, ...checks.map((c) => c.name.length + 2));
  return /* @__PURE__ */ (0, import_jsx_runtime43.jsxs)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: theme.border.default,
      flexDirection: "column",
      paddingY: 1,
      paddingX: 2,
      width,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime43.jsx)(Text, { bold: true, color: theme.text.accent, children: t("Doctor Report") }),
        /* @__PURE__ */ (0, import_jsx_runtime43.jsx)(Box_default, { height: 1 }),
        categoryEntries.map(([category, items], groupIdx) => /* @__PURE__ */ (0, import_jsx_runtime43.jsxs)(
          Box_default,
          {
            flexDirection: "column",
            marginTop: groupIdx > 0 ? 1 : 0,
            children: [
              /* @__PURE__ */ (0, import_jsx_runtime43.jsx)(Text, { bold: true, color: theme.text.link, children: category }),
              items.map((check) => /* @__PURE__ */ (0, import_jsx_runtime43.jsxs)(Box_default, { flexDirection: "column", children: [
                /* @__PURE__ */ (0, import_jsx_runtime43.jsxs)(Box_default, { flexDirection: "row", children: [
                  /* @__PURE__ */ (0, import_jsx_runtime43.jsxs)(Text, { color: getStatusColor2(check.status), children: [
                    "  ",
                    STATUS_ICONS2[check.status],
                    " "
                  ] }),
                  /* @__PURE__ */ (0, import_jsx_runtime43.jsx)(Box_default, { width: nameColWidth, children: /* @__PURE__ */ (0, import_jsx_runtime43.jsx)(Text, { color: theme.text.primary, children: check.name }) }),
                  /* @__PURE__ */ (0, import_jsx_runtime43.jsx)(Text, { dimColor: true, children: check.message })
                ] }),
                check.detail && /* @__PURE__ */ (0, import_jsx_runtime43.jsx)(Box_default, { marginLeft: 6, children: /* @__PURE__ */ (0, import_jsx_runtime43.jsxs)(Text, { dimColor: true, children: [
                  "-> ",
                  check.detail
                ] }) })
              ] }, `${category}-${check.name}`))
            ]
          },
          category
        )),
        /* @__PURE__ */ (0, import_jsx_runtime43.jsxs)(Box_default, { marginTop: 1, children: [
          /* @__PURE__ */ (0, import_jsx_runtime43.jsx)(Text, { dimColor: true, children: "-- " }),
          /* @__PURE__ */ (0, import_jsx_runtime43.jsxs)(Text, { color: theme.status.success, children: [
            summary.pass,
            " ",
            t("passed")
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime43.jsx)(Text, { dimColor: true, children: ", " }),
          /* @__PURE__ */ (0, import_jsx_runtime43.jsxs)(Text, { color: theme.status.warning, children: [
            summary.warn,
            " ",
            t("warnings")
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime43.jsx)(Text, { dimColor: true, children: ", " }),
          /* @__PURE__ */ (0, import_jsx_runtime43.jsxs)(Text, { color: theme.status.error, children: [
            summary.fail,
            " ",
            t("failures")
          ] })
        ] })
      ]
    }
  );
}, "DoctorReport");

// packages/cli/src/ui/components/arena/ArenaCards.tsx
init_esbuild_shims();
var import_jsx_runtime44 = __toESM(require_jsx_runtime(), 1);
var ArenaAgentCard = /* @__PURE__ */ __name(({
  agent,
  width
}) => {
  const { icon, text, color } = getArenaStatusLabel(agent.status);
  const duration = formatDuration(agent.durationMs);
  const tokens = agent.totalTokens.toLocaleString();
  const inTokens = agent.inputTokens.toLocaleString();
  const outTokens = agent.outputTokens.toLocaleString();
  return /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Box_default, { flexDirection: "column", width, children: [
    /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Text, { color, children: [
      icon,
      " ",
      agent.label,
      " \xB7 ",
      text,
      " \xB7 ",
      duration
    ] }) }),
    /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Box_default, { marginLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Text, { color: theme.text.secondary, children: [
      "Tokens: ",
      tokens,
      " (in ",
      inTokens,
      ", out ",
      outTokens,
      ")"
    ] }) }),
    /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Box_default, { marginLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Text, { color: theme.text.secondary, children: [
      "Tool Calls: ",
      agent.toolCalls,
      agent.failedToolCalls > 0 && /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(import_jsx_runtime44.Fragment, { children: [
        " ",
        "(",
        /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Text, { color: theme.status.success, children: [
          "\u2713 ",
          agent.successfulToolCalls
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Text, { color: theme.text.secondary, children: " " }),
        /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Text, { color: theme.status.error, children: [
          "\u2715 ",
          agent.failedToolCalls
        ] }),
        ")"
      ] })
    ] }) }),
    agent.error && /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Box_default, { marginLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Text, { color: theme.status.error, children: agent.error }) })
  ] });
}, "ArenaAgentCard");
function getDiffStats(diff, diffSummary) {
  if (diffSummary) {
    return {
      text: `+${diffSummary.additions}/-${diffSummary.deletions}`,
      additions: diffSummary.additions,
      deletions: diffSummary.deletions
    };
  }
  if (!diff) return { text: "", additions: 0, deletions: 0 };
  const lines = diff.split("\n");
  let additions = 0;
  let deletions = 0;
  for (const line of lines) {
    if (line.startsWith("+") && !line.startsWith("+++")) {
      additions++;
    } else if (line.startsWith("-") && !line.startsWith("---")) {
      deletions++;
    }
  }
  return { text: `+${additions}/-${deletions}`, additions, deletions };
}
__name(getDiffStats, "getDiffStats");
var MAX_FILE_LIST_ITEMS = 4;
function formatFileList(files) {
  if (!files || files.length === 0) {
    return "none";
  }
  const visible = files.slice(0, MAX_FILE_LIST_ITEMS);
  const suffix = files.length > MAX_FILE_LIST_ITEMS ? `, +${files.length - MAX_FILE_LIST_ITEMS} more` : "";
  return `${visible.join(", ")}${suffix}`;
}
__name(formatFileList, "formatFileList");
function getAgentFiles(agent) {
  return agent.modifiedFiles ?? agent.diffSummary?.files.map((file) => file.path) ?? [];
}
__name(getAgentFiles, "getAgentFiles");
function getComparisonFileGroups(agents) {
  const counts = /* @__PURE__ */ new Map();
  for (const agent of agents) {
    for (const file of new Set(getAgentFiles(agent))) {
      counts.set(file, (counts.get(file) ?? 0) + 1);
    }
  }
  const common = [...counts.entries()].filter(([, count]) => count > 1).map(([file]) => file).sort();
  const groups = [{ label: "common", files: common }];
  for (const agent of agents) {
    const unique = getAgentFiles(agent).filter((file) => counts.get(file) === 1).sort();
    if (unique.length > 0) {
      groups.push({ label: `${agent.label}-only`, files: unique });
    }
  }
  return groups;
}
__name(getComparisonFileGroups, "getComparisonFileGroups");
function getTreeBranch(index, total) {
  return index === total - 1 ? "\u2514\u2500" : "\u251C\u2500";
}
__name(getTreeBranch, "getTreeBranch");
var ArenaSessionCard = /* @__PURE__ */ __name(({
  sessionStatus,
  agents,
  width
}) => {
  const titleLabel = sessionStatus === "idle" || sessionStatus === "completed" ? "Arena Comparison Summary" : sessionStatus === "cancelled" ? "Arena Cancelled" : "Arena Failed";
  return /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(
    Box_default,
    {
      borderStyle: "round",
      borderColor: theme.border.default,
      flexDirection: "column",
      paddingX: 2,
      paddingY: 1,
      width,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Text, { bold: true, color: theme.text.primary, children: titleLabel }) }),
        /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Box_default, { height: 1 }),
        (sessionStatus === "idle" || sessionStatus === "completed") && /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(import_jsx_runtime44.Fragment, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Box_default, { flexDirection: "column", children: [
            /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Text, { bold: true, color: theme.text.primary, children: "Status Summary:" }),
            agents.map((agent, index) => {
              const { text: statusText, color } = getArenaStatusLabel(
                agent.status
              );
              return /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Box_default, { marginLeft: 2, children: [
                /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Text, { color: theme.text.secondary, children: [
                  index === agents.length - 1 ? "\u2514\u2500" : "\u251C\u2500",
                  " ",
                  agent.label,
                  ":",
                  " "
                ] }),
                /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Text, { color, children: statusText })
              ] }, agent.label);
            })
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Box_default, { height: 1 }),
          /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Box_default, { flexDirection: "column", children: [
            /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Text, { bold: true, color: theme.text.primary, children: "Files Modified:" }),
            getComparisonFileGroups(agents).map((group, index, groups) => /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Box_default, { marginLeft: 2, children: [
              /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Text, { color: theme.text.secondary, children: [
                getTreeBranch(index, groups.length),
                " ",
                group.label,
                ":",
                " "
              ] }),
              /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Text, { color: theme.text.primary, children: formatFileList(group.files) })
            ] }, group.label))
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Box_default, { height: 1 }),
          /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Box_default, { flexDirection: "column", children: [
            /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Text, { bold: true, color: theme.text.primary, children: "Approach Summary:" }),
            agents.map((agent, index) => {
              const diffStats = getDiffStats(agent.diff, agent.diffSummary);
              const files = getAgentFiles(agent).length;
              const branch = index === agents.length - 1 ? "\u2514\u2500" : "\u251C\u2500";
              const summary = agent.approachSummary ?? "No approach summary available.";
              return /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Box_default, { marginLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Text, { children: [
                /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Text, { color: theme.text.secondary, children: [
                  branch,
                  " ",
                  agent.label,
                  ":",
                  " "
                ] }),
                /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Text, { color: theme.text.primary, children: [
                  summary,
                  " "
                ] }),
                /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Text, { color: theme.text.secondary, children: "(" }),
                /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Text, { color: theme.text.accent, children: files }),
                /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Text, { color: theme.text.secondary, children: files === 1 ? " file, " : " files, " }),
                /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Text, { color: theme.status.success, children: [
                  "+",
                  diffStats.additions
                ] }),
                /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Text, { color: theme.text.secondary, children: " " }),
                /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Text, { color: theme.status.error, children: [
                  "-",
                  diffStats.deletions
                ] }),
                /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Text, { color: theme.text.secondary, children: " lines, " }),
                /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Text, { color: theme.text.accent, children: agent.toolCalls }),
                /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Text, { color: theme.text.secondary, children: agent.toolCalls === 1 ? " tool call)" : " tool calls)" })
              ] }) }, agent.label);
            })
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Box_default, { height: 1 }),
          /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Box_default, { flexDirection: "column", children: [
            /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Text, { bold: true, color: theme.text.primary, children: "Token Efficiency:" }),
            agents.map((agent, index) => /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Box_default, { marginLeft: 2, children: [
              /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Text, { color: theme.text.secondary, children: [
                index === agents.length - 1 ? "\u2514\u2500" : "\u251C\u2500",
                " ",
                agent.label,
                ":",
                " "
              ] }),
              /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Text, { color: theme.text.primary, children: [
                agent.outputTokens.toLocaleString(),
                " tokens \xB7 runtime",
                " ",
                formatDuration(agent.durationMs)
              ] })
            ] }, agent.label))
          ] })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Box_default, { height: 1 }),
        sessionStatus === "idle" && /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Box_default, { flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Text, { color: theme.text.secondary, children: [
          "Run ",
          /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Text, { color: theme.text.accent, children: "/arena select" }),
          " to view detailed diff or pick a winner."
        ] }) }),
        sessionStatus === "completed" && /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime44.jsxs)(Text, { color: theme.text.secondary, children: [
          "Run ",
          /* @__PURE__ */ (0, import_jsx_runtime44.jsx)(Text, { color: theme.text.accent, children: "/arena select" }),
          " to pick a winner."
        ] }) })
      ]
    }
  );
}, "ArenaSessionCard");

// packages/cli/src/ui/components/messages/InsightProgressMessage.tsx
init_esbuild_shims();
var import_jsx_runtime45 = __toESM(require_jsx_runtime(), 1);
var InsightProgressMessage = /* @__PURE__ */ __name(({
  progress
}) => {
  const { stage, progress: percent, isComplete, error } = progress;
  const width = 30;
  const completedWidth = Math.round(percent / 100 * width);
  const remainingWidth = width - completedWidth;
  const bar = "\u2588".repeat(Math.max(0, completedWidth)) + "\u2591".repeat(Math.max(0, remainingWidth));
  if (error) {
    return /* @__PURE__ */ (0, import_jsx_runtime45.jsxs)(Box_default, { flexDirection: "column", children: [
      /* @__PURE__ */ (0, import_jsx_runtime45.jsxs)(Text, { color: theme.status.error, children: [
        "\u2715 ",
        stage
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(Text, { color: theme.text.secondary, children: error })
    ] });
  }
  if (isComplete) {
    return /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(Box_default, { flexDirection: "row", children: /* @__PURE__ */ (0, import_jsx_runtime45.jsxs)(Text, { color: theme.status.success, children: [
      "\u2713 ",
      stage
    ] }) });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime45.jsxs)(Box_default, { flexDirection: "row", children: [
    /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(Text, { color: theme.text.accent, children: /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(build_default, { type: "dots" }) }),
    /* @__PURE__ */ (0, import_jsx_runtime45.jsx)(Text, { children: " " }),
    /* @__PURE__ */ (0, import_jsx_runtime45.jsxs)(Text, { color: theme.text.secondary, children: [
      bar,
      " "
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime45.jsxs)(Text, { color: theme.text.accent, children: [
      stage,
      progress.detail ? ` (${progress.detail})` : ""
    ] })
  ] });
}, "InsightProgressMessage");

// packages/cli/src/ui/components/messages/BtwMessage.tsx
init_esbuild_shims();
var import_react35 = __toESM(require_react(), 1);
var import_jsx_runtime46 = __toESM(require_jsx_runtime(), 1);
var BTW_SELF_CHROME = 4;
function normalizeCodeFences(text) {
  return text.replace(/([^\n])(```|~~~)/g, "$1\n$2");
}
__name(normalizeCodeFences, "normalizeCodeFences");
var BtwMessageInternal = /* @__PURE__ */ __name(({
  btw,
  containerWidth
}) => {
  const { columns: terminalWidth } = useTerminalSize();
  const baseWidth = containerWidth ?? terminalWidth;
  const contentWidth = Math.max(2, baseWidth - BTW_SELF_CHROME);
  return /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)(
    Box_default,
    {
      flexDirection: "column",
      borderStyle: "round",
      borderColor: Colors.AccentYellow,
      paddingX: 1,
      width: "100%",
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)(Box_default, { flexDirection: "row", children: [
          /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Text, { color: Colors.AccentYellow, bold: true, children: "/btw " }),
          /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Text, { wrap: "wrap", color: Colors.AccentYellow, children: btw.question })
        ] }),
        btw.isPending ? /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)(Box_default, { flexDirection: "column", marginTop: 1, children: [
          /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)(Box_default, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Text, { color: Colors.AccentYellow, children: "+ " }),
            /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Text, { color: Colors.AccentYellow, children: t("Answering...") })
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Text, { dimColor: true, children: t("Press Escape, Ctrl+C, or Ctrl+D to cancel") }) })
        ] }) : /* @__PURE__ */ (0, import_jsx_runtime46.jsxs)(Box_default, { flexDirection: "column", marginTop: 1, children: [
          /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(
            MarkdownDisplay,
            {
              text: normalizeCodeFences(btw.answer),
              isPending: false,
              contentWidth
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime46.jsx)(Text, { dimColor: true, children: t("Press Space, Enter, or Escape to dismiss") }) })
        ] })
      ]
    }
  );
}, "BtwMessageInternal");
var BtwMessage = import_react35.default.memo(BtwMessageInternal);

// packages/cli/src/ui/components/messages/MemorySavedMessage.tsx
init_esbuild_shims();
var import_jsx_runtime47 = __toESM(require_jsx_runtime(), 1);
var MemorySavedMessage = /* @__PURE__ */ __name(({
  item
}) => {
  const verb = item.verb ?? "Saved";
  const n = item.writtenCount;
  const label = n === 1 ? "memory" : "memories";
  return /* @__PURE__ */ (0, import_jsx_runtime47.jsxs)(Box_default, { flexDirection: "row", children: [
    /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(Box_default, { minWidth: 2, children: /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(Text, { dimColor: true, children: "\u25CF" }) }),
    /* @__PURE__ */ (0, import_jsx_runtime47.jsxs)(Text, { dimColor: true, children: [
      verb,
      " ",
      n,
      " ",
      label
    ] })
  ] });
}, "MemorySavedMessage");

// packages/cli/src/ui/components/messages/DiffStatsDisplay.tsx
init_esbuild_shims();
var import_jsx_runtime48 = __toESM(require_jsx_runtime(), 1);
var DiffStatsDisplay = /* @__PURE__ */ __name(({
  model
}) => {
  const { filesCount, linesAdded, linesRemoved, rows, hiddenCount } = model;
  const { addWidth, remWidth, statColumnWidth } = computeDiffColumnWidths(rows);
  const headerLabel = filesCount === 1 ? t("{{count}} file changed", { count: String(filesCount) }) : t("{{count}} files changed", { count: String(filesCount) });
  return /* @__PURE__ */ (0, import_jsx_runtime48.jsxs)(Box_default, { flexDirection: "column", children: [
    /* @__PURE__ */ (0, import_jsx_runtime48.jsxs)(Text, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Text, { color: theme.text.primary, children: headerLabel }),
      /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Text, { color: theme.text.secondary, children: ", " }),
      /* @__PURE__ */ (0, import_jsx_runtime48.jsxs)(Text, { color: theme.status.success, children: [
        "+",
        linesAdded
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Text, { color: theme.text.secondary, children: " / " }),
      /* @__PURE__ */ (0, import_jsx_runtime48.jsxs)(Text, { color: theme.status.error, children: [
        "-",
        linesRemoved
      ] })
    ] }),
    rows.map((row) => /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(
      DiffRow,
      {
        row,
        addWidth,
        remWidth,
        statColumnWidth
      },
      row.filename
    )),
    hiddenCount > 0 && rows.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime48.jsxs)(Text, { color: theme.text.secondary, children: [
      "  ",
      t("\u2026and {{hidden}} more (showing first {{shown}})", {
        hidden: String(hiddenCount),
        shown: String(rows.length)
      })
    ] }) })
  ] });
}, "DiffStatsDisplay");
var DiffRow = /* @__PURE__ */ __name(({
  row,
  addWidth,
  remWidth,
  statColumnWidth
}) => {
  if (row.isBinary) {
    const marker = padRight("~", statColumnWidth);
    const suffix2 = row.isUntracked ? t("(binary, new)") : row.isDeleted ? t("(binary, deleted)") : t("(binary)");
    return /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime48.jsxs)(Text, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Text, { color: theme.text.primary, children: "  " }),
      /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Text, { color: theme.text.secondary, children: marker }),
      /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Text, { color: theme.text.primary, children: "  " }),
      /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Text, { color: theme.text.primary, children: row.filename }),
      /* @__PURE__ */ (0, import_jsx_runtime48.jsxs)(Text, { color: theme.text.secondary, children: [
        " ",
        suffix2
      ] })
    ] }) });
  }
  const added = String(row.added ?? 0).padStart(addWidth);
  const removed = String(row.removed ?? 0).padStart(remWidth);
  let suffix = null;
  if (row.isUntracked) {
    suffix = row.truncated ? t("(new, partial)") : t("(new)");
  } else if (row.isDeleted) {
    suffix = t("(deleted)");
  }
  return /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime48.jsxs)(Text, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Text, { color: theme.text.primary, children: "  " }),
    /* @__PURE__ */ (0, import_jsx_runtime48.jsxs)(Text, { color: theme.status.success, children: [
      "+",
      added
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Text, { color: theme.text.primary, children: " " }),
    /* @__PURE__ */ (0, import_jsx_runtime48.jsxs)(Text, { color: theme.status.error, children: [
      "-",
      removed
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Text, { color: theme.text.primary, children: "  " }),
    /* @__PURE__ */ (0, import_jsx_runtime48.jsx)(Text, { color: theme.text.primary, children: row.filename }),
    suffix && /* @__PURE__ */ (0, import_jsx_runtime48.jsxs)(Text, { color: theme.text.secondary, children: [
      " ",
      suffix
    ] })
  ] }) });
}, "DiffRow");
function padRight(s, width) {
  return s.length >= width ? s : s + " ".repeat(width - s.length);
}
__name(padRight, "padRight");

// packages/cli/src/ui/components/messages/GoalStatusMessage.tsx
init_esbuild_shims();
var import_react36 = __toESM(require_react(), 1);
var import_jsx_runtime49 = __toESM(require_jsx_runtime(), 1);
var pluralTurns = /* @__PURE__ */ __name((n) => n === 1 ? "turn" : "turns", "pluralTurns");
function assertNeverGoalStatusKind(kind) {
  throw new Error(`Unexpected goal status kind: ${kind}`);
}
__name(assertNeverGoalStatusKind, "assertNeverGoalStatusKind");
var GoalStatusMessageInternal = /* @__PURE__ */ __name(({
  kind,
  condition,
  iterations,
  durationMs,
  lastReason
}) => {
  if (kind === "checking") {
    const reason = lastReason?.trim();
    return /* @__PURE__ */ (0, import_jsx_runtime49.jsxs)(Box_default, { flexDirection: "row", children: [
      /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(Box_default, { width: 2, flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(Text, { color: theme.text.secondary, children: "\u25CB" }) }),
      /* @__PURE__ */ (0, import_jsx_runtime49.jsxs)(Box_default, { flexGrow: 1, flexDirection: "column", children: [
        /* @__PURE__ */ (0, import_jsx_runtime49.jsxs)(Text, { color: theme.text.secondary, children: [
          "Goal check",
          typeof iterations === "number" && iterations > 0 ? ` \xB7 turn ${iterations}` : "",
          " ",
          "\xB7 not yet met"
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime49.jsxs)(Text, { color: theme.text.secondary, wrap: "wrap", children: [
          "Goal: ",
          condition
        ] }),
        reason ? /* @__PURE__ */ (0, import_jsx_runtime49.jsxs)(Text, { color: theme.text.secondary, wrap: "wrap", children: [
          "Judge: ",
          reason
        ] }) : null
      ] })
    ] });
  }
  const { prefix, prefixColor, title } = (() => {
    switch (kind) {
      case "set":
        return {
          prefix: "\u25CE",
          prefixColor: theme.text.accent,
          title: "Goal set"
        };
      case "achieved":
        return {
          prefix: "\u2713",
          prefixColor: theme.status.success,
          title: "Goal achieved"
        };
      case "cleared":
        return {
          prefix: "\u25CB",
          prefixColor: theme.text.secondary,
          title: "Goal cleared"
        };
      case "failed":
        return {
          prefix: "\u2716",
          prefixColor: theme.status.error,
          title: "Goal could not be achieved"
        };
      case "aborted":
        return {
          prefix: "!",
          prefixColor: theme.status.warning,
          title: "Goal aborted"
        };
      default:
        return assertNeverGoalStatusKind(kind);
    }
  })();
  const stats = [];
  if (typeof iterations === "number" && iterations > 0) {
    stats.push(`${iterations} ${pluralTurns(iterations)}`);
  }
  if (typeof durationMs === "number") {
    stats.push(formatDuration(durationMs, { hideTrailingZeros: true }));
  }
  const subtitle = stats.length > 0 ? stats.join(" \xB7 ") : null;
  return /* @__PURE__ */ (0, import_jsx_runtime49.jsxs)(Box_default, { flexDirection: "row", children: [
    /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(Box_default, { width: 2, flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(Text, { color: prefixColor, children: prefix }) }),
    /* @__PURE__ */ (0, import_jsx_runtime49.jsxs)(Box_default, { flexGrow: 1, flexDirection: "column", children: [
      /* @__PURE__ */ (0, import_jsx_runtime49.jsxs)(Text, { color: prefixColor, children: [
        title,
        subtitle ? /* @__PURE__ */ (0, import_jsx_runtime49.jsxs)(Text, { color: theme.text.secondary, children: [
          " \xB7 ",
          subtitle
        ] }) : null
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime49.jsxs)(Box_default, { flexDirection: "row", children: [
        /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(Box_default, { flexShrink: 0, marginRight: 1, children: /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(Text, { color: theme.text.secondary, children: "Goal:" }) }),
        /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(Box_default, { flexGrow: 1, children: /* @__PURE__ */ (0, import_jsx_runtime49.jsx)(Text, { wrap: "wrap", children: condition }) })
      ] }),
      isTerminalGoalStatusKind(kind) && lastReason?.trim() ? /* @__PURE__ */ (0, import_jsx_runtime49.jsxs)(Text, { color: theme.text.secondary, wrap: "wrap", children: [
        "Last check: ",
        lastReason.trim()
      ] }) : null
    ] })
  ] });
}, "GoalStatusMessageInternal");
var GoalStatusMessage = import_react36.default.memo(GoalStatusMessageInternal);

// packages/cli/src/ui/contexts/ThoughtExpandedContext.tsx
init_esbuild_shims();
var import_react37 = __toESM(require_react(), 1);
var ThoughtExpandedContext = (0, import_react37.createContext)(false);
var useThoughtExpanded = /* @__PURE__ */ __name(() => (0, import_react37.useContext)(ThoughtExpandedContext), "useThoughtExpanded");
var ThoughtExpandedProvider = ThoughtExpandedContext.Provider;

// packages/cli/src/ui/contexts/ThinkingViewerContext.tsx
init_esbuild_shims();
var import_react38 = __toESM(require_react(), 1);
var ThinkingViewerContext = (0, import_react38.createContext)({
  openThinkingViewer: /* @__PURE__ */ __name(() => {
  }, "openThinkingViewer")
});
var useThinkingViewer = /* @__PURE__ */ __name(() => (0, import_react38.useContext)(ThinkingViewerContext), "useThinkingViewer");
var ThinkingViewerProvider = ThinkingViewerContext.Provider;

// packages/cli/src/ui/components/HistoryItemDisplay.tsx
var import_jsx_runtime50 = __toESM(require_jsx_runtime(), 1);
var ClickableThinkMessage = /* @__PURE__ */ __name(({
  text,
  viewerText,
  isPending,
  expanded,
  availableTerminalHeight,
  contentWidth,
  durationMs
}) => {
  const ref = (0, import_react39.useRef)(null);
  const { openThinkingViewer } = useThinkingViewer();
  const isActive = !isPending && !expanded;
  const sanitizedViewerText = (0, import_react39.useMemo)(
    () => escapeAnsiCtrlCodes(viewerText),
    [viewerText]
  );
  useMouseEvents(
    (0, import_react39.useCallback)(
      (event) => {
        if (event.name !== "left-press" || !ref.current) return;
        const metrics = measureElementPosition(ref.current);
        const col = event.col - 1;
        const row = event.row - 1;
        if (col >= metrics.x && col < metrics.x + metrics.width && row >= metrics.y && row < metrics.y + metrics.height) {
          openThinkingViewer({ text: sanitizedViewerText, durationMs });
        }
      },
      [openThinkingViewer, sanitizedViewerText, durationMs]
    ),
    { isActive }
  );
  return /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Box_default, { ref: isActive ? ref : void 0, children: /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(
    ThinkMessage,
    {
      text,
      isPending,
      expanded,
      availableTerminalHeight,
      contentWidth,
      durationMs
    }
  ) });
}, "ClickableThinkMessage");
function getHistoryItemMarginTop(item) {
  switch (item.type) {
    case "gemini":
    case "gemini_thought":
      return 1;
    case "gemini_content":
    case "gemini_thought_content":
    case "info":
    case "success":
    case "warning":
    case "error":
    case "retry_countdown":
    case "memory_saved":
    case "tool_group":
    case "tool_use_summary":
    case "notification":
    case "compression":
    case "summary":
    case "insight_progress":
    case "btw":
    case "away_recap":
    case "user":
    case "user_prompt_submit_blocked":
    case "stop_hook_loop":
    case "stop_hook_system_message":
    case "goal_status":
    case "vision_notice":
      return 0;
    default:
      return 1;
  }
}
__name(getHistoryItemMarginTop, "getHistoryItemMarginTop");
var HistoryItemDisplayComponent = /* @__PURE__ */ __name(({
  item,
  availableTerminalHeight,
  terminalWidth,
  mainAreaWidth,
  isPending,
  commands,
  isFocused = true,
  activeShellPtyId,
  embeddedShellFocused,
  availableTerminalHeightGemini,
  sourceCopyIndexOffsets,
  thoughtExpanded,
  thinkingFullText
}) => {
  const marginTop = getHistoryItemMarginTop(item);
  const contextThoughtExpanded = useThoughtExpanded();
  const resolvedThoughtExpanded = thoughtExpanded ?? contextThoughtExpanded;
  const settings = useSettings();
  const showTimestamps = settings.merged.output?.showTimestamps === true;
  const itemForDisplay = (0, import_react39.useMemo)(() => escapeAnsiCtrlCodes(item), [item]);
  const contentWidth = terminalWidth - 4;
  const boxWidth = mainAreaWidth || contentWidth;
  return /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)(
    Box_default,
    {
      flexDirection: "column",
      marginTop,
      marginLeft: 2,
      marginRight: 2,
      children: [
        itemForDisplay.type === "user" && /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(UserMessage, { text: itemForDisplay.text }),
        itemForDisplay.type === "notification" && /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(InfoMessage, { text: itemForDisplay.text }),
        itemForDisplay.type === "user_shell" && /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(UserShellMessage, { text: itemForDisplay.text }),
        itemForDisplay.type === "gemini" && /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)(import_jsx_runtime50.Fragment, { children: [
          showTimestamps && itemForDisplay.timestamp != null && /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)(Text, { dimColor: true, children: [
            "[",
            new Date(itemForDisplay.timestamp).toLocaleTimeString("en-US", {
              hour12: false,
              hour: "2-digit",
              minute: "2-digit",
              second: "2-digit"
            }),
            "]"
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(
            AssistantMessage,
            {
              text: itemForDisplay.text,
              isPending,
              availableTerminalHeight: availableTerminalHeightGemini ?? availableTerminalHeight,
              contentWidth,
              sourceCopyIndexOffsets
            }
          )
        ] }),
        itemForDisplay.type === "gemini_content" && /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(
          AssistantMessageContent,
          {
            text: itemForDisplay.text,
            isPending,
            availableTerminalHeight: availableTerminalHeightGemini ?? availableTerminalHeight,
            contentWidth,
            sourceCopyIndexOffsets
          }
        ),
        itemForDisplay.type === "gemini_thought" && /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(
          ClickableThinkMessage,
          {
            text: itemForDisplay.text.trimEnd(),
            viewerText: (thinkingFullText || itemForDisplay.text).trimEnd(),
            isPending,
            expanded: resolvedThoughtExpanded,
            availableTerminalHeight: availableTerminalHeightGemini ?? availableTerminalHeight,
            contentWidth,
            durationMs: itemForDisplay.durationMs
          }
        ),
        itemForDisplay.type === "gemini_thought_content" && /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(
          ThinkMessageContent,
          {
            text: itemForDisplay.text.trimEnd(),
            isPending,
            expanded: resolvedThoughtExpanded,
            availableTerminalHeight: availableTerminalHeightGemini ?? availableTerminalHeight,
            contentWidth
          }
        ),
        itemForDisplay.type === "info" && /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(
          InfoMessage,
          {
            text: itemForDisplay.text,
            linkUrl: itemForDisplay.linkUrl,
            linkText: itemForDisplay.linkText
          }
        ),
        itemForDisplay.type === "success" && /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(SuccessMessage, { text: itemForDisplay.text }),
        itemForDisplay.type === "warning" && /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(WarningMessage, { text: itemForDisplay.text }),
        itemForDisplay.type === "error" && /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(ErrorMessage, { text: itemForDisplay.text, hint: itemForDisplay.hint }),
        itemForDisplay.type === "retry_countdown" && /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(RetryCountdownMessage, { text: itemForDisplay.text }),
        itemForDisplay.type === "vision_notice" && /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(VisionNoticeMessage, { text: itemForDisplay.text }),
        itemForDisplay.type === "about" && /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(AboutBox, { ...itemForDisplay.systemInfo, width: boxWidth }),
        itemForDisplay.type === "help" && commands && /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Help, { commands, width: boxWidth }),
        itemForDisplay.type === "stats" && /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(StatsDisplay, { duration: itemForDisplay.duration, width: boxWidth }),
        itemForDisplay.type === "diff_stats" && /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(DiffStatsDisplay, { model: itemForDisplay.model }),
        itemForDisplay.type === "model_stats" && /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(ModelStatsDisplay, { width: boxWidth }),
        itemForDisplay.type === "tool_stats" && /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(ToolStatsDisplay, { width: boxWidth }),
        itemForDisplay.type === "skill_stats" && /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(SkillStatsDisplay, { width: boxWidth }),
        itemForDisplay.type === "quit" && /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(
          SessionSummaryDisplay,
          {
            duration: itemForDisplay.duration,
            width: boxWidth
          }
        ),
        itemForDisplay.type === "tool_group" && /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(
          ToolGroupMessage,
          {
            toolCalls: itemForDisplay.tools,
            groupId: itemForDisplay.id,
            availableTerminalHeight,
            contentWidth,
            isFocused,
            isPending,
            activeShellPtyId,
            embeddedShellFocused,
            memoryWriteCount: itemForDisplay.memoryWriteCount,
            memoryReadCount: itemForDisplay.memoryReadCount,
            isUserInitiated: itemForDisplay.isUserInitiated
          }
        ),
        itemForDisplay.type === "tool_use_summary" && /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Box_default, { paddingLeft: 1, children: /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)(Text, { dimColor: true, children: [
          "\u25CF ",
          itemForDisplay.summary
        ] }) }),
        itemForDisplay.type === "compression" && /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(CompressionMessage, { compression: itemForDisplay.compression }),
        itemForDisplay.type === "summary" && /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(SummaryMessage, { summary: itemForDisplay.summary }),
        itemForDisplay.type === "extensions_list" && /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(ExtensionsList, {}),
        itemForDisplay.type === "tools_list" && /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(
          ToolsList,
          {
            contentWidth,
            tools: itemForDisplay.tools,
            showDescriptions: itemForDisplay.showDescriptions
          }
        ),
        itemForDisplay.type === "skills_list" && /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(SkillsList, { skills: itemForDisplay.skills }),
        itemForDisplay.type === "mcp_status" && /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(McpStatus, { ...itemForDisplay, serverStatus: getMCPServerStatus }),
        itemForDisplay.type === "context_usage" && /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(
          ContextUsage,
          {
            modelName: itemForDisplay.modelName,
            totalTokens: itemForDisplay.totalTokens,
            contextWindowSize: itemForDisplay.contextWindowSize,
            breakdown: itemForDisplay.breakdown,
            builtinTools: itemForDisplay.builtinTools,
            mcpTools: itemForDisplay.mcpTools,
            memoryFiles: itemForDisplay.memoryFiles,
            skills: itemForDisplay.skills,
            isEstimated: itemForDisplay.isEstimated,
            showDetails: itemForDisplay.showDetails
          }
        ),
        itemForDisplay.type === "doctor" && /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(
          DoctorReport,
          {
            checks: itemForDisplay.checks,
            summary: itemForDisplay.summary,
            width: boxWidth
          }
        ),
        itemForDisplay.type === "arena_agent_complete" && /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(ArenaAgentCard, { agent: itemForDisplay.agent, width: boxWidth }),
        itemForDisplay.type === "arena_session_complete" && /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(
          ArenaSessionCard,
          {
            sessionStatus: itemForDisplay.sessionStatus,
            task: itemForDisplay.task,
            totalDurationMs: itemForDisplay.totalDurationMs,
            agents: itemForDisplay.agents,
            width: boxWidth
          }
        ),
        itemForDisplay.type === "insight_progress" && /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(InsightProgressMessage, { progress: itemForDisplay.progress }),
        itemForDisplay.type === "btw" && itemForDisplay.btw && /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(BtwMessage, { btw: itemForDisplay.btw, containerWidth: contentWidth }),
        itemForDisplay.type === "user_prompt_submit_blocked" && /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Box_default, { flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Text, { color: theme.status.warning, children: `\u2715 UserPromptSubmit operation blocked by hook:
${itemForDisplay.reason}

Original prompt: ${sanitizeSensitiveText(itemForDisplay.originalPrompt)}` }) }),
        itemForDisplay.type === "stop_hook_loop" && /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(
          InfoMessage,
          {
            text: `Ran ${itemForDisplay.stopHookCount} stop hooks
  \u23BF  Stop hook error: ${itemForDisplay.reasons[itemForDisplay.reasons.length - 1]}`
          }
        ),
        itemForDisplay.type === "stop_hook_system_message" && /* @__PURE__ */ (0, import_jsx_runtime50.jsxs)(Box_default, { flexDirection: "column", children: [
          /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Text, { color: theme.text.primary, children: " \u23BF Stop says:" }),
          /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(Box_default, { marginLeft: 4, flexDirection: "column", children: /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(
            MarkdownDisplay,
            {
              text: itemForDisplay.message,
              isPending: false,
              contentWidth: contentWidth - 4
            }
          ) })
        ] }),
        itemForDisplay.type === "memory_saved" && /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(MemorySavedMessage, { item: itemForDisplay }),
        itemForDisplay.type === "away_recap" && /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(AwayRecapMessage, { text: itemForDisplay.text }),
        itemForDisplay.type === "goal_status" && /* @__PURE__ */ (0, import_jsx_runtime50.jsx)(
          GoalStatusMessage,
          {
            kind: itemForDisplay.kind,
            condition: itemForDisplay.condition,
            iterations: itemForDisplay.iterations,
            durationMs: itemForDisplay.durationMs,
            lastReason: itemForDisplay.lastReason
          }
        )
      ]
    },
    itemForDisplay.id
  );
}, "HistoryItemDisplayComponent");

// packages/cli/src/ui/components/SessionPreview.tsx
var import_jsx_runtime51 = __toESM(require_jsx_runtime(), 1);
function SessionPreview(props) {
  const {
    sessionService,
    sessionId,
    sessionTitle,
    messageCount,
    mtime,
    gitBranch,
    onExit,
    onResume
  } = props;
  const { columns } = useTerminalSize();
  const [data, setData] = (0, import_react40.useState)(null);
  const [error, setError] = (0, import_react40.useState)(null);
  (0, import_react40.useEffect)(() => {
    let cancelled = false;
    setData(null);
    setError(null);
    sessionService.loadSession(sessionId).then((d) => {
      if (cancelled) return;
      if (!d) {
        setError("Session not found");
        return;
      }
      setData(d);
    }).catch((e) => {
      if (cancelled) return;
      setError(e instanceof Error ? e.message : String(e));
    });
    return () => {
      cancelled = true;
    };
  }, [sessionService, sessionId]);
  const items = (0, import_react40.useMemo)(() => {
    if (!data) return [];
    return buildResumedHistoryItems(data, null);
  }, [data]);
  const computedMessageCount = (0, import_react40.useMemo)(() => {
    if (!data) return void 0;
    const seen = /* @__PURE__ */ new Set();
    for (const msg of data.conversation.messages) {
      if (msg.type === "user" || msg.type === "assistant") {
        seen.add(msg.uuid);
      }
    }
    return seen.size;
  }, [data]);
  const displayMessageCount = messageCount ?? computedMessageCount;
  useKeypress(
    (key) => {
      const { name, ctrl } = key;
      if (name === "escape" || ctrl && name === "c") {
        onExit();
        return;
      }
      if (name === "return") {
        onResume(sessionId);
      }
    },
    { isActive: true }
  );
  const boxWidth = Math.max(10, columns - 4);
  const separatorWidth = Math.max(0, boxWidth - 2);
  const metaParts = [];
  if (typeof displayMessageCount === "number") {
    metaParts.push(formatMessageCount(displayMessageCount));
  }
  if (typeof mtime === "number") {
    metaParts.push(formatRelativeTime(mtime));
  }
  if (gitBranch) {
    metaParts.push(gitBranch);
  }
  const metaLine = metaParts.join(" \xB7 ");
  const header = /* @__PURE__ */ (0, import_jsx_runtime51.jsx)(Box_default, { paddingX: 1, children: /* @__PURE__ */ (0, import_jsx_runtime51.jsx)(Text, { bold: true, color: theme.text.primary, children: sessionTitle ?? t("Session Preview") }) }, "header");
  const topSeparator = /* @__PURE__ */ (0, import_jsx_runtime51.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime51.jsx)(Text, { color: theme.border.default, children: "\u2500".repeat(separatorWidth) }) }, "top-separator");
  const footerSeparator = /* @__PURE__ */ (0, import_jsx_runtime51.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime51.jsx)(Text, { color: theme.border.default, children: "\u2500".repeat(separatorWidth) }) }, "footer-separator");
  const meta = metaLine ? /* @__PURE__ */ (0, import_jsx_runtime51.jsx)(Box_default, { paddingX: 1, children: /* @__PURE__ */ (0, import_jsx_runtime51.jsx)(Text, { color: theme.text.secondary, children: metaLine }) }, "meta") : null;
  const footer = /* @__PURE__ */ (0, import_jsx_runtime51.jsx)(Box_default, { paddingX: 1, children: /* @__PURE__ */ (0, import_jsx_runtime51.jsx)(Text, { color: theme.text.secondary, children: t("Enter to resume \xB7 Esc to back") }) }, "footer");
  if (data && !error) {
    return /* @__PURE__ */ (0, import_jsx_runtime51.jsx)(Box_default, { flexDirection: "column", width: boxWidth, children: /* @__PURE__ */ (0, import_jsx_runtime51.jsx)(
      Static,
      {
        items: [
          header,
          topSeparator,
          ...items.map((item) => /* @__PURE__ */ (0, import_jsx_runtime51.jsx)(
            HistoryItemDisplayComponent,
            {
              item,
              terminalWidth: boxWidth,
              isPending: false,
              thoughtExpanded: true
            },
            item.id
          )),
          footerSeparator,
          ...meta ? [meta] : [],
          footer
        ],
        children: (item) => item
      },
      sessionId
    ) });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime51.jsxs)(Box_default, { flexDirection: "column", width: boxWidth, children: [
    header,
    topSeparator,
    error ? /* @__PURE__ */ (0, import_jsx_runtime51.jsx)(Box_default, { paddingY: 1, justifyContent: "center", children: /* @__PURE__ */ (0, import_jsx_runtime51.jsx)(Text, { color: theme.status.error, children: error }) }) : /* @__PURE__ */ (0, import_jsx_runtime51.jsx)(Box_default, { paddingY: 1, justifyContent: "center", children: /* @__PURE__ */ (0, import_jsx_runtime51.jsx)(Text, { color: theme.text.secondary, children: t("Loading session preview...") }) }),
    footerSeparator,
    meta,
    footer
  ] });
}
__name(SessionPreview, "SessionPreview");

// packages/cli/src/ui/components/SessionPicker.tsx
var import_jsx_runtime52 = __toESM(require_jsx_runtime(), 1);
var PREFIX_CHARS = {
  selected: "\u203A ",
  scrollUp: "\u2191 ",
  scrollDown: "\u2193 ",
  normal: "  "
};
function SessionListItemView({
  session,
  isSelected,
  isFirst,
  isLast,
  showScrollUp,
  showScrollDown,
  maxPromptWidth,
  prefixChars = PREFIX_CHARS,
  boldSelectedPrefix = true,
  isChecked,
  isDisabled = false,
  disabledHint
}) {
  const timeAgo = formatRelativeTime(session.mtime);
  const messageText = typeof session.messageCount === "number" ? formatMessageCount(session.messageCount) : void 0;
  const showUpIndicator = isFirst && showScrollUp;
  const showDownIndicator = isLast && showScrollDown;
  const prefix = isSelected ? prefixChars.selected : showUpIndicator ? prefixChars.scrollUp : showDownIndicator ? prefixChars.scrollDown : prefixChars.normal;
  const promptText = session.customTitle || session.prompt || "(empty prompt)";
  const checkboxWidth = isChecked === void 0 ? 0 : 4;
  const truncatedPrompt = truncateText(
    promptText,
    Math.max(1, maxPromptWidth - checkboxWidth)
  );
  const isAutoTitle = session.titleSource === "auto" && Boolean(session.customTitle);
  return /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Box_default, { flexDirection: "column", marginBottom: isLast ? 0 : 1, children: [
    /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Box_default, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(
        Text,
        {
          color: isSelected ? theme.text.accent : showUpIndicator || showDownIndicator ? theme.text.secondary : void 0,
          bold: isSelected && boldSelectedPrefix,
          children: prefix
        }
      ),
      isChecked !== void 0 && /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(
        Text,
        {
          color: isDisabled ? theme.text.secondary : isChecked ? theme.text.accent : isSelected ? theme.text.accent : theme.text.secondary,
          bold: isChecked,
          children: isChecked ? "[x] " : "[ ] "
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(
        Text,
        {
          color: isDisabled ? theme.text.secondary : isSelected ? theme.text.accent : isAutoTitle ? theme.text.secondary : theme.text.primary,
          bold: isSelected && !isDisabled,
          children: truncatedPrompt
        }
      )
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Box_default, { paddingLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Text, { color: theme.text.secondary, children: [
      timeAgo,
      messageText !== void 0 && ` \xB7 ${messageText}`,
      session.gitBranch && ` \xB7 ${session.gitBranch}`,
      isDisabled && disabledHint ? ` \xB7 ${disabledHint}` : ""
    ] }) })
  ] });
}
__name(SessionListItemView, "SessionListItemView");
function SessionPicker(props) {
  const {
    sessionService,
    onSelect,
    onCancel,
    currentBranch,
    title,
    centerSelection = true,
    initialSessions,
    enablePreview = false,
    enableMultiSelect = false,
    onConfirmMulti,
    disabledIds
  } = props;
  const { columns: width, rows: height } = useTerminalSize();
  const boxWidth = width - 4;
  const reservedLines = 7;
  const itemHeight = 3;
  const maxVisibleItems = Math.max(
    1,
    Math.floor((height - reservedLines) / itemHeight)
  );
  const picker = useSessionPicker({
    sessionService,
    currentBranch,
    onSelect,
    onCancel,
    maxVisibleItems,
    centerSelection,
    initialSessions,
    isActive: true,
    enablePreview,
    enableMultiSelect,
    onConfirmMulti,
    disabledIds
  });
  if (enablePreview && picker.viewMode === "preview" && picker.previewSessionId && sessionService) {
    const previewed = picker.filteredSessions.find(
      (s) => s.sessionId === picker.previewSessionId
    );
    return /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(
      SessionPreview,
      {
        sessionService,
        sessionId: picker.previewSessionId,
        sessionTitle: previewed?.customTitle ?? previewed?.prompt ?? void 0,
        messageCount: previewed?.messageCount,
        mtime: previewed?.mtime,
        gitBranch: previewed?.gitBranch,
        onExit: picker.exitPreview,
        onResume: onSelect
      }
    );
  }
  return /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(
    Box_default,
    {
      flexDirection: "column",
      width: boxWidth,
      height: height - 1,
      overflow: "hidden",
      children: /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(
        Box_default,
        {
          flexDirection: "column",
          borderStyle: "round",
          borderColor: theme.border.default,
          width: boxWidth,
          height: height - 1,
          overflow: "hidden",
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Box_default, { paddingX: 1, children: [
              /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text, { bold: true, color: theme.text.primary, children: title ?? t("Resume Session") }),
              picker.filterByBranch && currentBranch && /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Text, { color: theme.text.secondary, children: [
                " ",
                t("(branch: {{branch}})", { branch: currentBranch })
              ] }),
              picker.searchQuery !== "" && /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Text, { color: theme.text.secondary, children: [
                " ",
                t("({{count}} matches)", {
                  count: String(picker.filteredSessions.length)
                })
              ] })
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Box_default, { paddingX: 1, children: picker.isSearchActive ? /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(import_jsx_runtime52.Fragment, { children: [
              /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text, { color: theme.text.secondary, children: t("Search: ") }),
              /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Text, { color: theme.text.primary, children: [
                picker.searchQuery,
                /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text, { color: theme.text.secondary, children: "\u258C" })
              ] })
            ] }) : picker.searchQuery !== "" ? /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(import_jsx_runtime52.Fragment, { children: [
              /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text, { color: theme.text.secondary, children: t("Filter: ") }),
              /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text, { color: theme.text.primary, children: picker.searchQuery })
            ] }) : /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text, { color: theme.text.secondary, children: t("Press / to search") }) }),
            /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text, { color: theme.border.default, children: "\u2500".repeat(boxWidth - 2) }) }),
            /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Box_default, { flexDirection: "column", flexGrow: 1, paddingX: 1, overflow: "hidden", children: !sessionService || picker.isLoading ? /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Box_default, { paddingY: 1, justifyContent: "center", children: /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text, { color: theme.text.secondary, children: t("Loading sessions...") }) }) : picker.filteredSessions.length === 0 ? /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Box_default, { paddingY: 1, justifyContent: "center", children: /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text, { color: theme.text.secondary, children: picker.searchQuery !== "" ? t('No sessions match "{{query}}"', {
              query: picker.searchQuery
            }) : picker.filterByBranch ? t('No sessions found for branch "{{branch}}"', {
              branch: currentBranch ?? ""
            }) : t("No sessions found") }) }) : picker.visibleSessions.map((session, visibleIndex) => {
              const actualIndex = picker.scrollOffset + visibleIndex;
              const isDisabled = picker.disabledIdSet.has(session.sessionId);
              return /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(
                SessionListItemView,
                {
                  session,
                  isSelected: !picker.isSearchActive && actualIndex === picker.selectedIndex,
                  isFirst: visibleIndex === 0,
                  isLast: visibleIndex === picker.visibleSessions.length - 1,
                  showScrollUp: picker.showScrollUp,
                  showScrollDown: picker.showScrollDown,
                  maxPromptWidth: boxWidth - 6,
                  prefixChars: PREFIX_CHARS,
                  boldSelectedPrefix: false,
                  isChecked: enableMultiSelect ? picker.checkedIds.has(session.sessionId) : void 0,
                  isDisabled: enableMultiSelect && isDisabled,
                  disabledHint: enableMultiSelect && isDisabled ? t("current \u2014 cannot delete") : void 0
                },
                session.sessionId
              );
            }) }),
            /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text, { color: theme.border.default, children: "\u2500".repeat(boxWidth - 2) }) }),
            /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Box_default, { paddingX: 1, children: /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Box_default, { flexDirection: "row", children: picker.isSearchActive ? /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text, { color: theme.text.secondary, children: t("Type to search \xB7 Enter to commit \xB7 Esc to clear") }) : /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(import_jsx_runtime52.Fragment, { children: [
              currentBranch && /* @__PURE__ */ (0, import_jsx_runtime52.jsxs)(Text, { color: theme.text.secondary, children: [
                /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(
                  Text,
                  {
                    bold: picker.filterByBranch,
                    color: picker.filterByBranch ? theme.text.accent : void 0,
                    children: "Ctrl+B"
                  }
                ),
                t(" to toggle branch \xB7 ")
              ] }),
              enablePreview && /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text, { color: theme.text.secondary, children: t("Space to preview \xB7 ") }),
              enableMultiSelect && (() => {
                let committableCheckedCount = 0;
                for (const id of picker.checkedIds) {
                  if (!picker.disabledIdSet.has(id)) {
                    committableCheckedCount++;
                  }
                }
                return /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text, { color: theme.text.secondary, children: committableCheckedCount > 0 ? t("Space to toggle \xB7 {{count}} selected \xB7 ", {
                  count: String(committableCheckedCount)
                }) : t("Space to select multiple \xB7 ") });
              })(),
              /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(Text, { color: theme.text.secondary, children: t("\u2191\u2193 to navigate \xB7 Type to search \xB7 Esc to cancel") })
            ] }) }) })
          ]
        }
      )
    }
  );
}
__name(SessionPicker, "SessionPicker");

export {
  ConfigContext,
  useConfig,
  truncateText,
  removeLastGrapheme,
  isDeletionKey,
  isPrintableSearchChar,
  loadLowlight,
  colorizeCode,
  sanitizeForOsc,
  osc8Hyperlink,
  supportsHyperlinks,
  TerminalOutputProvider,
  useTerminalOutput,
  RenderModeProvider,
  countMarkdownSourceBlocks,
  MarkdownDisplay,
  SCREEN_READER_USER_PREFIX,
  getArenaStatusLabel,
  TOOL_SUCCESS_RATE_HIGH,
  TOOL_SUCCESS_RATE_MEDIUM,
  USER_AGREEMENT_RATE_HIGH,
  USER_AGREEMENT_RATE_MEDIUM,
  getStatusColor,
  formatDuration2 as formatDuration,
  THINKING_ICON,
  DiffRenderer,
  keyMatchers,
  useSelectionList,
  BaseSelectionList,
  RadioButtonSelect,
  checkExhaustive,
  logicalPosToOffset,
  useTextBuffer,
  usePreferredEditor,
  renderSoftwareCursor,
  TextInput,
  ToolConfirmationMessage,
  build_default,
  StreamingContext,
  useStreamingContext,
  GeminiRespondingSpinner,
  GeminiSpinner,
  dist_default,
  AboutBox,
  dist_default2,
  getRenderableGradientColors,
  Help,
  useHistory,
  IdeIntegrationNudge,
  CommandFormatMigrationNudge,
  FolderTrustDialog,
  MCPServerApprovalDialog,
  useArenaCommand,
  UIActionsContext,
  useUIActions,
  useIdeTrustListener,
  useProviderUpdates,
  UIStateContext,
  useUIState,
  initialExtensionUpdatesState,
  extensionUpdatesReducer,
  BtwMessage,
  ThoughtExpandedProvider,
  ThinkingViewerProvider,
  HistoryItemDisplayComponent,
  SessionPicker
};
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * @license
 * Copyright 2025 Qwen Code
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * @license
 * Copyright 2025 Qwen
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * @license
 * Copyright 2026 Qwen Team
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * @license
 * Copyright 2025 Qwen Team
 * SPDX-License-Identifier: Apache-2.0
 */
