<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<script>
window.__engineErrors = [];
window.onerror = function(msg) {
  // Why: a degraded engine can throw per frame; cap so the capture buffer
  // and downstream reporting stay bounded for the document's lifetime.
  if (window.__engineErrors.length < 20) window.__engineErrors.push(String(msg));
};
</script>
<style>__ORCA_TERMINAL_ENGINE_CSS__</style>
<style>
  * { margin: 0; padding: 0; box-sizing: border-box; }
  html, body {
    background: #1a1b26;
    overflow: hidden;
    width: 100%;
    height: 100%;
  }
  #terminal-container {
    overflow: hidden;
    position: relative;
    width: 100%;
    height: 100%;
  }
  #terminal-surface {
    transform-origin: top left;
    display: inline-block;
  }
  .xterm { -webkit-user-select: none; user-select: none; font-variant-emoji: text; }
  .xterm .xterm-viewport {
    overflow-y: hidden !important;
    scrollbar-width: none !important;
    -ms-overflow-style: none;
  }
  .xterm .xterm-viewport::-webkit-scrollbar {
    display: none !important;
    width: 0 !important;
    height: 0 !important;
    background: transparent !important;
  }
  .xterm .xterm-scrollable-element > .xterm-scrollbar,
  .xterm .xterm-scrollbar {
    display: none !important;
    width: 0 !important;
    opacity: 0 !important;
    pointer-events: none !important;
  }
  #scroll-indicator {
    position: fixed;
    top: 4px;
    right: 3px;
    bottom: 4px;
    width: 3px;
    pointer-events: none;
    opacity: 0;
    transition: opacity 120ms linear;
    z-index: 7;
  }
  #scroll-indicator.visible { opacity: 0.72; }
  #scroll-thumb {
    position: absolute;
    top: 0;
    right: 0;
    width: 3px;
    min-height: 24px;
    border-radius: 999px;
    background: #a1a1a1;
    will-change: transform, height;
  }
  /* Why: selection overlay sits in unscaled viewport coords, above the
     transformed surface, so handle hit areas and Copy menu positions
     don't depend on getTotalScale() for their on-screen size. */
  #selection-overlay {
    position: fixed;
    top: 0; left: 0; right: 0; bottom: 0;
    pointer-events: none;
    z-index: 10;
    display: none;
  }
  #selection-overlay.active { display: block; }
  .sel-handle {
    position: absolute;
    width: 44px; height: 44px;
    margin-left: -22px; margin-top: -22px;
    pointer-events: auto;
    background: transparent;
  }
  .sel-handle::before {
    content: '';
    position: absolute;
    left: 50%; top: 22px;
    transform: translateX(-50%);
    width: 14px; height: 14px;
    background: #7aa2f7;
    border-radius: 50%;
    border: 2px solid #c0caf5;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.5);
  }
  .sel-handle.start::before { top: 8px; }
  .sel-handle.start::after {
    content: '';
    position: absolute;
    left: 50%; top: 22px;
    transform: translateX(-50%);
    width: 2px; height: 16px;
    background: #7aa2f7;
  }
  .sel-handle.end::before { top: 22px; }
  .sel-handle.end::after {
    content: '';
    position: absolute;
    left: 50%; top: 6px;
    transform: translateX(-50%);
    width: 2px; height: 16px;
    background: #7aa2f7;
  }
  #sel-menu {
    position: absolute;
    pointer-events: auto;
    background: #2a2f4a;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.5);
    display: flex;
    overflow: hidden;
    transform: translateY(-100%);
    margin-top: -12px;
    user-select: none;
    -webkit-user-select: none;
  }
  #sel-menu button {
    background: transparent;
    border: none;
    color: #c0caf5;
    font: 600 13px -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
    padding: 10px 16px;
    cursor: pointer;
  }
  #sel-menu button:active { background: #414868; }
  #sel-menu button + button { border-left: 1px solid #414868; }
</style>
</head>
<body>
<div id="terminal-container">
  <div id="terminal-surface"></div>
</div>
<div id="scroll-indicator"><div id="scroll-thumb"></div></div>
<div id="selection-overlay">
  <div id="sel-handle-start" class="sel-handle start"></div>
  <div id="sel-handle-end" class="sel-handle end"></div>
  <div id="sel-menu">
    <button id="sel-menu-copy">Copy</button>
    <button id="sel-menu-all">Select All</button>
  </div>
</div>
<script>__ORCA_TERMINAL_ENGINE_JS__</script>
<script>
(function() {
  const textScalePresets = [0.5, 0.75, 1, 1.25, 1.5, 2];
  const statusDot = String.fromCharCode(9210);
  const textPresentationSelector = String.fromCharCode(65038);
  const emojiPresentationSelector = String.fromCharCode(65039);
  function createTerminalDocumentScope() {
    return {
      term: null,
      panX: 0,
      panY: 0,
      terminalGeneration: 0,
      termObserverDisposables: [],
      initRows: 24,
      webglAddon: null,
      webglRecoveryTimer: null,
      terminalThemeInput: null,
      defaultTheme: { "background": "#1a1b26", "foreground": "#c0caf5", "cursor": "#c0caf5", "cursorAccent": "#1a1b26", "selectionBackground": "#33467c", "selectionForeground": "#c0caf5", "black": "#15161e", "red": "#f7768e", "green": "#9ece6a", "yellow": "#e0af68", "blue": "#7aa2f7", "magenta": "#bb9af7", "cyan": "#7dcfff", "white": "#a9b1d6", "brightBlack": "#414868", "brightRed": "#f7768e", "brightGreen": "#9ece6a", "brightYellow": "#e0af68", "brightBlue": "#7aa2f7", "brightMagenta": "#bb9af7", "brightCyan": "#7dcfff", "brightWhite": "#c0caf5" },
      terminalTheme: { "background": "#1a1b26", "foreground": "#c0caf5", "cursor": "#c0caf5", "cursorAccent": "#1a1b26", "selectionBackground": "#33467c", "selectionForeground": "#c0caf5", "black": "#15161e", "red": "#f7768e", "green": "#9ece6a", "yellow": "#e0af68", "blue": "#7aa2f7", "magenta": "#bb9af7", "cyan": "#7dcfff", "white": "#a9b1d6", "brightBlack": "#414868", "brightRed": "#f7768e", "brightGreen": "#9ece6a", "brightYellow": "#e0af68", "brightBlue": "#7aa2f7", "brightMagenta": "#bb9af7", "brightCyan": "#7dcfff", "brightWhite": "#c0caf5" },
      terminalMinimumContrastRatio: 3,
      initialOscLinks: [],
      initialOscLinkRowOffset: 0,
      ESC: String.fromCharCode(27),
      lastEmittedModes: {
        bracketedPasteMode: false,
        altScreen: false,
        mouseTrackingMode: "none",
        sgrMouseMode: false,
        sgrMousePixelsMode: false
      },
      everReady: false,
      C1_CSI: String.fromCharCode(155),
      mouseModeScanTail: "",
      trackedMouseTrackingMode: "none",
      sgrMouseMode: false,
      sgrMousePixelsMode: false,
      scrollIndicatorHideTimer: null,
      MIN_FIT_COLS: 20,
      MIN_TEXT_SCALE: textScalePresets[0],
      MAX_TEXT_SCALE: textScalePresets[textScalePresets.length - 1],
      handledMessageIds: [],
      currentTextScale: 1,
      terminalFontFamily: "",
      firstDataPending: true,
      activeAltScreenSnapshot: false,
      currentScale: 1,
      userScale: 1,
      CLAUDE_STATUS_DOT: statusDot,
      TEXT_PRESENTATION_SELECTOR: textPresentationSelector,
      EMOJI_PRESENTATION_SELECTOR: emojiPresentationSelector,
      CLAUDE_STATUS_DOT_PATTERN: new RegExp(
        statusDot + "[" + textPresentationSelector + emojiPresentationSelector + "]*",
        "g"
      ),
      statusDotPendingSelector: false,
      PRIVATE_MODE_SCAN_TAIL_LIMIT: 4096,
      writeQueue: [],
      writeQueueHead: 0,
      writesDraining: false,
      afterDrainCallbacks: [],
      ready: false,
      smoothScrollOffsetY: 0,
      pendingNormalScrollDeltaY: 0,
      normalScrollFrameId: null,
      WORD_RE: /[\p{L}\p{N}_./:@~+=?&#%-]/u,
      EDGE_SCROLL_PX: 40,
      EDGE_SCROLL_INTERVAL: 60,
      selMenu: null,
      btnCopy: null,
      btnSelAll: null,
      edgeScrollTimer: null,
      edgeScrollDir: 0,
      edgeScrollClientX: 0,
      edgeScrollClientY: 0,
      initialOscLinkEvictionReady: false,
      LONG_PRESS_MS: 500,
      LONG_PRESS_SLOP: 10,
      TAP_SLOP: 24,
      TAP_MAX_MS: 700,
      selectionOverlay: null,
      handleStart: null,
      handleEnd: null,
      selMode: "navigate",
      sel: null,
      longPressTimer: null,
      longPressOrigin: null,
      tapCandidate: null,
      wheelAccumDeltaY: 0,
      surface: null,
      pendingTerm: null
    };
  }
  const scope = createTerminalDocumentScope();
  scope.surface = document.getElementById("terminal-surface");
  scope.ESC = String.fromCharCode(27);
  scope.C1_CSI = String.fromCharCode(155);
  scope.CLAUDE_STATUS_DOT = String.fromCharCode(9210);
  scope.TEXT_PRESENTATION_SELECTOR = String.fromCharCode(65038);
  scope.EMOJI_PRESENTATION_SELECTOR = String.fromCharCode(65039);
  scope.CLAUDE_STATUS_DOT_PATTERN = new RegExp(
    scope.CLAUDE_STATUS_DOT + "[" + scope.TEXT_PRESENTATION_SELECTOR + scope.EMOJI_PRESENTATION_SELECTOR + "]*",
    "g"
  );
  scope.statusDotPendingSelector = false;
  scope.PRIVATE_MODE_SCAN_TAIL_LIMIT = 4096;
  scope.term = null;
  let terminalDataRepliesEnabled = false;
  function resetTerminalDataReplyAuthority() {
    terminalDataRepliesEnabled = false;
  }
  function resumeTerminalDataReplyAuthority() {
    terminalDataRepliesEnabled = true;
  }
  function forwardTerminalDataReply(data) {
    if (terminalDataRepliesEnabled) {
      notify({ type: "terminal-data", bytes: data });
    }
  }
  function enqueueTerminalDataReplyBoundary(gen) {
    enqueueWriteBoundary(function() {
      if (gen === scope.terminalGeneration) {
        terminalDataRepliesEnabled = true;
      }
    });
  }
  function attachTerminalQueryReplyBridge(term, gen) {
    try {
      term.attachCustomKeyEventHandler(function() {
        return false;
      });
      if (term.textarea) {
        term.textarea.readOnly = true;
        term.textarea.tabIndex = -1;
        term.textarea.setAttribute("inputmode", "none");
      }
    } catch {
    }
    try {
      scope.termObserverDisposables.push(
        term.onData(function(data) {
          forwardTerminalDataReply(data);
        })
      );
    } catch {
    }
    enqueueTerminalDataReplyBoundary(gen);
  }
  let committedTerm = null;
  let committedSurface = scope.surface;
  scope.pendingTerm = null;
  let pendingSurface = null;
  function beginTerminalSurfaceSwap() {
    if (pendingSurface) {
      try {
        pendingSurface.remove();
      } catch {
      }
      if (scope.pendingTerm) {
        try {
          scope.pendingTerm.dispose();
        } catch {
        }
      }
      pendingSurface = null;
      scope.pendingTerm = null;
    }
    const swap = {
      oldTerm: committedTerm,
      oldSurface: committedSurface,
      nextSurface: document.createElement("div")
    };
    disposeTermObservers();
    swap.nextSurface.id = "terminal-surface";
    swap.nextSurface.style.visibility = "hidden";
    swap.nextSurface.style.position = "absolute";
    swap.nextSurface.style.left = "0";
    swap.nextSurface.style.top = "0";
    document.getElementById("terminal-container").appendChild(swap.nextSurface);
    scope.surface = swap.nextSurface;
    pendingSurface = swap.nextSurface;
    attachSurfaceEventHandlers(scope.surface);
    swap.oldSurface.removeAttribute("id");
    return swap;
  }
  function commitTerminalSurfaceSwap(swap, nextTerm) {
    swap.nextSurface.style.visibility = "visible";
    swap.nextSurface.style.position = "";
    swap.nextSurface.style.left = "";
    swap.nextSurface.style.top = "";
    swap.oldSurface.remove();
    if (swap.oldTerm) {
      swap.oldTerm.dispose();
    }
    committedTerm = nextTerm;
    committedSurface = swap.nextSurface;
    scope.pendingTerm = null;
    pendingSurface = null;
  }
  const scrollIndicator = document.getElementById("scroll-indicator");
  const scrollThumb = document.getElementById("scroll-thumb");
  scope.scrollIndicatorHideTimer = null;
  scope.writeQueue = [];
  scope.writeQueueHead = 0;
  scope.writesDraining = false;
  scope.afterDrainCallbacks = [];
  scope.termObserverDisposables = [];
  scope.ready = false;
  scope.everReady = false;
  scope.currentScale = 1;
  scope.userScale = 1;
  const BASE_FONT_PX = 13;
  const MIN_FONT_PX = 6;
  scope.MIN_FIT_COLS = 20;
  scope.currentTextScale = 1;
  const TEXT_SCALE_PRESETS = [0.5, 0.75, 1, 1.25, 1.5, 2];
  scope.MIN_TEXT_SCALE = TEXT_SCALE_PRESETS[0];
  scope.MAX_TEXT_SCALE = TEXT_SCALE_PRESETS[TEXT_SCALE_PRESETS.length - 1];
  function snapToTextScalePreset(value) {
    let best = TEXT_SCALE_PRESETS[0], bestDelta = Infinity;
    for (let i = 0; i < TEXT_SCALE_PRESETS.length; i++) {
      const delta = Math.abs(TEXT_SCALE_PRESETS[i] - value);
      if (delta < bestDelta) {
        bestDelta = delta;
        best = TEXT_SCALE_PRESETS[i];
      }
    }
    return best;
  }
  function fontPxForScale(scale) {
    return Math.max(MIN_FONT_PX, Math.round(BASE_FONT_PX * scale));
  }
  function isIOSWebView() {
    if (/iP(ad|hone|od)/.test(navigator.userAgent)) {
      return true;
    }
    return navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1;
  }
  const TERMINAL_FONT_FALLBACKS = '"Menlo", "Monaco", "Cascadia Mono", "Consolas", "DejaVu Sans Mono", "Liberation Mono", "Symbols Nerd Font Mono", monospace';
  scope.terminalFontFamily = (isIOSWebView() ? "ui-monospace, " : '"SF Mono", ') + TERMINAL_FONT_FALLBACKS;
  function applyTextScale(scale) {
    scope.currentTextScale = scale;
    if (!scope.term) {
      return;
    }
    const px = fontPxForScale(scale);
    if (scope.term.options.fontSize === px) {
      return;
    }
    scope.term.options.fontSize = px;
    requestAnimationFrame(function() {
      if (!scope.term) {
        return;
      }
      const cellW = getCellWidth();
      const cellH = getCellHeight();
      if (cellW > 0 && cellH > 0) {
        const cols = Math.floor(window.innerWidth / cellW);
        if (cols < scope.MIN_FIT_COLS) {
          return;
        }
        const rows = Math.max(8, Math.floor(window.innerHeight / cellH));
        scope.term.resize(cols, rows);
        emitKeyboardAvoidanceMetrics();
      }
      applyFitScale("text-scale");
    });
  }
  scope.panX = 0;
  scope.panY = 0;
  scope.smoothScrollOffsetY = 0;
  scope.pendingNormalScrollDeltaY = 0;
  scope.normalScrollFrameId = null;
  scope.initRows = 24;
  scope.terminalGeneration = 0;
  scope.defaultTheme = { "background": "#1a1b26", "foreground": "#c0caf5", "cursor": "#c0caf5", "cursorAccent": "#1a1b26", "selectionBackground": "#33467c", "selectionForeground": "#c0caf5", "black": "#15161e", "red": "#f7768e", "green": "#9ece6a", "yellow": "#e0af68", "blue": "#7aa2f7", "magenta": "#bb9af7", "cyan": "#7dcfff", "white": "#a9b1d6", "brightBlack": "#414868", "brightRed": "#f7768e", "brightGreen": "#9ece6a", "brightYellow": "#e0af68", "brightBlue": "#7aa2f7", "brightMagenta": "#bb9af7", "brightCyan": "#7dcfff", "brightWhite": "#c0caf5" };
  scope.terminalThemeInput = null;
  scope.terminalTheme = scope.defaultTheme;
  scope.terminalMinimumContrastRatio = 3;
  scope.webglAddon = null;
  scope.webglRecoveryTimer = null;
  scope.activeAltScreenSnapshot = false;
  scope.trackedMouseTrackingMode = "none";
  scope.sgrMouseMode = false;
  scope.sgrMousePixelsMode = false;
  scope.initialOscLinks = [];
  scope.initialOscLinkRowOffset = 0;
  scope.initialOscLinkEvictionReady = false;
  scope.mouseModeScanTail = "";
  scope.handledMessageIds = [];
  scope.firstDataPending = false;
  function flog(tag, payload) {
    try {
      if (window.ReactNativeWebView) {
        window.ReactNativeWebView.postMessage(
          JSON.stringify({
            type: "log",
            tag: "[fit]" + tag,
            payload
          })
        );
      }
    } catch {
    }
  }
  function getCellWidth() {
    if (!scope.term || !scope.term._core) {
      return 0;
    }
    const core = scope.term._core;
    if (core._renderService && core._renderService.dimensions) {
      return core._renderService.dimensions.css.cell.width || 0;
    }
    return 0;
  }
  function computeFitScale() {
    if (!scope.term) {
      return 1;
    }
    const cellW = getCellWidth();
    const termWidth = cellW > 0 ? cellW * scope.term.cols : scope.term.element ? scope.term.element.scrollWidth : 0;
    if (termWidth <= 0) {
      return 1;
    }
    const vpWidth = window.innerWidth;
    return Math.min(1, vpWidth / termWidth);
  }
  function getTotalScale() {
    return scope.currentScale * scope.userScale;
  }
  function updateTransform() {
    scope.surface.style.transform = "translate(" + scope.panX + "px," + scope.panY + "px) scale(" + getTotalScale() + ")";
    updateScrollIndicator(false);
    if (scope.selMode === "select") {
      repositionOverlay();
    }
  }
  function updateScrollIndicator(reveal) {
    if (!scrollIndicator || !scrollThumb || !scope.term || !scope.term.buffer || !scope.term.buffer.active) {
      return;
    }
    const buffer = scope.term.buffer.active;
    const maxViewportY = buffer.baseY || 0;
    if (maxViewportY <= 0 || shouldRouteScrollToTerminalInput()) {
      scrollIndicator.classList.remove("visible");
      return;
    }
    const trackHeight = Math.max(0, window.innerHeight - 8);
    const totalRows = maxViewportY + (scope.term.rows || 0);
    if (trackHeight <= 0 || totalRows <= 0) {
      return;
    }
    const thumbHeight = Math.max(24, trackHeight * (scope.term.rows || 0) / totalRows);
    const maxTop = Math.max(0, trackHeight - thumbHeight);
    const top = maxViewportY > 0 ? buffer.viewportY / maxViewportY * maxTop : 0;
    scrollThumb.style.height = thumbHeight + "px";
    scrollThumb.style.transform = "translateY(" + top + "px)";
    if (!reveal) {
      return;
    }
    scrollIndicator.classList.add("visible");
    if (scope.scrollIndicatorHideTimer) {
      clearTimeout(scope.scrollIndicatorHideTimer);
    }
    scope.scrollIndicatorHideTimer = setTimeout(function() {
      scrollIndicator.classList.remove("visible");
      scope.scrollIndicatorHideTimer = null;
    }, 550);
  }
  const DARK_BG_MIN_CONTRAST = 3;
  const LIGHT_BG_MIN_CONTRAST = 4.5;
  const CONTRAST_APP_SURFACE = { r: 10, g: 10, b: 10 };
  function parseTerminalBackgroundRgba(value) {
    if (typeof value !== "string") {
      return null;
    }
    const v = value.trim().toLowerCase();
    if (!v) {
      return null;
    }
    if (v === "black") {
      return { r: 0, g: 0, b: 0, a: 1 };
    }
    if (v === "white") {
      return { r: 255, g: 255, b: 255, a: 1 };
    }
    if (v === "transparent") {
      return { r: 0, g: 0, b: 0, a: 0 };
    }
    const hex = v.match(/^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/);
    if (hex) {
      const h = hex[1];
      let ch;
      if (h.length === 3 || h.length === 4) {
        ch = h.split("").map(function(p) {
          return Number.parseInt(p + p, 16);
        });
      } else {
        ch = [];
        for (let i = 0; i < h.length; i += 2) {
          ch.push(Number.parseInt(h.slice(i, i + 2), 16));
        }
      }
      return { r: ch[0], g: ch[1], b: ch[2], a: ch[3] === void 0 ? 1 : ch[3] / 255 };
    }
    const rgb = v.match(/^rgba?\(([^)]+)\)$/);
    if (!rgb) {
      return null;
    }
    let parts = rgb[1].indexOf(",") >= 0 ? rgb[1].split(",") : rgb[1].split(/[\s/]+/);
    parts = parts.map(function(p) {
      return p.trim();
    }).filter(function(p) {
      return p.length > 0;
    });
    if (parts.length < 3) {
      return null;
    }
    const channel = function(p) {
      const n = p.charAt(p.length - 1) === "%" ? Number.parseFloat(p) / 100 * 255 : Number.parseFloat(p);
      return Number.isFinite(n) ? Math.min(255, Math.max(0, Math.round(n))) : null;
    };
    const r = channel(parts[0]), g = channel(parts[1]), b = channel(parts[2]);
    if (r === null || g === null || b === null) {
      return null;
    }
    let a = 1;
    if (parts[3] !== void 0) {
      const raw = parts[3].charAt(parts[3].length - 1) === "%" ? Number.parseFloat(parts[3]) / 100 : Number.parseFloat(parts[3]);
      a = Number.isFinite(raw) ? Math.min(1, Math.max(0, raw)) : 1;
    }
    return { r, g, b, a };
  }
  function terminalRelativeLuminance(rgb) {
    const lin = function(c) {
      const n = c / 255;
      return n <= 0.03928 ? n / 12.92 : Math.pow((n + 0.055) / 1.055, 2.4);
    };
    return 0.2126 * lin(rgb.r) + 0.7152 * lin(rgb.g) + 0.0722 * lin(rgb.b);
  }
  function terminalContrastRatio(a, b) {
    const la = terminalRelativeLuminance(a), lb = terminalRelativeLuminance(b);
    return (Math.max(la, lb) + 0.05) / (Math.min(la, lb) + 0.05);
  }
  function normalizeTerminalContrastOverride(value) {
    if (typeof value !== "number" || !Number.isFinite(value)) {
      return null;
    }
    return Math.min(21, Math.max(1, value));
  }
  function resolveTerminalContrastFloor(background) {
    const color = parseTerminalBackgroundRgba(background);
    if (!color) {
      return DARK_BG_MIN_CONTRAST;
    }
    const composited = color.a < 1 ? {
      r: Math.round(color.r * color.a + CONTRAST_APP_SURFACE.r * (1 - color.a)),
      g: Math.round(color.g * color.a + CONTRAST_APP_SURFACE.g * (1 - color.a)),
      b: Math.round(color.b * color.a + CONTRAST_APP_SURFACE.b * (1 - color.a))
    } : color;
    const isLight = terminalContrastRatio({ r: 0, g: 0, b: 0 }, composited) >= terminalContrastRatio({ r: 255, g: 255, b: 255 }, composited);
    return isLight ? LIGHT_BG_MIN_CONTRAST : DARK_BG_MIN_CONTRAST;
  }
  function normalizeTerminalTheme(input) {
    const source = input && typeof input === "object" && input.theme && typeof input.theme === "object" ? input.theme : null;
    if (!source) {
      return scope.defaultTheme;
    }
    const next = {};
    const keys = Object.keys(scope.defaultTheme);
    for (let i = 0; i < keys.length; i++) {
      const key = keys[i];
      if (typeof source[key] === "string") {
        next[key] = source[key];
      }
    }
    return Object.assign({}, scope.defaultTheme, next);
  }
  function applyTerminalTheme(input) {
    scope.terminalThemeInput = input;
    scope.terminalTheme = normalizeTerminalTheme(input);
    const background = scope.terminalTheme.background || "#1a1b26";
    document.documentElement.style.background = background;
    document.body.style.background = background;
    const publishedFloor = normalizeTerminalContrastOverride(
      input && typeof input === "object" ? input.minimumContrastRatio : void 0
    );
    scope.terminalMinimumContrastRatio = publishedFloor === null ? resolveTerminalContrastFloor(background) : publishedFloor;
    if (scope.term) {
      scope.term.options.theme = scope.terminalTheme;
      scope.term.options.minimumContrastRatio = scope.terminalMinimumContrastRatio;
    }
  }
  function getCellHeight() {
    if (!scope.term || !scope.term._core) {
      return 15;
    }
    const core = scope.term._core;
    if (core._renderService && core._renderService.dimensions) {
      return core._renderService.dimensions.css.cell.height || 15;
    }
    return 15;
  }
  function clampPan() {
    if (!scope.term || !scope.term.element) {
      return;
    }
    const ts = getTotalScale();
    const cw = scope.term.element.scrollWidth * ts;
    const ch = scope.term.element.scrollHeight * ts;
    const vpW = window.innerWidth;
    const vpH = window.innerHeight;
    if (cw > vpW) {
      scope.panX = Math.min(0, Math.max(vpW - cw, scope.panX));
    } else {
      scope.panX = 0;
    }
    if (ch > vpH) {
      scope.panY = Math.min(0, Math.max(vpH - ch, scope.panY));
    } else {
      scope.panY = 0;
    }
  }
  function adjustRowsForViewport() {
  }
  const FIT_RETRY_MAX_FRAMES = 60;
  let fitRetryToken = 0;
  function applyFitScale(reason) {
    if (!scope.term || !scope.term.element) {
      return;
    }
    const token = ++fitRetryToken;
    let attempts = 0;
    let lastScrollWidth = -1;
    function attempt() {
      if (token !== fitRetryToken) {
        return;
      }
      if (!scope.term || !scope.term.element) {
        return;
      }
      attempts++;
      const cellW = getCellWidth();
      if (cellW > 0 && scope.term.cols > 0) {
        commitFitScale(reason, attempts, "cellW");
        return;
      }
      const w = scope.term.element.scrollWidth;
      if (w > 0 && w === lastScrollWidth) {
        commitFitScale(reason, attempts, "stableSW");
        return;
      }
      lastScrollWidth = w;
      if (attempts >= FIT_RETRY_MAX_FRAMES) {
        flog("commit-timeout", {
          reason,
          attempts,
          cellW,
          scrollWidth: w,
          cols: scope.term.cols
        });
        commitFitScale(reason, attempts, "timeout");
        return;
      }
      requestAnimationFrame(attempt);
    }
    requestAnimationFrame(attempt);
  }
  function commitFitScale(reason, attempts, gate) {
    if (!scope.term || !scope.term.element) {
      return;
    }
    const preSnapScale = computeFitScale();
    scope.currentScale = preSnapScale;
    if (scope.currentScale >= 0.95) {
      scope.currentScale = 1;
    }
    scope.userScale = 1;
    scope.panX = 0;
    scope.panY = 0;
    scope.smoothScrollOffsetY = 0;
    updateTransform();
    adjustRowsForViewport();
    const cellW = getCellWidth();
    const sw = scope.term.element.scrollWidth;
    const vpW = window.innerWidth;
    const expectedW = cellW * scope.term.cols;
    const suspect = scope.currentScale === 1 && scope.term.cols > 0 && expectedW > vpW + 1;
    if (suspect) {
      flog("commit-SUSPECT", {
        reason,
        attempts,
        gate,
        preSnapScale,
        finalScale: scope.currentScale,
        cellW,
        cols: scope.term.cols,
        expectedW,
        scrollWidth: sw,
        vpWidth: vpW
      });
    }
    repositionOverlay();
  }
  function isAltScreenActive(data) {
    if (typeof data !== "string") {
      return false;
    }
    const on = data.lastIndexOf(scope.ESC + "[?1049h");
    const off = data.lastIndexOf(scope.ESC + "[?1049l");
    return on !== -1 && on > off;
  }
  function normalizeInitialData(data) {
    if (!isAltScreenActive(data)) {
      return data;
    }
    const on = data.lastIndexOf(scope.ESC + "[?1049h");
    return on > 0 ? data.slice(on) : data;
  }
  function updateMouseModeFromData(data) {
    if (typeof data !== "string" || data.length === 0) {
      return;
    }
    const input = scope.mouseModeScanTail + data;
    scope.mouseModeScanTail = extractMouseModeScanTail(input);
    const re = new RegExp(
      scope.ESC + "c|" + scope.ESC + "\\[\\?([0-9;]+)([hl])|" + scope.C1_CSI + "\\?([0-9;]+)([hl])",
      "g"
    );
    let match;
    while ((match = re.exec(input)) !== null) {
      if (match[0] === scope.ESC + "c") {
        scope.trackedMouseTrackingMode = "none";
        scope.sgrMouseMode = false;
        scope.sgrMousePixelsMode = false;
        continue;
      }
      const enabled = (match[2] || match[4]) === "h";
      const params = (match[1] || match[3]).split(";");
      for (let i = 0; i < params.length; i++) {
        if (params[i] === "") {
          continue;
        }
        const param = Number(params[i]);
        if (!Number.isInteger(param)) {
          continue;
        }
        if (param === 9) {
          scope.trackedMouseTrackingMode = enabled ? "x10" : "none";
        }
        if (param === 1e3) {
          scope.trackedMouseTrackingMode = enabled ? "vt200" : "none";
        }
        if (param === 1002) {
          scope.trackedMouseTrackingMode = enabled ? "drag" : "none";
        }
        if (param === 1003) {
          scope.trackedMouseTrackingMode = enabled ? "any" : "none";
        }
        if (param === 1006) {
          scope.sgrMouseMode = enabled;
          scope.sgrMousePixelsMode = false;
        }
        if (param === 1016) {
          scope.sgrMouseMode = false;
          scope.sgrMousePixelsMode = enabled;
        }
      }
    }
  }
  function resetWriteQueue() {
    scope.writeQueue = [];
    scope.writeQueueHead = 0;
  }
  function isStatusDotPresentationSelector(value) {
    return value === scope.TEXT_PRESENTATION_SELECTOR || value === scope.EMOJI_PRESENTATION_SELECTOR;
  }
  function endsWithStatusDotPresentationSequence(data) {
    let i = data.length - 1;
    while (i >= 0 && isStatusDotPresentationSelector(data.charAt(i))) {
      i--;
    }
    return i >= 0 && data.charAt(i) === scope.CLAUDE_STATUS_DOT;
  }
  function normalizeStatusDotPresentation(data) {
    if (typeof data !== "string" || data.length === 0) {
      return data;
    }
    if (scope.statusDotPendingSelector) {
      scope.statusDotPendingSelector = false;
      let strippedPendingSelectors = false;
      while (data.length > 0 && isStatusDotPresentationSelector(data.charAt(0))) {
        data = data.slice(1);
      }
      strippedPendingSelectors = data.length === 0;
      if (strippedPendingSelectors) {
        scope.statusDotPendingSelector = true;
        return "";
      }
    }
    const normalized = data.replace(
      scope.CLAUDE_STATUS_DOT_PATTERN,
      scope.CLAUDE_STATUS_DOT + scope.TEXT_PRESENTATION_SELECTOR
    );
    scope.statusDotPendingSelector = endsWithStatusDotPresentationSequence(data);
    return normalized;
  }
  function enqueueWrite(data) {
    scope.writeQueue.push(normalizeStatusDotPresentation(data));
  }
  function enqueueWriteBoundary(callback) {
    scope.writeQueue.push(callback);
  }
  function nextQueuedWrite() {
    if (scope.writeQueueHead >= scope.writeQueue.length) {
      resetWriteQueue();
      return void 0;
    }
    const next = scope.writeQueue[scope.writeQueueHead];
    scope.writeQueue[scope.writeQueueHead] = void 0;
    scope.writeQueueHead++;
    if (scope.writeQueueHead > 128 && scope.writeQueueHead * 2 > scope.writeQueue.length) {
      scope.writeQueue = scope.writeQueue.slice(scope.writeQueueHead);
      scope.writeQueueHead = 0;
    }
    return next;
  }
  function disposeTermObservers() {
    const disposables = scope.termObserverDisposables;
    scope.termObserverDisposables = [];
    for (let i = 0; i < disposables.length; i++) {
      try {
        disposables[i] && disposables[i].dispose && disposables[i].dispose();
      } catch {
      }
    }
  }
  function extractMouseModeScanTail(input) {
    const start = Math.max(input.lastIndexOf(scope.ESC), input.lastIndexOf(scope.C1_CSI));
    if (start === -1) {
      return "";
    }
    const tail = input.slice(start);
    if (tail.length > scope.PRIVATE_MODE_SCAN_TAIL_LIMIT) {
      return "";
    }
    if (tail === scope.ESC || tail === scope.ESC + "[" || tail === scope.C1_CSI) {
      return tail;
    }
    if (tail.indexOf(scope.ESC + "[?") === 0) {
      return /^[0-9;]*$/.test(tail.slice(3)) ? tail : "";
    }
    if (tail.indexOf(scope.C1_CSI + "?") === 0) {
      return /^[0-9;]*$/.test(tail.slice(2)) ? tail : "";
    }
    return "";
  }
  function pumpWrites(gen) {
    if (!scope.ready || !scope.term || scope.writesDraining || gen !== scope.terminalGeneration) {
      return;
    }
    const next = nextQueuedWrite();
    if (typeof next !== "string") {
      if (typeof next === "function") {
        return next(), pumpWrites(gen);
      }
      const callbacks = scope.afterDrainCallbacks;
      scope.afterDrainCallbacks = [];
      for (let i = 0; i < callbacks.length; i++) {
        callbacks[i]();
      }
      return;
    }
    scope.writesDraining = true;
    scope.term.write(next, function() {
      if (gen !== scope.terminalGeneration) {
        return;
      }
      scope.writesDraining = false;
      pumpWrites(gen);
    });
  }
  function afterWritesDrained(callback) {
    scope.afterDrainCallbacks.push(callback);
    pumpWrites(scope.terminalGeneration);
  }
  function refreshTerminalSurface() {
    if (!scope.term) {
      return;
    }
    try {
      scope.term.refresh(0, Math.max(0, scope.term.rows - 1));
    } catch {
    }
  }
  function cancelWebglContextRecovery() {
    if (!scope.webglRecoveryTimer) {
      return;
    }
    clearTimeout(scope.webglRecoveryTimer);
    scope.webglRecoveryTimer = null;
  }
  function attachWebglAddon(allowRecovery) {
    if (!scope.term || !window.WebglAddon || !window.WebglAddon.WebglAddon) {
      return false;
    }
    let addon = null;
    try {
      addon = new window.WebglAddon.WebglAddon();
      scope.webglAddon = addon;
      if (addon.onContextLoss) {
        addon.onContextLoss(function() {
          if (scope.webglAddon !== addon) {
            return;
          }
          flog("webgl-context-loss", { retry: allowRecovery });
          scope.webglAddon = null;
          try {
            addon.dispose();
          } catch {
          }
          refreshTerminalSurface();
          if (!allowRecovery) {
            return;
          }
          cancelWebglContextRecovery();
          const recoveryTerm = scope.term;
          const recoveryGeneration = scope.terminalGeneration;
          scope.webglRecoveryTimer = setTimeout(function() {
            scope.webglRecoveryTimer = null;
            if (scope.term !== recoveryTerm || scope.terminalGeneration !== recoveryGeneration) {
              return;
            }
            attachWebglAddon(false);
          }, 100);
        });
      }
      scope.term.loadAddon(addon);
      if (!allowRecovery) {
        try {
          if (addon.clearTextureAtlas) {
            addon.clearTextureAtlas();
          }
        } catch {
        }
        refreshTerminalSurface();
      }
      return true;
    } catch (e) {
      flog("webgl-attach-failed", { retry: !allowRecovery, message: String(e) });
      if (scope.webglAddon === addon) {
        scope.webglAddon = null;
      }
      try {
        if (addon) {
          addon.dispose();
        }
      } catch {
      }
      refreshTerminalSurface();
      return false;
    }
  }
  document.addEventListener("visibilitychange", function() {
    if (document.visibilityState !== "visible") {
      return;
    }
    applyTerminalTheme(scope.terminalThemeInput);
    try {
      if (scope.webglAddon && scope.webglAddon.clearTextureAtlas) {
        scope.webglAddon.clearTextureAtlas();
      }
    } catch {
    }
    refreshTerminalSurface();
  });
  function init(cols, rows, initialData, nextTheme, nextFontScale, preserveScroll, nextOscLinks) {
    if (typeof nextFontScale === "number" && nextFontScale > 0) {
      scope.currentTextScale = nextFontScale;
    }
    const prevB = preserveScroll && scope.term && scope.term.buffer && scope.term.buffer.active ? scope.term.buffer.active : null;
    const scrollAnchorRows = prevB ? Math.max(0, (prevB.baseY || 0) - (prevB.viewportY || 0)) : -1;
    scope.terminalGeneration++;
    const gen = scope.terminalGeneration;
    resetTerminalDataReplyAuthority();
    cancelWebglContextRecovery();
    scope.webglAddon = null;
    scope.ready = false;
    resetWriteQueue();
    scope.statusDotPendingSelector = false;
    scope.writesDraining = false;
    scope.afterDrainCallbacks = [];
    scope.initRows = rows || 24;
    scope.firstDataPending = true;
    scope.smoothScrollOffsetY = 0;
    scope.wheelAccumDeltaY = 0;
    scope.mouseModeScanTail = "";
    scope.trackedMouseTrackingMode = "none";
    scope.sgrMouseMode = false;
    scope.sgrMousePixelsMode = false;
    scope.lastEmittedModes = {
      bracketedPasteMode: false,
      altScreen: false,
      mouseTrackingMode: "none",
      sgrMouseMode: false,
      sgrMousePixelsMode: false
    };
    const replayData = normalizeInitialData(initialData);
    updateMouseModeFromData(replayData);
    scope.activeAltScreenSnapshot = isAltScreenActive(replayData);
    scope.initialOscLinks = Array.isArray(nextOscLinks) ? nextOscLinks : [];
    scope.initialOscLinkRowOffset = 0;
    scope.initialOscLinkEvictionReady = false;
    const surfaceSwap = beginTerminalSurfaceSwap();
    const nextSurface = surfaceSwap.nextSurface;
    applyTerminalTheme(nextTheme);
    scope.term = new Terminal({
      cols: cols || 80,
      rows: rows || 24,
      theme: scope.terminalTheme,
      minimumContrastRatio: scope.terminalMinimumContrastRatio,
      fontFamily: scope.terminalFontFamily,
      fontSize: fontPxForScale(scope.currentTextScale),
      fontWeight: "300",
      fontWeightBold: "500",
      scrollback: 5e3,
      // Why: xterm suppresses parser-generated query replies when disableStdin
      // is true. Native accepts only validated reply grammars from onData.
      disableStdin: false,
      cursorBlink: false,
      cursorStyle: "bar",
      // Native TextInput owns focus; initialize xterm's otherwise-gated main-buffer caret.
      showCursorImmediately: true,
      // A full inactive cell remains visible under the terminal's phone-fit scale.
      cursorInactiveStyle: "block",
      convertEol: false,
      allowProposedApi: true
    });
    const nextTerm = scope.term;
    scope.pendingTerm = nextTerm;
    scope.term.open(scope.surface);
    attachWebglAddon(true);
    if (window.Unicode11Addon && window.Unicode11Addon.Unicode11Addon) {
      try {
        scope.term.loadAddon(new window.Unicode11Addon.Unicode11Addon());
        scope.term.unicode.activeVersion = "11";
      } catch {
      }
    }
    if (typeof replayData === "string" && replayData.length > 0) {
      enqueueWrite(scope.ESC + "[0m" + replayData);
    }
    resetEvictionCounter();
    cancelSelect();
    attachTermObservers();
    attachTerminalQueryReplyBridge(scope.term, gen);
    requestAnimationFrame(function() {
      if (gen !== scope.terminalGeneration) {
        return;
      }
      scope.ready = true;
      scope.everReady = true;
      afterWritesDrained(function() {
        if (gen !== scope.terminalGeneration) {
          return;
        }
        commitTerminalSurfaceSwap(surfaceSwap, nextTerm);
        if (scrollAnchorRows > 0 && scope.term && scope.term.buffer && scope.term.buffer.active) {
          try {
            scope.term.scrollToLine(
              Math.max(0, (scope.term.buffer.active.baseY || 0) - scrollAnchorRows)
            );
          } catch {
          }
        }
        captureInitialOscLinkTexts();
        scope.initialOscLinkRowOffset = 0;
        scope.initialOscLinkEvictionReady = true;
        applyFitScale("init-replay");
        notify({ type: "ready", cols, rows });
      });
    });
  }
  function write(data) {
    updateMouseModeFromData(data);
    enqueueWrite(data);
    pumpWrites(scope.terminalGeneration);
    if (scope.firstDataPending) {
      scope.firstDataPending = false;
      const gen = scope.terminalGeneration;
      afterWritesDrained(function() {
        if (gen !== scope.terminalGeneration) {
          return;
        }
        applyFitScale("first-data");
      });
    }
  }
  function resize(cols, rows) {
    if (!scope.term) {
      return;
    }
    scope.initRows = rows || scope.initRows;
    scope.term.resize(cols || scope.term.cols, rows || scope.term.rows);
    emitKeyboardAvoidanceMetrics();
    applyFitScale("resize-msg");
    notify({ type: "ready", cols, rows });
  }
  function reflow(cols, rows) {
    if (!scope.term || isAlternateBufferActive()) {
      return;
    }
    const nextCols = cols || scope.term.cols;
    const nextRows = rows || scope.term.rows;
    if (nextCols === scope.term.cols && nextRows === scope.term.rows) {
      return;
    }
    const buffer = scope.term.buffer.active;
    const wasAtBottom = buffer.viewportY >= buffer.baseY;
    const distanceFromBottom = buffer.baseY - buffer.viewportY;
    scope.initRows = nextRows;
    scope.term.resize(nextCols, nextRows);
    const rewrapped = scope.term.buffer.active;
    if (wasAtBottom) {
      scope.term.scrollToBottom();
    } else {
      scope.term.scrollLines(rewrapped.baseY - distanceFromBottom - rewrapped.viewportY);
    }
    applyFitScale("reflow-msg");
    updateScrollIndicator(false);
    emitKeyboardAvoidanceMetrics();
  }
  function notify(msg) {
    if (window.ReactNativeWebView) {
      window.ReactNativeWebView.postMessage(JSON.stringify(msg));
    }
  }
  function engineErrorText(err) {
    if (!err) {
      return "";
    }
    if (typeof err === "string") {
      return err;
    }
    if (err && typeof err.message === "string") {
      return err.message;
    }
    try {
      return String(err);
    } catch {
      return "";
    }
  }
  function chromeVersionText() {
    const match = String(navigator.userAgent || "").match(/(?:Chrome|Chromium)\/([0-9.]+)/);
    return match ? "Chrome " + match[1] : "Chrome version unknown";
  }
  let nonFatalErrorNotifies = 0;
  function reportEngineError(context, err, fatal) {
    const isFatal = fatal === void 0 ? !scope.everReady : !!fatal;
    if (!isFatal) {
      nonFatalErrorNotifies++;
      if (nonFatalErrorNotifies > 5) {
        return;
      }
    }
    const parts = [context];
    const errText = engineErrorText(err);
    if (errText) {
      parts.push(errText);
    }
    if (window.__engineErrors && window.__engineErrors.length) {
      parts.push("captured: " + window.__engineErrors.join(" | "));
    }
    parts.push(chromeVersionText());
    notify({
      type: "error",
      fatal: isFatal,
      message: parts.join(" - ")
    });
  }
  window.onerror = function(msg, source, line, column, err) {
    if (window.__engineErrors.length < 20) {
      window.__engineErrors.push(String(msg));
    }
    reportEngineError("terminal runtime error", err || msg);
  };
  function measureFitDimensions(containerHeightPx, retriesLeft) {
    if (typeof retriesLeft !== "number") {
      retriesLeft = 30;
    }
    const notReady = !scope.term || !scope.term.element;
    let cellWidth = 0;
    let cellHeight = 0;
    if (!notReady) {
      const core = scope.term._core;
      if (core && core._renderService && core._renderService.dimensions) {
        cellWidth = core._renderService.dimensions.css.cell.width;
        cellHeight = core._renderService.dimensions.css.cell.height;
      }
    }
    if (notReady || cellWidth <= 0 || cellHeight <= 0) {
      if (retriesLeft > 0) {
        requestAnimationFrame(function() {
          measureFitDimensions(containerHeightPx, retriesLeft - 1);
        });
        return;
      }
      flog("measure-fail", {
        notReady,
        cellWidth,
        cellHeight,
        retriesLeft
      });
      notify({ type: "measure-result", cols: null, rows: null });
      return;
    }
    const vpWidth = window.innerWidth;
    const vpHeight = typeof containerHeightPx === "number" && containerHeightPx > 0 ? containerHeightPx : window.innerHeight;
    const cols = Math.floor(vpWidth / cellWidth);
    if (cols < scope.MIN_FIT_COLS) {
      flog("measure-skip-small-width", {
        vpWidth,
        cellWidth,
        cols
      });
      notify({ type: "measure-result", cols: null, rows: null });
      return;
    }
    const rows = Math.max(8, Math.floor(vpHeight / cellHeight));
    notify({ type: "measure-result", cols, rows });
  }
  function handleMsg(msg) {
    if (typeof msg.id === "number") {
      if (scope.handledMessageIds.indexOf(msg.id) !== -1) {
        return;
      }
      scope.handledMessageIds.push(msg.id);
      if (scope.handledMessageIds.length > 256) {
        scope.handledMessageIds.shift();
      }
    }
    if (msg.type === "ping") {
      notify({ type: "pong", pingId: msg.id });
    } else if (msg.type === "init") {
      init(
        msg.cols,
        msg.rows,
        msg.initialData,
        msg.terminalTheme,
        msg.fontScale,
        msg.preserveScroll,
        msg.oscLinks
      );
    } else if (msg.type === "set-font-scale") {
      if (typeof msg.fontScale === "number" && msg.fontScale > 0 && msg.fontScale !== scope.currentTextScale) {
        scope.userScale = 1;
        scope.panX = 0;
        scope.panY = 0;
        applyTextScale(msg.fontScale);
      }
    } else if (msg.type === "resize") {
      resize(msg.cols, msg.rows);
    } else if (msg.type === "reflow") {
      reflow(msg.cols, msg.rows);
    } else if (msg.type === "write") {
      write(msg.data);
    } else if (msg.type === "clear") {
      scope.terminalGeneration++;
      resetWriteQueue();
      resumeTerminalDataReplyAuthority();
      scope.statusDotPendingSelector = false;
      scope.afterDrainCallbacks = [];
      scope.writesDraining = false;
      scope.mouseModeScanTail = "";
      scope.trackedMouseTrackingMode = "none";
      scope.sgrMouseMode = false;
      scope.sgrMousePixelsMode = false;
      scope.initialOscLinks = [];
      scope.initialOscLinkRowOffset = 0;
      scope.initialOscLinkEvictionReady = false;
      if (scope.term) {
        scope.term.clear();
        scope.term.reset();
      }
      emitModesIfChanged();
      emitKeyboardAvoidanceMetrics();
      resetEvictionCounter();
      if (scope.selMode === "select") {
        notify({ type: "selection-evicted" });
        cancelSelect();
      }
    } else if (msg.type === "measure") {
      measureFitDimensions(msg.containerHeight);
    } else if (msg.type === "reset-zoom") {
      applyFitScale("reset-zoom-msg");
    } else if (msg.type === "set-theme") {
      applyTerminalTheme(msg.terminalTheme);
    } else if (msg.type === "cancel-select") {
      if (scope.selMode === "select") {
        cancelSelect();
      }
    } else if (msg.type === "do-select-all") {
      if (scope.term) {
        try {
          scope.term.selectAll();
          const b = scope.term.buffer.active;
          if (scope.selMode !== "select") {
            scope.selMode = "select";
            scope.selectionOverlay.classList.add("active");
            notify({ type: "set-select-mode", enabled: true });
          }
          scope.sel = {
            anchor: { col: 0, row: 0 },
            focus: { col: scope.term.cols - 1, row: b.length - 1 },
            activeHandle: null
          };
          repositionOverlay();
        } catch {
        }
      }
    }
  }
  scope.WORD_RE = /[\p{L}\p{N}_./:@~+=?&#%-]/u;
  scope.LONG_PRESS_MS = 500;
  scope.LONG_PRESS_SLOP = 10;
  scope.TAP_SLOP = 24;
  scope.TAP_MAX_MS = 700;
  scope.EDGE_SCROLL_PX = 40;
  scope.EDGE_SCROLL_INTERVAL = 60;
  scope.selectionOverlay = document.getElementById("selection-overlay");
  scope.handleStart = document.getElementById("sel-handle-start");
  scope.handleEnd = document.getElementById("sel-handle-end");
  scope.selMenu = document.getElementById("sel-menu");
  scope.btnCopy = document.getElementById("sel-menu-copy");
  scope.btnSelAll = document.getElementById("sel-menu-all");
  scope.selMode = "navigate";
  scope.sel = null;
  scope.longPressTimer = null;
  scope.longPressOrigin = null;
  scope.tapCandidate = null;
  scope.edgeScrollTimer = null;
  scope.edgeScrollDir = 0;
  scope.edgeScrollClientX = 0;
  scope.edgeScrollClientY = 0;
  let linesEverWritten = 0;
  function resetEvictionCounter() {
    linesEverWritten = 0;
  }
  function isBufferFull() {
    if (!scope.term) {
      return false;
    }
    return linesEverWritten >= 5e3 + (scope.term.rows || 0);
  }
  function checkEviction() {
    if (scope.selMode !== "select" || !scope.sel) {
      return;
    }
    const oldest = Math.min(scope.sel.anchor.row, scope.sel.focus.row);
    if (oldest < 0) {
      notify({ type: "selection-evicted" });
      cancelSelect();
    }
  }
  function logFeedAndEvict() {
    linesEverWritten++;
    if (scope.initialOscLinkEvictionReady && isBufferFull()) {
      scope.initialOscLinkRowOffset += 1;
    }
    if (scope.selMode === "select" && scope.sel && isBufferFull()) {
      scope.sel.anchor.row -= 1;
      scope.sel.focus.row -= 1;
      checkEviction();
      repositionOverlay();
    }
  }
  function emitModesIfChanged() {
    if (!scope.term) {
      return;
    }
    const bp = !!(scope.term.modes && scope.term.modes.bracketedPasteMode);
    let alt = false;
    const mouseTrackingMode = getMouseTrackingMode();
    try {
      alt = scope.term.buffer && scope.term.buffer.active && scope.term.buffer.active.type === "alternate";
    } catch {
    }
    if (bp !== scope.lastEmittedModes.bracketedPasteMode || alt !== scope.lastEmittedModes.altScreen || mouseTrackingMode !== scope.lastEmittedModes.mouseTrackingMode || scope.sgrMouseMode !== scope.lastEmittedModes.sgrMouseMode || scope.sgrMousePixelsMode !== scope.lastEmittedModes.sgrMousePixelsMode) {
      scope.lastEmittedModes = {
        bracketedPasteMode: bp,
        altScreen: alt,
        mouseTrackingMode,
        sgrMouseMode: scope.sgrMouseMode,
        sgrMousePixelsMode: scope.sgrMousePixelsMode
      };
      notify({
        type: "modes",
        bracketedPasteMode: bp,
        altScreen: alt,
        mouseTrackingMode,
        sgrMouseMode: scope.sgrMouseMode,
        sgrMousePixelsMode: scope.sgrMousePixelsMode
      });
    }
  }
  scope.lastEmittedModes = {
    bracketedPasteMode: false,
    altScreen: false,
    mouseTrackingMode: "none",
    sgrMouseMode: false,
    sgrMousePixelsMode: false
  };
  function lineHasVisibleContent(line, cell) {
    if (line.translateToString(true).trim().length > 0) {
      return true;
    }
    if (!cell || !line.getCell) {
      return false;
    }
    const limit = Math.min(scope.term.cols || 0, line.length || 0);
    for (let x = 0; x < limit; x++) {
      const current = line.getCell(x, cell);
      if (!current) {
        continue;
      }
      if (!current.isBgDefault() || current.isInverse()) {
        return true;
      }
      if (typeof current.isUnderline === "function" && current.isUnderline()) {
        return true;
      }
      if (typeof current.isStrikethrough === "function" && current.isStrikethrough()) {
        return true;
      }
      if (typeof current.isOverline === "function" && current.isOverline()) {
        return true;
      }
    }
    return false;
  }
  function computeContentBottomRow() {
    if (!scope.term || !scope.term.buffer || !scope.term.buffer.active) {
      return 0;
    }
    const buffer = scope.term.buffer.active;
    const top = buffer.viewportY || 0;
    const cell = buffer.getNullCell ? buffer.getNullCell() : null;
    for (let y = (scope.term.rows || 0) - 1; y >= 0; y--) {
      try {
        const line = buffer.getLine(top + y);
        if (line && lineHasVisibleContent(line, cell)) {
          return y;
        }
      } catch {
      }
    }
    return 0;
  }
  function emitKeyboardAvoidanceMetrics() {
    if (!scope.term) {
      return;
    }
    let alt = false;
    try {
      alt = scope.term.buffer && scope.term.buffer.active && scope.term.buffer.active.type === "alternate";
    } catch {
    }
    notify({
      type: "keyboard-avoidance-metrics",
      cursorY: scope.term.buffer && scope.term.buffer.active ? scope.term.buffer.active.cursorY : 0,
      contentBottomRow: alt ? 0 : computeContentBottomRow(),
      rows: scope.term.rows || 0,
      altScreen: alt
    });
  }
  function attachTermObservers() {
    if (!scope.term) {
      return;
    }
    disposeTermObservers();
    try {
      scope.termObserverDisposables.push(scope.term.onLineFeed(logFeedAndEvict));
    } catch {
    }
    try {
      scope.termObserverDisposables.push(
        scope.term.onScroll(function() {
          updateScrollIndicator(false);
        })
      );
    } catch {
    }
    try {
      if (scope.term.onWriteParsed) {
        scope.termObserverDisposables.push(
          scope.term.onWriteParsed(function() {
            emitModesIfChanged();
            emitKeyboardAvoidanceMetrics();
          })
        );
      }
    } catch {
    }
    afterWritesDrained(function() {
      emitModesIfChanged();
      emitKeyboardAvoidanceMetrics();
    });
  }
  function viewportToCell(clientX, clientY) {
    if (!scope.term) {
      return null;
    }
    const cellW = getCellWidth();
    const cellH = getCellHeight();
    if (cellW <= 0 || cellH <= 0) {
      return null;
    }
    let total = getTotalScale();
    if (total <= 0) {
      total = 1;
    }
    const sx = (clientX - scope.panX) / total;
    const sy = (clientY - scope.panY) / total;
    let col = Math.floor(sx / cellW);
    let viewportRow = Math.floor(sy / cellH);
    if (col < 0) {
      col = 0;
    }
    if (col > scope.term.cols - 1) {
      col = scope.term.cols - 1;
    }
    if (viewportRow < 0) {
      viewportRow = 0;
    }
    if (viewportRow > scope.term.rows - 1) {
      viewportRow = scope.term.rows - 1;
    }
    const viewportY = scope.term.buffer.active.viewportY;
    return { col, row: viewportRow + viewportY };
  }
  function viewportToMouseReportCell(clientX, clientY) {
    if (!scope.term) {
      return null;
    }
    const cellW = getCellWidth();
    const cellH = getCellHeight();
    if (cellW <= 0 || cellH <= 0) {
      return null;
    }
    if (typeof clientX !== "number") {
      clientX = window.innerWidth / 2;
    }
    if (typeof clientY !== "number") {
      clientY = window.innerHeight / 2;
    }
    let total = getTotalScale();
    if (total <= 0) {
      total = 1;
    }
    let sx = (clientX - scope.panX) / total;
    let sy = (clientY - scope.panY) / total;
    const maxX = Math.max(0, scope.term.cols * cellW - 1);
    const maxY = Math.max(0, scope.term.rows * cellH - 1);
    if (sx < 0) {
      sx = 0;
    }
    if (sx > maxX) {
      sx = maxX;
    }
    if (sy < 0) {
      sy = 0;
    }
    if (sy > maxY) {
      sy = maxY;
    }
    let col = Math.floor(sx / cellW);
    let row = Math.floor(sy / cellH);
    if (col < 0) {
      col = 0;
    }
    if (col > scope.term.cols - 1) {
      col = scope.term.cols - 1;
    }
    if (row < 0) {
      row = 0;
    }
    if (row > scope.term.rows - 1) {
      row = scope.term.rows - 1;
    }
    return { col, row, x: Math.floor(sx), y: Math.floor(sy) };
  }
  function isAlternateBufferActive() {
    try {
      return !!(scope.term && scope.term.buffer && scope.term.buffer.active && scope.term.buffer.active.type === "alternate");
    } catch {
      return false;
    }
  }
  function getMouseTrackingMode() {
    try {
      if (scope.term && scope.term.modes && typeof scope.term.modes.mouseTrackingMode === "string") {
        const mode = scope.term.modes.mouseTrackingMode;
        if (mode === "x10" || mode === "vt200" || mode === "drag" || mode === "any") {
          return mode;
        }
        return "none";
      }
    } catch {
    }
    if (scope.trackedMouseTrackingMode === "x10" || scope.trackedMouseTrackingMode === "vt200" || scope.trackedMouseTrackingMode === "drag" || scope.trackedMouseTrackingMode === "any") {
      return scope.trackedMouseTrackingMode;
    }
    return "none";
  }
  function repeatSequence(sequence, count) {
    let out = "";
    for (let i = 0; i < count; i++) {
      out += sequence;
    }
    return out;
  }
  function buildArrowScrollSequence(lines) {
    let prefix = "[";
    try {
      if (scope.term && scope.term.modes && scope.term.modes.applicationCursorKeysMode) {
        prefix = "O";
      }
    } catch {
    }
    return scope.ESC + prefix + (lines < 0 ? "A" : "B");
  }
  function buildMouseWheelSequence(lines, clientX, clientY) {
    const cell = viewportToMouseReportCell(clientX, clientY);
    if (!cell) {
      return "";
    }
    const eventCode = lines < 0 ? 64 : 65;
    if (scope.sgrMousePixelsMode) {
      if (!isSafeSgrMouseCoordinate(cell.x) || !isSafeSgrMouseCoordinate(cell.y)) {
        return "";
      }
      return scope.ESC + "[<" + eventCode + ";" + cell.x + ";" + cell.y + "M";
    }
    if (scope.sgrMouseMode) {
      const sgrCol = cell.col + 1;
      const sgrRow = cell.row + 1;
      if (!isSafeSgrMouseCoordinate(sgrCol) || !isSafeSgrMouseCoordinate(sgrRow)) {
        return "";
      }
      return scope.ESC + "[<" + eventCode + ";" + sgrCol + ";" + sgrRow + "M";
    }
    const button = eventCode + 32;
    const col = cell.col + 1 + 32;
    const row = cell.row + 1 + 32;
    if (button > 126 || col > 126 || row > 126) {
      return "";
    }
    return scope.ESC + "[M" + String.fromCharCode(button) + String.fromCharCode(col) + String.fromCharCode(row);
  }
  function isSafeSgrMouseCoordinate(value) {
    return Number.isInteger(value) && value >= 0 && value <= 9999;
  }
  function buildMouseClickInput(clientX, clientY) {
    const mouseTrackingMode = getMouseTrackingMode();
    if (!isClickMouseTrackingMode(mouseTrackingMode)) {
      return "";
    }
    const cell = viewportToMouseReportCell(clientX, clientY);
    if (!cell) {
      return "";
    }
    if (scope.sgrMousePixelsMode) {
      const pixelX = cell.x;
      const pixelY = cell.y;
      if (!isSafeSgrMouseCoordinate(pixelX) || !isSafeSgrMouseCoordinate(pixelY)) {
        return "";
      }
      const pixelPress = scope.ESC + "[<0;" + pixelX + ";" + pixelY + "M";
      if (mouseTrackingMode === "x10") {
        return pixelPress;
      }
      return pixelPress + scope.ESC + "[<0;" + pixelX + ";" + pixelY + "m";
    }
    if (scope.sgrMouseMode) {
      const sgrCol = cell.col + 1;
      const sgrRow = cell.row + 1;
      if (!isSafeSgrMouseCoordinate(sgrCol) || !isSafeSgrMouseCoordinate(sgrRow)) {
        return "";
      }
      const sgrPress = scope.ESC + "[<0;" + sgrCol + ";" + sgrRow + "M";
      if (mouseTrackingMode === "x10") {
        return sgrPress;
      }
      return sgrPress + scope.ESC + "[<0;" + sgrCol + ";" + sgrRow + "m";
    }
    const col = cell.col + 1 + 32;
    const row = cell.row + 1 + 32;
    if (col > 126 || row > 126) {
      return "";
    }
    const press = scope.ESC + "[M" + String.fromCharCode(32) + String.fromCharCode(col) + String.fromCharCode(row);
    if (mouseTrackingMode === "x10") {
      return press;
    }
    return press + scope.ESC + "[M" + String.fromCharCode(35) + String.fromCharCode(col) + String.fromCharCode(row);
  }
  function isClickMouseTrackingMode(mode) {
    return mode !== "none";
  }
  function isWheelMouseTrackingMode(mode) {
    return mode !== "none" && mode !== "x10";
  }
  function shouldRouteScrollToTerminalInput() {
    return isWheelMouseTrackingMode(getMouseTrackingMode()) || isAlternateBufferActive();
  }
  function buildMouseWheelScrollInput(lines, clientX, clientY) {
    const count = Math.min(Math.abs(lines), 32);
    if (count === 0) {
      return "";
    }
    const sequence = buildMouseWheelSequence(lines, clientX, clientY);
    if (!sequence) {
      return "";
    }
    return repeatSequence(sequence, count);
  }
  function buildTuiScrollInput(lines, clientX, clientY) {
    const count = Math.min(Math.abs(lines), 32);
    if (count === 0) {
      return "";
    }
    const mouseTrackingMode = getMouseTrackingMode();
    let sequence = "";
    if (isWheelMouseTrackingMode(mouseTrackingMode)) {
      sequence = buildMouseWheelSequence(lines, clientX, clientY);
    }
    if (!sequence) {
      sequence = buildArrowScrollSequence(lines);
    }
    return repeatSequence(sequence, count);
  }
  function routeScrollLines(lines, clientX, clientY) {
    if (!scope.term || lines === 0) {
      return;
    }
    const mouseTrackingMode = getMouseTrackingMode();
    const alternateBufferActive = isAlternateBufferActive();
    if (isWheelMouseTrackingMode(mouseTrackingMode)) {
      const mouseInput = buildMouseWheelScrollInput(lines, clientX, clientY);
      if (mouseInput) {
        notify({ type: "terminal-input", bytes: mouseInput });
        return;
      }
      const fallbackInput = buildTuiScrollInput(lines, clientX, clientY);
      if (fallbackInput) {
        notify({ type: "terminal-input", bytes: fallbackInput });
      }
      return;
    }
    if (alternateBufferActive) {
      const input = buildTuiScrollInput(lines, clientX, clientY);
      if (input) {
        notify({ type: "terminal-input", bytes: input });
      }
      return;
    }
    scope.term.scrollLines(lines);
  }
  function clampNormalScrollLines(lines) {
    if (!scope.term || !scope.term.buffer || !scope.term.buffer.active || lines === 0) {
      return 0;
    }
    const buffer = scope.term.buffer.active;
    if (lines > 0) {
      return Math.min(lines, Math.max(0, buffer.baseY - buffer.viewportY));
    }
    return Math.max(lines, -buffer.viewportY);
  }
  function canScrollNormalBufferDelta(deltaY) {
    if (!scope.term || !scope.term.buffer || !scope.term.buffer.active || deltaY === 0) {
      return false;
    }
    const buffer = scope.term.buffer.active;
    if (deltaY > 0) {
      return buffer.viewportY < buffer.baseY;
    }
    return buffer.viewportY > 0;
  }
  function applyNormalBufferScrollDelta(deltaY) {
    if (!scope.term || deltaY === 0) {
      return false;
    }
    const effectiveCellH = getCellHeight() * getTotalScale();
    if (effectiveCellH <= 0) {
      return false;
    }
    if (!canScrollNormalBufferDelta(deltaY)) {
      resetSmoothScrollOffset();
      return false;
    }
    scope.smoothScrollOffsetY -= deltaY;
    const lines = Math.trunc(-scope.smoothScrollOffsetY / effectiveCellH);
    if (lines !== 0) {
      const applied = clampNormalScrollLines(lines);
      if (applied !== 0) {
        scope.term.scrollLines(applied);
        scope.smoothScrollOffsetY += applied * effectiveCellH;
      }
      if (applied !== lines) {
        scope.smoothScrollOffsetY = 0;
      }
    }
    const limit = effectiveCellH - 1;
    if (scope.smoothScrollOffsetY > limit) {
      scope.smoothScrollOffsetY = limit;
    }
    if (scope.smoothScrollOffsetY < -limit) {
      scope.smoothScrollOffsetY = -limit;
    }
    updateScrollIndicator(true);
    return true;
  }
  function enqueueNormalBufferScrollDelta(deltaY) {
    if (!scope.term || deltaY === 0) {
      return false;
    }
    if (!canScrollNormalBufferDelta(deltaY)) {
      resetSmoothScrollOffset();
      return false;
    }
    scope.pendingNormalScrollDeltaY += deltaY;
    if (scope.normalScrollFrameId !== null) {
      return true;
    }
    scope.normalScrollFrameId = requestAnimationFrame(function() {
      scope.normalScrollFrameId = null;
      const delta = scope.pendingNormalScrollDeltaY;
      scope.pendingNormalScrollDeltaY = 0;
      if (!applyNormalBufferScrollDelta(delta)) {
        resetSmoothScrollOffset();
      }
    });
    return true;
  }
  function resetSmoothScrollOffset() {
    scope.pendingNormalScrollDeltaY = 0;
    if (scope.normalScrollFrameId !== null) {
      cancelAnimationFrame(scope.normalScrollFrameId);
      scope.normalScrollFrameId = null;
    }
    if (scope.smoothScrollOffsetY === 0) {
      return;
    }
    scope.smoothScrollOffsetY = 0;
    updateScrollIndicator(false);
  }
  function cellToViewportPx(col, absRow) {
    if (!scope.term) {
      return { x: 0, y: 0 };
    }
    const cellW = getCellWidth();
    const cellH = getCellHeight();
    const viewportRow = absRow - scope.term.buffer.active.viewportY;
    const sx = col * cellW;
    const sy = viewportRow * cellH;
    const total = getTotalScale();
    return { x: sx * total + scope.panX, y: sy * total + scope.panY };
  }
  function getLineText(absRow) {
    if (!scope.term) {
      return "";
    }
    const line = scope.term.buffer.active.getLine(absRow);
    if (!line) {
      return "";
    }
    return line.translateToString(false);
  }
  function cellColToStringIndex(absRow, col) {
    if (!scope.term) {
      return col;
    }
    const line = scope.term.buffer.active.getLine(absRow);
    if (!line) {
      return col;
    }
    return line.translateToString(false, 0, col).length;
  }
  const FILE_PATH_RE = /(?:~[\\/]|[\\/]|\.{1,2}[\\/]|[A-Za-z]:[\\/]|[A-Za-z0-9._-]+[\\/]|(?=[A-Za-z0-9._-]*\.[A-Za-z0-9]))[A-Za-z0-9._~\-\/%+@\\()[\]]*(?::\d+)?(?::\d+)?/g;
  const SPACED_PATH_RE = /(?:~[\\/]|[\\/]|\.{1,2}[\\/]|[A-Za-z]:[\\/]|[A-Za-z0-9._-]+[\\/])[^()[\]{}'",;<>|\`\r\n]+(?::\d+)?(?::\d+)?/g;
  const PATH_LEADING_TRIM = { "(": 1, "[": 1, "{": 1, '"': 1, "'": 1 };
  const PATH_TRAILING_TRIM = {
    ")": 1,
    "]": 1,
    "}": 1,
    '"': 1,
    "'": 1,
    ",": 1,
    ";": 1,
    ".": 1
  };
  function parsePathLineCol(value) {
    const m = /^(.*?)(?::(\d+))?(?::(\d+))?$/.exec(value);
    if (!m) {
      return null;
    }
    const pathText = m[1];
    const last = pathText.charAt(pathText.length - 1);
    if (!pathText || last === "/" || last === "\\") {
      return null;
    }
    const line = m[2] ? Number.parseInt(m[2], 10) : null;
    const column = m[3] ? Number.parseInt(m[3], 10) : null;
    if (line !== null && line < 1 || column !== null && column < 1) {
      return null;
    }
    return { pathText, line, column };
  }
  function trimPathBoundaryPunctuation(raw, rawStart) {
    let start = 0, end = raw.length;
    while (start < end && PATH_LEADING_TRIM[raw.charAt(start)]) {
      start += 1;
    }
    while (end > start && PATH_TRAILING_TRIM[raw.charAt(end - 1)]) {
      end -= 1;
    }
    if (start >= end) {
      return null;
    }
    return { text: raw.slice(start, end), startIndex: rawStart + start, endIndex: rawStart + end };
  }
  function hasSeparatorAfterWhitespace(text) {
    let sawWhitespace = false;
    for (let i = 0; i < text.length; i++) {
      const ch = text.charAt(i);
      if (/\s/.test(ch)) {
        sawWhitespace = true;
        continue;
      }
      if (sawWhitespace && (ch === "/" || ch === "\\")) {
        return true;
      }
    }
    return false;
  }
  function trimSpacedPathTrailingProse(range, col) {
    let selected = null;
    const extensionPrefixPattern = /\.[A-Za-z0-9_+-]+(?::\d+)?(?::\d+)?(?=\s+|$)/g;
    let match;
    while ((match = extensionPrefixPattern.exec(range.text)) !== null) {
      const end = match.index + match[0].length;
      var text = range.text.slice(0, end);
      if (countPathStarts(text) > 1) {
        continue;
      }
      if (end < range.text.length || selected === null || /[\\/]/.test(range.text.slice(selected.length, end))) {
        selected = text;
      }
    }
    if (selected) {
      if (col !== void 0 && col >= range.startIndex + selected.length) {
        return null;
      }
      return {
        text: selected,
        startIndex: range.startIndex,
        endIndex: range.startIndex + selected.length
      };
    }
    var text = range.text.replace(/\s+$/, "");
    return { text, startIndex: range.startIndex, endIndex: range.startIndex + text.length };
  }
  function countPathStarts(text) {
    let count = 0;
    const pathStartPattern = /(?:^|\s)(?:~[\\/]|[\\/]|\.{1,2}[\\/]|[A-Za-z]:[\\/])/g;
    while (pathStartPattern.exec(text) !== null) {
      count += 1;
    }
    return count;
  }
  function hasSpacedPathExtension(text) {
    const range = trimSpacedPathTrailingProse({ text, startIndex: 0, endIndex: text.length });
    if (!range) {
      return false;
    }
    const trimmed = range.text.replace(/\s+$/, "");
    return /\s/.test(trimmed) && /\.[A-Za-z0-9_+-]+(?::\d+)?(?::\d+)?$/.test(trimmed);
  }
  function matchSpacedFilePathAtColumn(lineText, col) {
    SPACED_PATH_RE.lastIndex = 0;
    let match;
    while ((match = SPACED_PATH_RE.exec(lineText)) !== null) {
      const trimmed = trimPathBoundaryPunctuation(match[0], match.index);
      if (!trimmed || !hasSeparatorAfterWhitespace(trimmed.text) && !hasSpacedPathExtension(trimmed.text)) {
        continue;
      }
      const candidate = trimSpacedPathTrailingProse(trimmed, col);
      if (!candidate) {
        continue;
      }
      if (col < candidate.startIndex || col >= candidate.endIndex) {
        continue;
      }
      const parsed = parsePathLineCol(candidate.text);
      if (parsed) {
        return parsed;
      }
    }
    return null;
  }
  function matchFilePathAtColumn(lineText, col) {
    const spaced = matchSpacedFilePathAtColumn(lineText, col);
    if (spaced) {
      return spaced;
    }
    FILE_PATH_RE.lastIndex = 0;
    let match;
    while ((match = FILE_PATH_RE.exec(lineText)) !== null) {
      const raw = match[0];
      if (raw.length === 0) {
        FILE_PATH_RE.lastIndex += 1;
        continue;
      }
      const trimmed = trimPathBoundaryPunctuation(raw, match.index);
      if (!trimmed) {
        continue;
      }
      if (col < trimmed.startIndex || col >= trimmed.endIndex) {
        continue;
      }
      const parsed = parsePathLineCol(trimmed.text);
      if (parsed) {
        return parsed;
      }
    }
    return null;
  }
  function filePathAtViewportPoint(originX, originY) {
    const tapCell = viewportToCell(originX, originY);
    if (!tapCell) {
      return null;
    }
    return matchFilePathAtColumn(
      getLineText(tapCell.row),
      cellColToStringIndex(tapCell.row, tapCell.col)
    );
  }
  const URL_TAP_RE_SOURCE = "\\bhttps?:\\/\\/[^\\s\"'!*(){}|\\\\^<>`]*[^\\s\"':,.!?{}|\\\\^~[\\]`()<>]";
  const FILE_URL_TAP_RE_SOURCE = "\\bfile:\\/\\/[^\\s\"'!*(){}|\\\\^<>`]*[^\\s\"',!?{}|\\\\^~[\\]`()<>]";
  const URL_TAP_MAX_LENGTH = 2048;
  function findUrlAtColumn(lineText, col) {
    return findTerminalUrlAtColumn(lineText, col, URL_TAP_RE_SOURCE);
  }
  function findFileUrlAtColumn(lineText, col) {
    return findTerminalUrlAtColumn(lineText, col, FILE_URL_TAP_RE_SOURCE);
  }
  function findTerminalUrlAtColumn(lineText, col, source) {
    if (typeof lineText !== "string" || lineText.length === 0) {
      return null;
    }
    const re = new RegExp(source, "gi");
    let match;
    while ((match = re.exec(lineText)) !== null) {
      const end = match.index + match[0].length;
      if (match[0].length <= URL_TAP_MAX_LENGTH && col >= match.index && col < end) {
        return match[0];
      }
      if (match[0].length === 0) {
        re.lastIndex++;
      }
    }
    return null;
  }
  function fileUrlAtViewportPoint(clientX, clientY) {
    const cell = viewportToCell(clientX, clientY);
    if (!cell) {
      return null;
    }
    return findFileUrlAtColumn(getLineText(cell.row), cellColToStringIndex(cell.row, cell.col));
  }
  function urlAtViewportPoint(clientX, clientY) {
    const cell = viewportToCell(clientX, clientY);
    if (!cell) {
      return null;
    }
    return findUrlAtColumn(getLineText(cell.row), cellColToStringIndex(cell.row, cell.col));
  }
  function oscLinkService() {
    try {
      const core = scope.term && scope.term._core;
      if (!core) {
        return null;
      }
      return core._oscLinkService || core._inputHandler && core._inputHandler._oscLinkService || null;
    } catch {
      return null;
    }
  }
  function oscLinkAtViewportPoint(clientX, clientY) {
    try {
      const cell = viewportToCell(clientX, clientY);
      if (!cell) {
        return null;
      }
      const line = scope.term.buffer.active.getLine(cell.row);
      if (!line) {
        return null;
      }
      const urlId = oscLinkIdAtCell(line, cell.col);
      if (!urlId) {
        return initialOscLinkAtCell(cell.row, cell.col);
      }
      const svc = oscLinkService();
      if (!svc || !svc.getLinkData) {
        return initialOscLinkAtCell(cell.row, cell.col);
      }
      const data = svc.getLinkData(urlId);
      const uri = data && data.uri;
      return terminalOscLinkTarget(uri);
    } catch {
      return null;
    }
  }
  function initialOscLinkAtCell(row, col) {
    for (let i = 0; i < scope.initialOscLinks.length; i++) {
      const link = scope.initialOscLinks[i];
      if (!link || typeof link.uri !== "string") {
        continue;
      }
      if (link.row < scope.initialOscLinkRowOffset) {
        continue;
      }
      const shiftedRow = link.row - scope.initialOscLinkRowOffset;
      if (shiftedRow === row && col >= link.startCol && col < link.endCol && initialOscLinkTextStillMatches(link, shiftedRow)) {
        return terminalOscLinkTarget(link.uri);
      }
    }
    return null;
  }
  function terminalOscLinkTarget(uri) {
    if (typeof uri !== "string") {
      return null;
    }
    if (/^https?:/i.test(uri)) {
      return { kind: "url", url: uri };
    }
    const fileTap = resolveTerminalOscFileTap(uri);
    return fileTap ? { kind: "file", fileTap } : null;
  }
  function resolveTerminalOscFileTap(uri) {
    return resolveTerminalFileUrlTap(uri) || parseOscPathLikeTarget(uri);
  }
  function resolveTerminalFileUrlTap(uri) {
    let parsed;
    try {
      parsed = new URL(uri);
    } catch {
      return null;
    }
    if (parsed.protocol !== "file:") {
      return null;
    }
    let filePath;
    try {
      filePath = decodeURIComponent(parsed.pathname || "");
    } catch {
      return null;
    }
    if (parsed.hostname && !isLocalFileUriHostname(parsed.hostname)) {
      filePath = "//" + parsed.hostname + filePath;
    } else if (/^\/[A-Za-z]:\//.test(filePath)) {
      filePath = filePath.slice(1);
    }
    if (!filePath) {
      return null;
    }
    const hashTarget = parseFileUrlLineHash(parsed.hash || "");
    if (hashTarget) {
      return { pathText: filePath, line: hashTarget.line, column: hashTarget.column };
    }
    if (/%3a/i.test(parsed.pathname || "")) {
      return { pathText: filePath, line: null, column: null };
    }
    return parseFilePathTrailingLineTarget(filePath) || { pathText: filePath, line: null, column: null };
  }
  function isLocalFileUriHostname(hostname) {
    const normalized = String(hostname).toLowerCase();
    return normalized === "localhost" || normalized === "127.0.0.1" || normalized === "::1" || normalized === "[::1]";
  }
  function parseOscPathLikeTarget(value) {
    if (!/^(?:~[\\/]|[\\/]|\.{1,2}[\\/]|[A-Za-z]:[\\/]|[A-Za-z0-9._-]+[\\/]|(?=[A-Za-z0-9._-]*\.[A-Za-z0-9]))/.test(
      value
    )) {
      return null;
    }
    return parsePathLineCol(value);
  }
  function parseFileUrlLineHash(hash) {
    const match = /^#?L(\d+)(?:C(\d+))?$/i.exec(hash);
    if (!match) {
      return null;
    }
    const line = Number.parseInt(match[1], 10);
    const column = match[2] ? Number.parseInt(match[2], 10) : null;
    if (line < 1 || column !== null && column < 1) {
      return null;
    }
    return { line, column };
  }
  function parseFilePathTrailingLineTarget(filePath) {
    const match = /^(.*?)(?::(\d+))(?::(\d+))?$/.exec(filePath);
    if (!match || !match[1] || match[1].charAt(match[1].length - 1) === "/" || match[1].charAt(match[1].length - 1) === "\\") {
      return null;
    }
    const line = Number.parseInt(match[2], 10);
    const column = match[3] ? Number.parseInt(match[3], 10) : null;
    if (line < 1 || column !== null && column < 1) {
      return null;
    }
    return { pathText: match[1], line, column };
  }
  function captureInitialOscLinkTexts() {
    if (!Array.isArray(scope.initialOscLinks)) {
      return;
    }
    for (let i = 0; i < scope.initialOscLinks.length; i++) {
      const link = scope.initialOscLinks[i];
      if (!link || typeof link.text === "string") {
        continue;
      }
      link.text = initialOscLinkTextAtRow(link, link.row);
    }
  }
  function initialOscLinkTextStillMatches(link, row) {
    if (typeof link.text !== "string") {
      return false;
    }
    return link.text.length > 0 && initialOscLinkTextAtRow(link, row) === link.text;
  }
  function initialOscLinkTextAtRow(link, row) {
    try {
      const lineText = getLineText(row);
      const start = cellColToStringIndex(row, link.startCol);
      const end = cellColToStringIndex(row, link.endCol);
      return lineText.slice(start, end);
    } catch {
      return "";
    }
  }
  function oscLinkIdAtCell(line, col) {
    try {
      const bufCell = line.getCell(col);
      return bufCell && bufCell.extended && bufCell.extended.urlId ? bufCell.extended.urlId : 0;
    } catch {
      return 0;
    }
  }
  function notifyTerminalSurfaceTap(originX, originY, focusKeyboard) {
    const tappedOscLink = oscLinkAtViewportPoint(originX, originY);
    if (tappedOscLink && tappedOscLink.kind === "file") {
      notify({
        type: "terminal-file-tap",
        pathText: tappedOscLink.fileTap.pathText,
        line: tappedOscLink.fileTap.line,
        column: tappedOscLink.fileTap.column
      });
      return;
    }
    const tappedFileUrl = fileUrlAtViewportPoint(originX, originY);
    const tappedFileUrlPath = tappedFileUrl ? resolveTerminalFileUrlTap(tappedFileUrl) : null;
    if (tappedFileUrlPath) {
      notify({
        type: "terminal-file-tap",
        pathText: tappedFileUrlPath.pathText,
        line: tappedFileUrlPath.line,
        column: tappedFileUrlPath.column
      });
      return;
    }
    const tappedUrl = tappedOscLink && tappedOscLink.kind === "url" ? tappedOscLink.url : urlAtViewportPoint(originX, originY);
    if (tappedUrl) {
      notify({ type: "open-url", url: tappedUrl });
      return;
    }
    const tappedPath = filePathAtViewportPoint(originX, originY);
    if (tappedPath) {
      notify({
        type: "terminal-file-tap",
        pathText: tappedPath.pathText,
        line: tappedPath.line,
        column: tappedPath.column
      });
      return;
    }
    const clickInput = buildMouseClickInput(originX, originY);
    if (clickInput) {
      notify({ type: "terminal-input", bytes: clickInput });
    }
    if (focusKeyboard || !isClickMouseTrackingMode(getMouseTrackingMode())) {
      notify({ type: "terminal-tap" });
    }
  }
  function seedWordSelection(col, absRow) {
    const line = getLineText(absRow);
    if (!line) {
      scope.sel = {
        anchor: { col, row: absRow },
        focus: { col, row: absRow },
        activeHandle: null
      };
      applyXtermSelection();
      return;
    }
    let s = col;
    let e = col;
    if (col >= 0 && col < line.length && scope.WORD_RE.test(line[col])) {
      while (s > 0 && scope.WORD_RE.test(line[s - 1])) {
        s--;
      }
      while (e < line.length - 1 && scope.WORD_RE.test(line[e + 1])) {
        e++;
      }
    }
    scope.sel = {
      anchor: { col: s, row: absRow },
      focus: { col: e, row: absRow },
      activeHandle: null
    };
    applyXtermSelection();
  }
  function isStartFirst(a, b) {
    if (a.row !== b.row) {
      return a.row < b.row;
    }
    return a.col <= b.col;
  }
  function selRange() {
    if (!scope.sel) {
      return null;
    }
    if (isStartFirst(scope.sel.anchor, scope.sel.focus)) {
      return { start: scope.sel.anchor, end: scope.sel.focus };
    }
    return { start: scope.sel.focus, end: scope.sel.anchor };
  }
  function applyXtermSelection() {
    if (!scope.term || !scope.sel) {
      return;
    }
    const r = selRange();
    if (!r) {
      return;
    }
    let length;
    if (r.start.row === r.end.row) {
      length = Math.max(1, r.end.col - r.start.col + 1);
    } else {
      const first = scope.term.cols - r.start.col;
      const middle = Math.max(0, r.end.row - r.start.row - 1) * scope.term.cols;
      const last = r.end.col + 1;
      length = first + middle + last;
    }
    try {
      scope.term.select(r.start.col, r.start.row, length);
    } catch {
    }
  }
  function cancelSelect() {
    scope.selMode = "navigate";
    scope.sel = null;
    stopEdgeScroll();
    if (scope.term) {
      try {
        scope.term.clearSelection();
      } catch {
      }
      try {
        scope.term.refresh(0, scope.term.rows - 1);
      } catch {
      }
    }
    scope.selectionOverlay.classList.remove("active");
    notify({ type: "set-select-mode", enabled: false });
  }
  function enterSelect(col, absRow) {
    scope.selMode = "select";
    seedWordSelection(col, absRow);
    scope.selectionOverlay.classList.add("active");
    notify({ type: "set-select-mode", enabled: true });
    notify({ type: "haptic", kind: "selection" });
    repositionOverlay();
  }
  function repositionOverlay() {
    if (scope.selMode !== "select" || !scope.sel || !scope.term) {
      return;
    }
    const r = selRange();
    const sPx = cellToViewportPx(r.start.col, r.start.row);
    const ePx = cellToViewportPx(r.end.col + 1, r.end.row);
    const cellH = getCellHeight() * getTotalScale();
    scope.handleStart.style.left = sPx.x + "px";
    scope.handleStart.style.top = sPx.y + "px";
    scope.handleEnd.style.left = ePx.x + "px";
    scope.handleEnd.style.top = ePx.y + cellH + "px";
    const startVisible = sPx.y >= 0 && sPx.y <= window.innerHeight;
    const endVisible = ePx.y >= 0 && ePx.y <= window.innerHeight;
    scope.handleStart.style.visibility = startVisible ? "visible" : "hidden";
    scope.handleEnd.style.visibility = endVisible ? "visible" : "hidden";
    let menuCenterX, menuY, vTransform, marginTop;
    if (startVisible && sPx.y > 56) {
      menuCenterX = sPx.x;
      menuY = sPx.y;
      vTransform = "translateY(-100%)";
      marginTop = "-12px";
    } else if (endVisible && ePx.y + cellH + 56 < window.innerHeight) {
      menuCenterX = ePx.x;
      menuY = ePx.y + cellH;
      vTransform = "translateY(0)";
      marginTop = "12px";
    } else {
      menuCenterX = window.innerWidth / 2;
      menuY = window.innerHeight / 2;
      vTransform = "translateY(-50%)";
      marginTop = "0";
    }
    scope.selMenu.style.transform = vTransform;
    scope.selMenu.style.marginTop = marginTop;
    scope.selMenu.style.top = menuY + "px";
    scope.selMenu.style.left = "0px";
    const EDGE_MARGIN = 8;
    const menuW = scope.selMenu.offsetWidth || 0;
    const minLeft = EDGE_MARGIN;
    const maxLeft = Math.max(EDGE_MARGIN, window.innerWidth - menuW - EDGE_MARGIN);
    const desiredLeft = menuCenterX - menuW / 2;
    const clampedLeft = Math.max(minLeft, Math.min(maxLeft, desiredLeft));
    scope.selMenu.style.left = clampedLeft + "px";
  }
  function syncSelectionHandleToViewportPoint(handle, clientX, clientY) {
    const c = viewportToCell(clientX, clientY);
    if (!c || !scope.sel) {
      return false;
    }
    if (handle === "start") {
      scope.sel.anchor = c;
    } else {
      scope.sel.focus = c;
    }
    applyXtermSelection();
    return true;
  }
  function syncEdgeScrollSelectionEndpoint() {
    if (!scope.sel || !scope.sel.activeHandle) {
      return false;
    }
    return syncSelectionHandleToViewportPoint(
      scope.sel.activeHandle,
      scope.edgeScrollClientX,
      scope.edgeScrollClientY
    );
  }
  function startEdgeScroll(dir) {
    if (scope.edgeScrollDir === dir) {
      return;
    }
    stopEdgeScroll();
    scope.edgeScrollDir = dir;
    scope.edgeScrollTimer = setInterval(function() {
      if (!scope.term || scope.edgeScrollDir === 0) {
        return;
      }
      const beforeY = scope.term.buffer.active.viewportY;
      scope.term.scrollLines(scope.edgeScrollDir);
      const afterY = scope.term.buffer.active.viewportY;
      if (beforeY === afterY) {
        notify({ type: "haptic", kind: "edge-bump" });
        stopEdgeScroll();
        return;
      }
      syncEdgeScrollSelectionEndpoint();
      repositionOverlay();
    }, scope.EDGE_SCROLL_INTERVAL);
  }
  function stopEdgeScroll() {
    if (scope.edgeScrollTimer) {
      clearInterval(scope.edgeScrollTimer);
      scope.edgeScrollTimer = null;
    }
    scope.edgeScrollDir = 0;
  }
  function handleDragMove(handle, clientX, clientY) {
    scope.edgeScrollClientX = clientX;
    scope.edgeScrollClientY = clientY;
    if (!syncSelectionHandleToViewportPoint(handle, clientX, clientY)) {
      return;
    }
    repositionOverlay();
    if (clientY < scope.EDGE_SCROLL_PX) {
      startEdgeScroll(-1);
    } else if (clientY > window.innerHeight - scope.EDGE_SCROLL_PX) {
      startEdgeScroll(1);
    } else {
      stopEdgeScroll();
    }
  }
  const dispatch = {
    mode: "idle",
    touchId: null,
    touchIds: null,
    longPressFingerInsideOverlay: false
  };
  function touchById(touches, id) {
    for (let i = 0; i < touches.length; i++) {
      if (touches[i].identifier === id) {
        return touches[i];
      }
    }
    return null;
  }
  function targetInside(target, el) {
    if (!target || !el) {
      return false;
    }
    return el.contains(target);
  }
  function clearLongPress() {
    if (scope.longPressTimer) {
      clearTimeout(scope.longPressTimer);
      scope.longPressTimer = null;
    }
    scope.longPressOrigin = null;
  }
  function armLongPress(touch) {
    scope.longPressOrigin = { x: touch.clientX, y: touch.clientY, identifier: touch.identifier };
    scope.longPressTimer = setTimeout(function() {
      scope.longPressTimer = null;
      if (!scope.longPressOrigin) {
        return;
      }
      const c = viewportToCell(scope.longPressOrigin.x, scope.longPressOrigin.y);
      if (!c) {
        return;
      }
      enterSelect(c.col, c.row);
    }, scope.LONG_PRESS_MS);
  }
  function touchSlopExceeded(t) {
    if (!scope.longPressOrigin) {
      return false;
    }
    const dx = Math.abs(t.clientX - scope.longPressOrigin.x);
    const dy = Math.abs(t.clientY - scope.longPressOrigin.y);
    return dx + dy > scope.LONG_PRESS_SLOP;
  }
  function dispatcherShouldBlockSurface() {
    return dispatch.mode === "select-drag";
  }
  document.addEventListener(
    "touchstart",
    function(e) {
      const t = e.touches[0];
      const target = e.target;
      const onHandle = target === scope.handleStart || target === scope.handleEnd;
      const inOverlay = targetInside(target, scope.selectionOverlay);
      const inSurface = targetInside(target, scope.surface);
      scope.tapCandidate = null;
      if (e.touches.length === 2) {
        if (scope.selMode === "select") {
          notify({ type: "mobile-clip-cancel-by-pinch" });
          cancelSelect();
        }
        dispatch.mode = "pinch";
        dispatch.touchIds = [e.touches[0].identifier, e.touches[1].identifier];
        clearLongPress();
        return;
      }
      if (onHandle && scope.selMode === "select") {
        const handleName = target === scope.handleStart ? "start" : "end";
        scope.sel.activeHandle = handleName;
        dispatch.mode = "select-drag";
        dispatch.touchId = t.identifier;
        e.preventDefault();
        return;
      }
      if (inOverlay) {
        return;
      }
      if (inSurface && scope.selMode === "select") {
        cancelSelect();
        dispatch.mode = "surface";
        dispatch.touchId = t.identifier;
        return;
      }
      if (inSurface) {
        dispatch.mode = "surface";
        dispatch.touchId = t.identifier;
        scope.tapCandidate = { x: t.clientX, y: t.clientY, t: Date.now(), identifier: t.identifier };
        armLongPress(t);
      }
    },
    { capture: true, passive: false }
  );
  document.addEventListener(
    "touchmove",
    function(e) {
      if (dispatch.mode === "select-drag") {
        const t = touchById(e.touches, dispatch.touchId);
        if (!t || !scope.sel || !scope.sel.activeHandle) {
          return;
        }
        e.preventDefault();
        handleDragMove(scope.sel.activeHandle, t.clientX, t.clientY);
        return;
      }
      if (dispatch.mode === "surface" || dispatch.mode === "pinch") {
        if (scope.longPressTimer && e.touches.length === 1) {
          if (touchSlopExceeded(e.touches[0])) {
            clearLongPress();
          }
        }
        if (scope.tapCandidate && e.touches.length === 1) {
          const mt = e.touches[0];
          if (mt.identifier === scope.tapCandidate.identifier) {
            const dx = Math.abs(mt.clientX - scope.tapCandidate.x);
            const dy = Math.abs(mt.clientY - scope.tapCandidate.y);
            if (dx + dy > scope.TAP_SLOP) {
              scope.tapCandidate = null;
            }
          }
        } else if (e.touches.length !== 1) {
          scope.tapCandidate = null;
        }
      }
    },
    { capture: true, passive: false }
  );
  document.addEventListener(
    "touchend",
    function(e) {
      if (dispatch.mode === "select-drag") {
        if (scope.sel) {
          scope.sel.activeHandle = null;
        }
        stopEdgeScroll();
        dispatch.mode = "idle";
        dispatch.touchId = null;
        return;
      }
      if (dispatch.mode === "pinch") {
        if (e.touches.length < 2) {
          dispatch.mode = e.touches.length === 1 ? "surface" : "idle";
          dispatch.touchIds = null;
          if (e.touches.length === 1) {
            dispatch.touchId = e.touches[0].identifier;
          }
        }
        return;
      }
      if (dispatch.mode === "surface") {
        if (e.touches.length === 0 && scope.tapCandidate && scope.selMode !== "select" && Date.now() - scope.tapCandidate.t <= scope.TAP_MAX_MS) {
          notifyTerminalSurfaceTap(scope.tapCandidate.x, scope.tapCandidate.y, true);
        }
        clearLongPress();
        scope.tapCandidate = null;
        if (e.touches.length === 0) {
          dispatch.mode = "idle";
          dispatch.touchId = null;
        }
      }
    },
    { capture: true, passive: true }
  );
  document.addEventListener(
    "touchcancel",
    function() {
      clearLongPress();
      scope.tapCandidate = null;
      stopEdgeScroll();
      if (dispatch.mode === "select-drag") {
        if (scope.sel) {
          scope.sel.activeHandle = null;
        }
      }
      dispatch.mode = "idle";
      dispatch.touchId = null;
      dispatch.touchIds = null;
    },
    { capture: true, passive: true }
  );
  scope.wheelAccumDeltaY = 0;
  function wheelEventPixelDeltaY(e) {
    const delta = e.deltaY;
    if (typeof delta !== "number" || !Number.isFinite(delta) || delta === 0) {
      return 0;
    }
    if (e.deltaMode === 1) {
      return delta * getCellHeight() * getTotalScale();
    }
    if (e.deltaMode === 2) {
      return delta * window.innerHeight;
    }
    return delta;
  }
  function attachSurfaceWheelHandler(targetSurface) {
    targetSurface.addEventListener(
      "wheel",
      function(e) {
        if (dispatcherShouldBlockSurface()) {
          return;
        }
        if (!scope.term) {
          return;
        }
        e.preventDefault();
        e.stopPropagation();
        if (e.ctrlKey) {
          return;
        }
        const deltaY = wheelEventPixelDeltaY(e);
        if (deltaY === 0) {
          return;
        }
        if (shouldRouteScrollToTerminalInput()) {
          resetSmoothScrollOffset();
          const effectiveCellH = getCellHeight() * getTotalScale();
          if (!(effectiveCellH > 0)) {
            return;
          }
          scope.wheelAccumDeltaY += deltaY;
          const lines = Math.trunc(scope.wheelAccumDeltaY / effectiveCellH);
          if (lines !== 0) {
            scope.wheelAccumDeltaY -= lines * effectiveCellH;
            routeScrollLines(lines, e.clientX, e.clientY);
          }
          return;
        }
        scope.wheelAccumDeltaY = 0;
        enqueueNormalBufferScrollDelta(deltaY);
      },
      { capture: true, passive: false }
    );
  }
  let mouseGesture = null;
  function buildMouseButtonReport(kind, clientX, clientY) {
    const mouseTrackingMode = getMouseTrackingMode();
    if (mouseTrackingMode === "none") {
      return "";
    }
    if (kind === "motion" && mouseTrackingMode !== "drag" && mouseTrackingMode !== "any") {
      return "";
    }
    if (kind === "release" && mouseTrackingMode === "x10") {
      return "";
    }
    const cell = viewportToMouseReportCell(clientX, clientY);
    if (!cell) {
      return "";
    }
    const sgrButton = kind === "motion" ? 32 : 0;
    const sgrFinal = kind === "release" ? "m" : "M";
    if (scope.sgrMousePixelsMode) {
      if (!isSafeSgrMouseCoordinate(cell.x) || !isSafeSgrMouseCoordinate(cell.y)) {
        return "";
      }
      return scope.ESC + "[<" + sgrButton + ";" + cell.x + ";" + cell.y + sgrFinal;
    }
    if (scope.sgrMouseMode) {
      const sgrCol = cell.col + 1;
      const sgrRow = cell.row + 1;
      if (!isSafeSgrMouseCoordinate(sgrCol) || !isSafeSgrMouseCoordinate(sgrRow)) {
        return "";
      }
      return scope.ESC + "[<" + sgrButton + ";" + sgrCol + ";" + sgrRow + sgrFinal;
    }
    const button = kind === "motion" ? 64 : kind === "release" ? 35 : 32;
    const col = cell.col + 1 + 32;
    const row = cell.row + 1 + 32;
    if (col > 126 || row > 126) {
      return "";
    }
    return scope.ESC + "[M" + String.fromCharCode(button) + String.fromCharCode(col) + String.fromCharCode(row);
  }
  function mouseReportCellKey(clientX, clientY) {
    const cell = viewportToMouseReportCell(clientX, clientY);
    return cell ? cell.col + "," + cell.row : null;
  }
  function abandonMouseGesture() {
    const gesture = mouseGesture;
    mouseGesture = null;
    if (!gesture) {
      return;
    }
    if (gesture.mode === "tracking") {
      const release = buildMouseButtonReport("release", gesture.lastX, gesture.lastY);
      if (release) {
        notify({ type: "terminal-input", bytes: release });
      }
    } else if (gesture.mode === "selecting") {
      if (scope.sel) {
        scope.sel.activeHandle = null;
      }
      stopEdgeScroll();
    }
  }
  function beginMouseDrag(gesture) {
    gesture.moved = true;
    if (getMouseTrackingMode() !== "none") {
      gesture.mode = "tracking";
      gesture.lastCellKey = mouseReportCellKey(gesture.startX, gesture.startY);
      const press = buildMouseButtonReport("press", gesture.startX, gesture.startY);
      if (press) {
        notify({ type: "terminal-input", bytes: press });
      }
      return;
    }
    const anchor = viewportToCell(gesture.startX, gesture.startY);
    if (!anchor) {
      gesture.mode = "cancelled";
      return;
    }
    gesture.mode = "selecting";
    scope.selMode = "select";
    scope.sel = { anchor, focus: anchor, activeHandle: "end" };
    scope.selectionOverlay.classList.add("active");
    notify({ type: "set-select-mode", enabled: true });
    applyXtermSelection();
    repositionOverlay();
  }
  function attachSurfaceMouseClickDragHandler(targetSurface) {
    targetSurface.addEventListener(
      "pointerdown",
      function(e) {
        if (e.pointerType !== "mouse" || e.button !== 0) {
          return;
        }
        if (dispatcherShouldBlockSurface() || !scope.term) {
          return;
        }
        if (mouseGesture) {
          abandonMouseGesture();
        }
        try {
          if (targetSurface.setPointerCapture) {
            targetSurface.setPointerCapture(e.pointerId);
          }
        } catch {
        }
        mouseGesture = {
          startX: e.clientX,
          startY: e.clientY,
          lastX: e.clientX,
          lastY: e.clientY,
          lastCellKey: null,
          moved: false,
          mode: "pending",
          dismissedSelection: false
        };
        if (scope.selMode === "select") {
          cancelSelect();
          mouseGesture.dismissedSelection = true;
        }
      },
      true
    );
    targetSurface.addEventListener(
      "pointermove",
      function(e) {
        const gesture = mouseGesture;
        if (e.pointerType !== "mouse" || !gesture || gesture.mode === "cancelled") {
          return;
        }
        if (!scope.term) {
          return;
        }
        gesture.lastX = e.clientX;
        gesture.lastY = e.clientY;
        if ((e.buttons & 1) === 0) {
          abandonMouseGesture();
          return;
        }
        if (!gesture.moved) {
          const dx = Math.abs(e.clientX - gesture.startX);
          const dy = Math.abs(e.clientY - gesture.startY);
          if (dx + dy <= scope.TAP_SLOP) {
            return;
          }
          beginMouseDrag(gesture);
        }
        if (gesture.mode === "tracking") {
          const cellKey = mouseReportCellKey(e.clientX, e.clientY);
          if (cellKey && cellKey !== gesture.lastCellKey) {
            gesture.lastCellKey = cellKey;
            const motion = buildMouseButtonReport("motion", e.clientX, e.clientY);
            if (motion) {
              notify({ type: "terminal-input", bytes: motion });
            }
          }
        } else if (gesture.mode === "selecting") {
          handleDragMove("end", e.clientX, e.clientY);
        }
      },
      true
    );
    targetSurface.addEventListener(
      "pointerup",
      function(e) {
        const gesture = mouseGesture;
        if (e.pointerType !== "mouse" || !gesture || e.button !== 0) {
          return;
        }
        mouseGesture = null;
        if (gesture.mode === "cancelled" || !scope.term) {
          return;
        }
        if (gesture.mode === "tracking") {
          const release = buildMouseButtonReport("release", e.clientX, e.clientY);
          if (release) {
            notify({ type: "terminal-input", bytes: release });
          }
          return;
        }
        if (gesture.mode === "selecting") {
          if (scope.sel) {
            scope.sel.activeHandle = null;
          }
          stopEdgeScroll();
          repositionOverlay();
          return;
        }
        if (dispatcherShouldBlockSurface()) {
          return;
        }
        if (gesture.dismissedSelection) {
          return;
        }
        notifyTerminalSurfaceTap(e.clientX, e.clientY, false);
      },
      true
    );
    targetSurface.addEventListener(
      "pointercancel",
      function(e) {
        if (e.pointerType !== "mouse") {
          return;
        }
        abandonMouseGesture();
      },
      true
    );
    targetSurface.addEventListener(
      "touchstart",
      function() {
        if (mouseGesture) {
          abandonMouseGesture();
        }
      },
      true
    );
  }
  scope.btnCopy.addEventListener("click", function(e) {
    e.preventDefault();
    e.stopPropagation();
    if (!scope.term) {
      return;
    }
    const text = scope.term.getSelection ? scope.term.getSelection() : "";
    if (text && text.length > 0) {
      notify({ type: "selection", text });
    } else {
      cancelSelect();
    }
  });
  scope.btnSelAll.addEventListener("click", function(e) {
    e.preventDefault();
    e.stopPropagation();
    if (!scope.term) {
      return;
    }
    try {
      scope.term.selectAll();
      const b = scope.term.buffer.active;
      scope.sel = {
        anchor: { col: 0, row: 0 },
        focus: { col: scope.term.cols - 1, row: b.length - 1 },
        activeHandle: null
      };
      repositionOverlay();
    } catch {
    }
  });
  const ts = {
    lastX: 0,
    lastY: 0,
    lastTime: 0,
    velY: 0,
    accumDelta: 0,
    momentumId: null,
    isPinching: false,
    pinchDist: 0,
    pinchScale: 0,
    pinchSurfX: 0,
    pinchSurfY: 0
  };
  function updateTouchVelocity(deltaY, dt) {
    if (dt <= 0) {
      return;
    }
    const instantVelocity = deltaY / dt;
    if (!Number.isFinite(instantVelocity)) {
      return;
    }
    ts.velY = ts.velY === 0 ? instantVelocity : ts.velY * 0.55 + instantVelocity * 0.45;
  }
  function getDistance(a, b) {
    const dx = a.clientX - b.clientX, dy = a.clientY - b.clientY;
    return Math.sqrt(dx * dx + dy * dy);
  }
  function attachSurfaceEventHandlers(targetSurface) {
    if (!targetSurface || targetSurface.__orcaSurfaceHandlersAttached) {
      return;
    }
    targetSurface.__orcaSurfaceHandlersAttached = true;
    targetSurface.addEventListener(
      "mousedown",
      function(e) {
        e.preventDefault();
        e.stopPropagation();
      },
      true
    );
    targetSurface.addEventListener(
      "click",
      function(e) {
        e.preventDefault();
        e.stopPropagation();
      },
      true
    );
    attachSurfaceWheelHandler(targetSurface);
    attachSurfaceMouseClickDragHandler(targetSurface);
    targetSurface.addEventListener(
      "touchstart",
      function(e) {
        if (dispatcherShouldBlockSurface()) {
          return;
        }
        if (ts.momentumId) {
          cancelAnimationFrame(ts.momentumId);
          ts.momentumId = null;
        }
        if (e.touches.length === 2) {
          ts.isPinching = true;
          scope.smoothScrollOffsetY = 0;
          ts.pinchDist = getDistance(e.touches[0], e.touches[1]);
          ts.pinchScale = scope.userScale;
          const mx = (e.touches[0].clientX + e.touches[1].clientX) / 2;
          const my = (e.touches[0].clientY + e.touches[1].clientY) / 2;
          const total = getTotalScale();
          ts.pinchSurfX = (mx - scope.panX) / total;
          ts.pinchSurfY = (my - scope.panY) / total;
        } else if (e.touches.length === 1) {
          ts.isPinching = false;
          ts.lastX = e.touches[0].clientX;
          ts.lastY = e.touches[0].clientY;
          ts.lastTime = Date.now();
          ts.velY = 0;
          ts.accumDelta = 0;
        }
      },
      { capture: true, passive: true }
    );
    targetSurface.addEventListener(
      "touchmove",
      function(e) {
        if (dispatcherShouldBlockSurface()) {
          return;
        }
        if (!scope.term) {
          return;
        }
        e.preventDefault();
        e.stopPropagation();
        if (e.touches.length === 2) {
          ts.isPinching = true;
          const dist = getDistance(e.touches[0], e.touches[1]);
          const mx = (e.touches[0].clientX + e.touches[1].clientX) / 2;
          const my = (e.touches[0].clientY + e.touches[1].clientY) / 2;
          const ratio = dist / ts.pinchDist;
          const loScale = scope.MIN_TEXT_SCALE / scope.currentTextScale;
          const hiScale = scope.MAX_TEXT_SCALE / scope.currentTextScale;
          scope.userScale = Math.max(loScale, Math.min(hiScale, ts.pinchScale * ratio));
          const total = getTotalScale();
          scope.panX = mx - ts.pinchSurfX * total;
          scope.panY = my - ts.pinchSurfY * total;
          clampPan();
          updateTransform();
        } else if (e.touches.length === 1 && !ts.isPinching) {
          const x = e.touches[0].clientX, y = e.touches[0].clientY;
          const now = Date.now(), dt = now - ts.lastTime;
          if (scope.term.element && scope.term.element.scrollWidth * getTotalScale() > window.innerWidth + 1) {
            scope.panX += x - ts.lastX;
            clampPan();
            updateTransform();
          }
          const deltaY = ts.lastY - y;
          ts.lastTime = now;
          if (shouldRouteScrollToTerminalInput()) {
            updateTouchVelocity(deltaY, dt);
            resetSmoothScrollOffset();
            const effectiveCellH = getCellHeight() * getTotalScale();
            ts.accumDelta += deltaY;
            const lines = Math.trunc(ts.accumDelta / effectiveCellH);
            if (lines !== 0) {
              ts.accumDelta -= lines * effectiveCellH;
              routeScrollLines(lines, x, y);
            }
          } else {
            if (enqueueNormalBufferScrollDelta(deltaY)) {
              updateTouchVelocity(deltaY, dt);
            } else {
              ts.velY = 0;
            }
          }
          ts.lastX = x;
          ts.lastY = y;
        }
      },
      { capture: true, passive: false }
    );
    targetSurface.addEventListener(
      "touchend",
      function(e) {
        if (dispatcherShouldBlockSurface()) {
          return;
        }
        if (!scope.term) {
          return;
        }
        if (ts.isPinching && e.touches.length < 2) {
          ts.isPinching = false;
          const target = snapToTextScalePreset(scope.currentTextScale * scope.userScale);
          const changed = target !== scope.currentTextScale;
          scope.userScale = 1;
          scope.panX = 0;
          scope.panY = 0;
          applyTextScale(target);
          updateTransform();
          notify({ type: "font-scale-changed", fontScale: target });
          if (changed) {
            notify({ type: "haptic", kind: "selection" });
          }
          if (e.touches.length === 1) {
            ts.lastX = e.touches[0].clientX;
            ts.lastY = e.touches[0].clientY;
            ts.lastTime = Date.now();
            ts.velY = 0;
            ts.accumDelta = 0;
          }
          return;
        }
        if (e.touches.length === 0) {
          let momentumStep = function() {
            vel *= FRICTION;
            if (Math.abs(vel) < MIN_VEL) {
              ts.momentumId = null;
              return;
            }
            const delta = vel * 16;
            if (shouldRouteScrollToTerminalInput()) {
              resetSmoothScrollOffset();
              const effectiveCellH = getCellHeight() * getTotalScale();
              ts.accumDelta += delta;
              const lines = Math.trunc(ts.accumDelta / effectiveCellH);
              if (lines !== 0) {
                ts.accumDelta -= lines * effectiveCellH;
                routeScrollLines(lines, ts.lastX, ts.lastY);
              }
            } else {
              if (!applyNormalBufferScrollDelta(delta)) {
                ts.momentumId = null;
                return;
              }
            }
            ts.momentumId = requestAnimationFrame(momentumStep);
          };
          let vel = ts.velY;
          const FRICTION = 0.972;
          const MIN_VEL = 0.012;
          if (Math.abs(vel) > MIN_VEL) {
            ts.momentumId = requestAnimationFrame(momentumStep);
          }
        }
      },
      { capture: true, passive: true }
    );
  }
  attachSurfaceEventHandlers(scope.surface);
  function handleIncomingMessage(e) {
    let msg;
    try {
      msg = typeof e.data === "string" ? JSON.parse(e.data) : e.data;
    } catch {
      return;
    }
    try {
      handleMsg(msg);
    } catch (ex) {
      reportEngineError(
        msg && msg.type === "init" ? "terminal init failed" : "terminal message failed",
        ex,
        msg && msg.type === "init" && !scope.everReady
      );
    }
  }
  window.addEventListener("message", handleIncomingMessage);
  document.addEventListener("message", handleIncomingMessage);
  window.addEventListener("resize", function() {
    applyFitScale("window-resize");
    adjustRowsForViewport();
    repositionOverlay();
    clampPan();
    updateTransform();
  });
  if (window.Terminal) {
    notify({ type: "web-ready" });
  } else {
    reportEngineError("terminal engine missing", "xterm failed to load", true);
  }
})();
</script>
</body>
</html>