// Force strict mode and setup for ESM
"use strict";
import {
  noteInteraction
} from "./chunk-MRO43B25.js";
import {
  require_jsx_runtime,
  use_stdin_default,
  use_stdout_default
} from "./chunk-4FRUXVSE.js";
import {
  require_react
} from "./chunk-KYMBIKIW.js";
import {
  sanitizeFilenameForDisplay
} from "./chunk-UVNBI7NN.js";
import {
  t
} from "./chunk-RYT2ET4O.js";
import {
  fetchGitDiff,
  findProviderByCredentials,
  resolveMetadataKey
} from "./chunk-IQ7FOOIH.js";
import {
  KittySequenceOverflowEvent,
  logKittySequenceOverflow
} from "./chunk-4IUH45NF.js";
import {
  createDebugLogger
} from "./chunk-AVQDCKNF.js";
import {
  init_esbuild_shims
} from "./chunk-A4BMJM77.js";
import {
  __name,
  __toESM
} from "./chunk-J2S4EL5Y.js";

// packages/cli/src/ui/contexts/KeypressContext.tsx
init_esbuild_shims();
var import_react3 = __toESM(require_react(), 1);
import readline from "node:readline";
import { PassThrough } from "node:stream";

// packages/cli/src/ui/utils/mouse.ts
init_esbuild_shims();
var ESC = "\x1B";
var SGR_EVENT_PREFIX = `${ESC}[<`;
var X11_EVENT_PREFIX = `${ESC}[M`;
var MAX_SGR_MOUSE_SEQUENCE_LENGTH = 50;
var SGR_MOUSE_REGEX = /^\x1b\[<(\d+);(\d+);(\d+)([mM])/;
function getEventName(buttonCode, isRelease) {
  const isMove = (buttonCode & 32) !== 0;
  if (buttonCode === 66) return "scroll-left";
  if (buttonCode === 67) return "scroll-right";
  if ((buttonCode & 64) === 64) {
    return (buttonCode & 1) === 0 ? "scroll-up" : "scroll-down";
  }
  if (isMove) return "move";
  const button = buttonCode & 3;
  const type = isRelease ? "release" : "press";
  switch (button) {
    case 0:
      return `left-${type}`;
    case 1:
      return `middle-${type}`;
    case 2:
      return `right-${type}`;
    default:
      return null;
  }
}
__name(getEventName, "getEventName");
function buttonFromCode(code) {
  switch (code & 3) {
    case 0:
      return "left";
    case 1:
      return "middle";
    case 2:
      return "right";
    default:
      return "none";
  }
}
__name(buttonFromCode, "buttonFromCode");
function parseSGRMouseEvent(buffer) {
  const match = buffer.match(SGR_MOUSE_REGEX);
  if (!match) return null;
  const buttonCode = parseInt(match[1], 10);
  const col = parseInt(match[2], 10);
  const row = parseInt(match[3], 10);
  const isRelease = match[4] === "m";
  const name = getEventName(buttonCode, isRelease);
  if (!name) return null;
  return {
    event: {
      name,
      col,
      row,
      shift: (buttonCode & 4) !== 0,
      meta: (buttonCode & 8) !== 0,
      ctrl: (buttonCode & 16) !== 0,
      button: buttonFromCode(buttonCode)
    },
    length: match[0].length
  };
}
__name(parseSGRMouseEvent, "parseSGRMouseEvent");
var ENABLE_SGR_MOUSE = {
  button: "\x1B[?1002h\x1B[?1006h",
  any: "\x1B[?1003h\x1B[?1006h"
};
var DISABLE_SGR_MOUSE = {
  button: "\x1B[?1006l\x1B[?1002l",
  any: "\x1B[?1006l\x1B[?1003l"
};
function enableMouseEvents(stdout, tracking = "button") {
  stdout.write(ENABLE_SGR_MOUSE[tracking]);
}
__name(enableMouseEvents, "enableMouseEvents");
function disableMouseEvents(stdout, tracking = "button") {
  stdout.write(DISABLE_SGR_MOUSE[tracking]);
}
__name(disableMouseEvents, "disableMouseEvents");

// packages/cli/src/ui/utils/platformConstants.ts
init_esbuild_shims();
var KITTY_CTRL_C = "[99;5u";
var KITTY_KEYCODE_ENTER = 13;
var KITTY_KEYCODE_NUMPAD_ENTER = 57414;
var KITTY_KEYCODE_TAB = 9;
var KITTY_KEYCODE_BACKSPACE = 127;
var KITTY_MODIFIER_BASE = 1;
var KITTY_MODIFIER_EVENT_TYPES_OFFSET = 128;
var MODIFIER_SHIFT_BIT = 1;
var MODIFIER_ALT_BIT = 2;
var MODIFIER_CTRL_BIT = 4;
var VSCODE_SHIFT_ENTER_SEQUENCE = "\\\r\n";
var BACKSLASH_ENTER_DETECTION_WINDOW_MS = 5;
var MAX_KITTY_SEQUENCE_LENGTH = 32;
var CHAR_CODE_ESC = 27;

// packages/cli/src/ui/utils/clipboardUtils.ts
init_esbuild_shims();
import * as fs from "node:fs/promises";
import { constants as fsConstants } from "node:fs";
import { execSync, spawn } from "node:child_process";
import * as path from "node:path";
import { randomUUID } from "node:crypto";

// packages/cli/src/utils/osc.ts
init_esbuild_shims();
var ESC2 = "\x1B";
var BEL = "\x07";
var ST = ESC2 + "\\";
var OSC_PREFIX = ESC2 + "]";
var SEP = ";";
var OSC = {
  /** iTerm2 notification / progress */
  ITERM2: 9,
  /** Kitty desktop notification protocol */
  KITTY: 99,
  /** Ghostty / cmux notification */
  GHOSTTY: 777
};
function detectTerminal() {
  const termProgram = process.env["TERM_PROGRAM"];
  switch (termProgram) {
    case "iTerm.app":
      return "iTerm.app";
    case "kitty":
      return "kitty";
    case "ghostty":
      return "ghostty";
    case "Apple_Terminal":
      return "Apple_Terminal";
    default:
      break;
  }
  if (process.env["TERM"] === "xterm-ghostty") {
    return "ghostty";
  }
  if (process.env["TERM"]?.includes("kitty")) {
    return "kitty";
  }
  if (process.env["KITTY_WINDOW_ID"]) return "kitty";
  return "unknown";
}
__name(detectTerminal, "detectTerminal");
function sanitizeOscPayload(text) {
  return text.replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f\x80-\x9f]/g, "");
}
__name(sanitizeOscPayload, "sanitizeOscPayload");
function osc(...parts) {
  const isKitty = detectTerminal() === "kitty";
  const inScreen = !!process.env["STY"];
  const terminator = isKitty && !inScreen ? ST : BEL;
  const sanitized = parts.map(
    (p) => typeof p === "string" ? sanitizeOscPayload(p) : p
  );
  return `${OSC_PREFIX}${sanitized.join(SEP)}${terminator}`;
}
__name(osc, "osc");
function wrapForMultiplexer(sequence) {
  if (process.env["TMUX"]) {
    const escaped = sequence.replaceAll("\x1B", "\x1B\x1B");
    return `\x1BPtmux;${escaped}\x1B\\`;
  }
  if (process.env["STY"]) {
    return `\x1BP${sequence}\x1B\\`;
  }
  return sequence;
}
__name(wrapForMultiplexer, "wrapForMultiplexer");
function encodeKittyPayload(text) {
  return Buffer.from(text, "utf8").toString("base64");
}
__name(encodeKittyPayload, "encodeKittyPayload");
function oscITerm2Notify(title, message) {
  const displayString = title ? `${title}:
${message}` : message;
  return osc(OSC.ITERM2, `

${displayString}`);
}
__name(oscITerm2Notify, "oscITerm2Notify");
function oscKittyNotify(title, message, id) {
  return [
    osc(OSC.KITTY, `i=${id}:d=0:p=title:e=1`, encodeKittyPayload(title)),
    osc(OSC.KITTY, `i=${id}:p=body:e=1`, encodeKittyPayload(message)),
    osc(OSC.KITTY, `i=${id}:d=1:a=focus`, "")
  ];
}
__name(oscKittyNotify, "oscKittyNotify");
function oscGhosttyNotify(title, message) {
  return osc(OSC.GHOSTTY, "notify", title, message);
}
__name(oscGhosttyNotify, "oscGhosttyNotify");
function generateKittyId() {
  return Math.floor(Math.random() * 2 ** 31);
}
__name(generateKittyId, "generateKittyId");

// packages/cli/src/ui/utils/clipboardUtils.ts
var debugLogger = createDebugLogger("CLIPBOARD_UTILS");
var PROCESS_TIMEOUT_MS = 5e3;
function writeOsc52(text) {
  try {
    const MAX_OSC52_BYTES = 75e3;
    if (Buffer.byteLength(text, "utf-8") > MAX_OSC52_BYTES) {
      debugLogger.warn(
        `writeOsc52: text too large (${Buffer.byteLength(text, "utf-8")} bytes), skipping`
      );
      return false;
    }
    const base64 = Buffer.from(text, "utf-8").toString("base64");
    const sequence = wrapForMultiplexer(`\x1B]52;c;${base64}\x07`);
    const stream = process.stderr.isTTY ? process.stderr : process.stdout.isTTY ? process.stdout : null;
    if (!stream) {
      debugLogger.warn(
        "OSC 52 clipboard requires a TTY; stdout/stderr not connected to terminal"
      );
      return false;
    }
    stream.write(sequence, (err) => {
      if (err) debugLogger.warn("writeOsc52: async write failed:", err);
    });
    return true;
  } catch (e) {
    debugLogger.warn("writeOsc52 failed:", e);
    return false;
  }
}
__name(writeOsc52, "writeOsc52");
var linuxClipboardTool;
var cachedWlPasteImageTypes = null;
var cachedClipboardModule = null;
var clipboardLoadAttempted = false;
async function getClipboardModule() {
  if (clipboardLoadAttempted) return cachedClipboardModule;
  clipboardLoadAttempted = true;
  try {
    const modName = "@teddyzhu/clipboard";
    cachedClipboardModule = await import(modName);
    return cachedClipboardModule;
  } catch (_e) {
    debugLogger.error(
      "Failed to load @teddyzhu/clipboard native module. Clipboard image features will be unavailable."
    );
    return null;
  }
}
__name(getClipboardModule, "getClipboardModule");
function getLinuxClipboardTool() {
  if (linuxClipboardTool !== void 0) return linuxClipboardTool;
  const sessionType = process.env["XDG_SESSION_TYPE"];
  const waylandDisplay = process.env["WAYLAND_DISPLAY"];
  const display = process.env["DISPLAY"];
  let toolName = null;
  if (sessionType === "wayland" || waylandDisplay) {
    toolName = "wl-paste";
  } else if (sessionType === "x11" || display) {
    toolName = "xclip";
  } else {
    linuxClipboardTool = null;
    return null;
  }
  try {
    execSync("command -v " + toolName, { stdio: "ignore" });
    linuxClipboardTool = toolName;
    return toolName;
  } catch {
    debugLogger.warn(`${toolName} not found`);
    linuxClipboardTool = null;
    return null;
  }
}
__name(getLinuxClipboardTool, "getLinuxClipboardTool");
async function saveFromCommand(command, args, destination) {
  let fd;
  try {
    fd = await fs.open(
      destination,
      fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_EXCL
    );
  } catch {
    return false;
  }
  return new Promise((resolve) => {
    const child = spawn(command, args, {
      stdio: ["ignore", "pipe", "pipe"]
    });
    const fileStream = fd.createWriteStream();
    let stderr = "";
    let resolved = false;
    const safeResolve = /* @__PURE__ */ __name((value) => {
      if (!resolved) {
        resolved = true;
        try {
          if (!child.killed) child.kill();
        } catch {
        }
        try {
          fileStream.destroy();
        } catch {
        }
        resolve(value);
      }
    }, "safeResolve");
    const timer = setTimeout(() => {
      debugLogger.debug(`${command} timed out after ${PROCESS_TIMEOUT_MS}ms`);
      safeResolve(false);
    }, PROCESS_TIMEOUT_MS);
    child.stderr.on("data", (data) => {
      stderr += data.toString();
    });
    child.stdout.pipe(fileStream);
    child.stdout.on("error", (err) => {
      debugLogger.debug(`stdout error for ${command}:`, err);
      clearTimeout(timer);
      safeResolve(false);
    });
    child.on("error", (err) => {
      debugLogger.debug(`Failed to spawn ${command}:`, err);
      clearTimeout(timer);
      safeResolve(false);
    });
    fileStream.on("error", (err) => {
      debugLogger.debug(`File stream error for ${destination}:`, err);
      clearTimeout(timer);
      safeResolve(false);
    });
    child.on("close", (code) => {
      clearTimeout(timer);
      if (resolved) return;
      if (code !== 0) {
        debugLogger.debug(
          `${command} exited with code ${code}. Args: ${args.join(" ")}`
        );
        if (stderr) debugLogger.debug(`${command} stderr: ${stderr.trim()}`);
        safeResolve(false);
        return;
      }
      const checkFile = /* @__PURE__ */ __name(() => {
        fs.stat(destination).then((stats) => {
          safeResolve(stats.size > 0);
        }).catch(() => {
          safeResolve(false);
        });
      }, "checkFile");
      if (fileStream.writableFinished) {
        checkFile();
      } else {
        fileStream.on("finish", checkFile);
        fileStream.on("close", () => {
          if (!resolved) checkFile();
        });
      }
    });
  });
}
__name(saveFromCommand, "saveFromCommand");
async function checkClipboardForImage(command, args) {
  if (command === "wl-paste" && args.length === 1 && args[0] === "--list-types") {
    const types = await getWlPasteImageTypes();
    return types.length > 0;
  }
  return new Promise((resolve) => {
    try {
      const child = spawn(command, args, {
        stdio: ["ignore", "pipe", "ignore"]
      });
      let stdout = "";
      const timer = setTimeout(() => {
        try {
          child.kill();
        } catch {
        }
        resolve(false);
      }, PROCESS_TIMEOUT_MS);
      child.stdout.on("data", (data) => {
        stdout += data.toString();
      });
      child.on("close", (code) => {
        clearTimeout(timer);
        resolve(
          code === 0 && stdout.split("\n").some((line) => line === "image/png" || line === "image/bmp")
        );
      });
      child.on("error", () => {
        clearTimeout(timer);
        resolve(false);
      });
    } catch {
      resolve(false);
    }
  });
}
__name(checkClipboardForImage, "checkClipboardForImage");
async function clipboardHasImage() {
  cachedWlPasteImageTypes = null;
  if (process.platform === "linux") {
    try {
      const tool = getLinuxClipboardTool();
      if (tool === "wl-paste") {
        return checkClipboardForImage("wl-paste", ["--list-types"]);
      }
      if (tool === "xclip") {
        return checkClipboardForImage("xclip", [
          "-selection",
          "clipboard",
          "-t",
          "TARGETS",
          "-o"
        ]);
      }
    } catch (error) {
      debugLogger.error("Error checking clipboard for image:", error);
    }
    return false;
  }
  try {
    const mod = await getClipboardModule();
    if (!mod) return false;
    const clipboard = new mod.ClipboardManager();
    return clipboard.hasFormat("image");
  } catch (error) {
    debugLogger.error("Error checking clipboard for image:", error);
    return false;
  }
}
__name(clipboardHasImage, "clipboardHasImage");
async function getWlPasteImageTypes() {
  if (cachedWlPasteImageTypes !== null) {
    return cachedWlPasteImageTypes;
  }
  return new Promise((resolve) => {
    const child = spawn("wl-paste", ["--list-types"], {
      stdio: ["ignore", "pipe", "ignore"]
    });
    let stdout = "";
    const timer = setTimeout(() => {
      try {
        child.kill();
      } catch {
      }
      resolve([]);
    }, PROCESS_TIMEOUT_MS);
    child.stdout.on("data", (data) => {
      stdout += data.toString();
    });
    child.on("close", (code) => {
      clearTimeout(timer);
      if (code !== 0) {
        resolve([]);
        return;
      }
      const types = stdout.trim().split("\n").filter((t2) => t2 === "image/png" || t2 === "image/bmp");
      cachedWlPasteImageTypes = types;
      resolve(types);
    });
    child.on("error", () => {
      clearTimeout(timer);
      resolve([]);
    });
  });
}
__name(getWlPasteImageTypes, "getWlPasteImageTypes");
async function saveFileWithWlPaste(tempFilePath) {
  const imageTypes = await getWlPasteImageTypes();
  if (imageTypes.includes("image/png")) {
    const success = await saveFromCommand(
      "wl-paste",
      ["--no-newline", "--type", "image/png"],
      tempFilePath
    );
    if (success) return tempFilePath;
    try {
      await fs.unlink(tempFilePath);
    } catch {
    }
  }
  if (imageTypes.includes("image/bmp")) {
    const bmpPath = tempFilePath.replace(/\.png$/, ".bmp");
    const bmpSuccess = await saveFromCommand(
      "wl-paste",
      ["--no-newline", "--type", "image/bmp"],
      bmpPath
    );
    if (bmpSuccess) {
      try {
        await new Promise((resolve, reject) => {
          const child = spawn(
            "python3",
            [
              "-c",
              "import sys; from PIL import Image; Image.open(sys.argv[1]).save(sys.argv[2])",
              bmpPath,
              tempFilePath
            ],
            { stdio: ["ignore", "ignore", "pipe"] }
          );
          let stderr = "";
          child.stderr.on("data", (d) => {
            stderr += d.toString();
          });
          const timer = setTimeout(() => {
            try {
              child.kill();
            } catch {
            }
            reject(new Error("python3 timed out"));
          }, PROCESS_TIMEOUT_MS);
          child.on("close", (code) => {
            clearTimeout(timer);
            if (code === 0) resolve();
            else
              reject(
                new Error(
                  `python3 exited with code ${code}${stderr ? ": " + stderr.trim() : ""}`
                )
              );
          });
          child.on("error", (err) => {
            clearTimeout(timer);
            reject(err);
          });
        });
        try {
          await fs.unlink(bmpPath);
        } catch {
        }
        return tempFilePath;
      } catch (err) {
        debugLogger.warn(
          "BMP-to-PNG conversion failed (install python3-pil for BMP support):",
          err
        );
        try {
          await fs.unlink(bmpPath);
        } catch {
        }
        try {
          await fs.unlink(tempFilePath);
        } catch {
        }
        return false;
      }
    }
    try {
      await fs.unlink(bmpPath);
    } catch {
    }
  }
  return false;
}
__name(saveFileWithWlPaste, "saveFileWithWlPaste");
async function saveFileWithXclip(tempFilePath) {
  const success = await saveFromCommand(
    "xclip",
    ["-selection", "clipboard", "-t", "image/png", "-o"],
    tempFilePath
  );
  if (success) return true;
  try {
    await fs.unlink(tempFilePath);
  } catch {
  }
  return false;
}
__name(saveFileWithXclip, "saveFileWithXclip");
async function saveClipboardImage(targetDir) {
  try {
    const baseDir = targetDir || process.cwd();
    const tempDir = path.join(baseDir, "clipboard");
    await fs.mkdir(tempDir, { recursive: true });
    const timestamp = (/* @__PURE__ */ new Date()).getTime();
    if (process.platform === "linux") {
      const pngPath = path.join(
        tempDir,
        `clipboard-${timestamp}-${randomUUID()}.png`
      );
      const tool = getLinuxClipboardTool();
      if (tool === "wl-paste") {
        const savedPath = await saveFileWithWlPaste(pngPath);
        if (savedPath) {
          try {
            const stats = await fs.stat(savedPath);
            if (stats.size > 0) return savedPath;
            await fs.unlink(savedPath);
          } catch {
          }
        }
        return null;
      }
      if (tool === "xclip") {
        if (await saveFileWithXclip(pngPath)) return pngPath;
        return null;
      }
      return null;
    }
    const mod = await getClipboardModule();
    if (!mod) return null;
    const clipboard = new mod.ClipboardManager();
    if (!clipboard.hasFormat("image")) {
      return null;
    }
    const tempFilePath = path.join(
      tempDir,
      `clipboard-${timestamp}-${randomUUID()}.png`
    );
    const imageData = clipboard.getImageData();
    const buffer = imageData.data;
    if (!buffer) {
      return null;
    }
    await fs.writeFile(tempFilePath, buffer);
    return tempFilePath;
  } catch (error) {
    debugLogger.error("Error saving clipboard image:", error);
    return null;
  }
}
__name(saveClipboardImage, "saveClipboardImage");
async function cleanupOldClipboardImages(targetDir) {
  try {
    const baseDir = targetDir || process.cwd();
    const tempDir = path.join(baseDir, "clipboard");
    const files = await fs.readdir(tempDir);
    const MAX_IMAGES = 100;
    const CLEANUP_COUNT = 50;
    const imageFiles = [];
    for (const file of files) {
      if (file.startsWith("clipboard-") && (file.endsWith(".png") || file.endsWith(".jpg") || file.endsWith(".webp") || file.endsWith(".heic") || file.endsWith(".heif") || file.endsWith(".tiff") || file.endsWith(".gif") || file.endsWith(".bmp"))) {
        const filePath = path.join(tempDir, file);
        const stats = await fs.stat(filePath);
        imageFiles.push({
          name: file,
          path: filePath,
          atime: stats.atimeMs
        });
      }
    }
    if (imageFiles.length > MAX_IMAGES) {
      imageFiles.sort((a, b) => a.atime - b.atime);
      const removeCount = Math.min(
        CLEANUP_COUNT,
        imageFiles.length - MAX_IMAGES + CLEANUP_COUNT
      );
      const filesToRemove = imageFiles.slice(0, removeCount);
      for (const file of filesToRemove) {
        await fs.unlink(file.path);
      }
    }
  } catch {
  }
}
__name(cleanupOldClipboardImages, "cleanupOldClipboardImages");

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

// packages/cli/src/ui/hooks/useKeypress.ts
init_esbuild_shims();
var import_react = __toESM(require_react(), 1);
function useKeypress(onKeypress, { isActive }) {
  const { subscribe, unsubscribe } = useKeypressContext();
  const onKeypressRef = (0, import_react.useRef)(onKeypress);
  onKeypressRef.current = onKeypress;
  const handleKeypress = (0, import_react.useCallback)((key) => {
    onKeypressRef.current(key);
  }, []);
  (0, import_react.useEffect)(() => {
    if (!isActive) {
      return;
    }
    subscribe(handleKeypress);
    return () => {
      unsubscribe(handleKeypress);
    };
  }, [isActive, handleKeypress, subscribe, unsubscribe]);
}
__name(useKeypress, "useKeypress");

// packages/cli/src/ui/hooks/useFocus.ts
var ENABLE_FOCUS_REPORTING = "\x1B[?1004h";
var DISABLE_FOCUS_REPORTING = "\x1B[?1004l";
var FOCUS_IN = "\x1B[I";
var FOCUS_OUT = "\x1B[O";
var useFocus = /* @__PURE__ */ __name(() => {
  const { stdin } = use_stdin_default();
  const { stdout } = use_stdout_default();
  const [isFocused, setIsFocused] = (0, import_react2.useState)(true);
  (0, import_react2.useEffect)(() => {
    const handleData = /* @__PURE__ */ __name((data) => {
      const sequence = data.toString();
      const lastFocusIn = sequence.lastIndexOf(FOCUS_IN);
      const lastFocusOut = sequence.lastIndexOf(FOCUS_OUT);
      if (lastFocusIn > lastFocusOut) {
        setIsFocused(true);
      } else if (lastFocusOut > lastFocusIn) {
        setIsFocused(false);
      }
    }, "handleData");
    stdout?.write(ENABLE_FOCUS_REPORTING);
    stdin?.on("data", handleData);
    return () => {
      stdout?.write(DISABLE_FOCUS_REPORTING);
      stdin?.removeListener("data", handleData);
    };
  }, [stdin, stdout]);
  useKeypress(
    (_) => {
      if (!isFocused) {
        setIsFocused(true);
      }
    },
    { isActive: true }
  );
  return isFocused;
}, "useFocus");

// packages/cli/src/ui/contexts/KeypressContext.tsx
var import_jsx_runtime = __toESM(require_jsx_runtime(), 1);
var ESC3 = "\x1B";
var OPTION_T_COMPOSED_GLYPH = "\u2020";
var PASTE_MODE_PREFIX = `${ESC3}[200~`;
var PASTE_MODE_SUFFIX = `${ESC3}[201~`;
var KITTY_SEQUENCE_TIMEOUT_MS = 200;
var PASTE_IDLE_TIMEOUT_MS = 1e3;
var KITTY_KEYPAD_PRINTABLE_KEYCODE_TO_CHAR = {
  57399: "0",
  57400: "1",
  57401: "2",
  57402: "3",
  57403: "4",
  57404: "5",
  57405: "6",
  57406: "7",
  57407: "8",
  57408: "9",
  57409: ".",
  57410: "/",
  57411: "*",
  57412: "-",
  57413: "+",
  // 57414 is keypad Enter - handled separately via CSI~ sequence
  57415: "=",
  57416: ","
};
var KITTY_KEYPAD_FUNCTIONAL_KEYCODE_TO_NAME = {
  57417: "left",
  57418: "right",
  57419: "up",
  57420: "down",
  57421: "pageup",
  57422: "pagedown",
  57423: "home",
  57424: "end",
  57425: "insert",
  57426: "delete"
};
var KeypressContext = (0, import_react3.createContext)(
  void 0
);
var debugLogger2 = createDebugLogger("KEYPRESS");
function useKeypressContext() {
  const context = (0, import_react3.useContext)(KeypressContext);
  if (!context) {
    throw new Error(
      "useKeypressContext must be used within a KeypressProvider"
    );
  }
  return context;
}
__name(useKeypressContext, "useKeypressContext");
function KeypressProvider({
  children,
  kittyProtocolEnabled,
  pasteWorkaround = false,
  config,
  debugKeystrokeLogging,
  initialCapturedInput
}) {
  const { stdin, setRawMode } = use_stdin_default();
  const subscribers = (0, import_react3.useRef)(/* @__PURE__ */ new Set()).current;
  const mouseSubscribers = (0, import_react3.useRef)(/* @__PURE__ */ new Set()).current;
  const subscribe = (0, import_react3.useCallback)(
    (handler) => {
      subscribers.add(handler);
    },
    [subscribers]
  );
  const unsubscribe = (0, import_react3.useCallback)(
    (handler) => {
      subscribers.delete(handler);
    },
    [subscribers]
  );
  const subscribeMouse = (0, import_react3.useCallback)(
    (handler) => {
      mouseSubscribers.add(handler);
    },
    [mouseSubscribers]
  );
  const unsubscribeMouse = (0, import_react3.useCallback)(
    (handler) => {
      mouseSubscribers.delete(handler);
    },
    [mouseSubscribers]
  );
  (0, import_react3.useEffect)(() => {
    setRawMode(true);
    const capturedInput = initialCapturedInput ?? Buffer.alloc(0);
    const keypressStream = new PassThrough();
    let usePassthrough = false;
    if (pasteWorkaround) {
      usePassthrough = true;
    }
    let isPaste = false;
    let pasteBuffer = Buffer.alloc(0);
    let pasteAlreadyFlushed = false;
    let pasteIdleTimeout = null;
    const kittySequenceBufferRef = { current: "" };
    let kittySequenceTimeout = null;
    let backslashTimeout = null;
    let waitingForEnterAfterBackslash = false;
    let rawDataBuffer = Buffer.alloc(0);
    let rawFlushTimeout = null;
    let swallowingSgrMouse = false;
    let sgrMouseBuffer = "";
    let sgrMouseTimeout = null;
    const resetSgrMouse = /* @__PURE__ */ __name(() => {
      swallowingSgrMouse = false;
      sgrMouseBuffer = "";
      if (sgrMouseTimeout) {
        clearTimeout(sgrMouseTimeout);
        sgrMouseTimeout = null;
      }
    }, "resetSgrMouse");
    const updateKittyBuffer = /* @__PURE__ */ __name((value) => {
      kittySequenceBufferRef.current = value;
    }, "updateKittyBuffer");
    const clearKittyTimeout = /* @__PURE__ */ __name(() => {
      if (kittySequenceTimeout) {
        clearTimeout(kittySequenceTimeout);
        kittySequenceTimeout = null;
      }
    }, "clearKittyTimeout");
    const startKittyTimeout = /* @__PURE__ */ __name(() => {
      clearKittyTimeout();
      kittySequenceTimeout = setTimeout(() => {
        if (kittySequenceBufferRef.current) {
          while (kittySequenceBufferRef.current) {
            const parsed = parseKittyPrefix(kittySequenceBufferRef.current);
            if (parsed) {
              kittySequenceBufferRef.current = kittySequenceBufferRef.current.slice(parsed.length);
              broadcast(parsed.key);
              continue;
            }
            const plain = parsePlainTextPrefix(kittySequenceBufferRef.current);
            if (plain) {
              kittySequenceBufferRef.current = kittySequenceBufferRef.current.slice(plain.length);
              broadcast(plain.key);
              continue;
            }
            break;
          }
          if (kittySequenceBufferRef.current) {
            if (debugKeystrokeLogging) {
              debugLogger2.debug(
                "[DEBUG] Kitty buffer timeout, clearing:",
                kittySequenceBufferRef.current
              );
            }
            kittySequenceBufferRef.current = "";
          }
        }
      }, KITTY_SEQUENCE_TIMEOUT_MS);
    }, "startKittyTimeout");
    const clearKittyBufferAndTimeout = /* @__PURE__ */ __name(() => {
      clearKittyTimeout();
      kittySequenceBufferRef.current = "";
    }, "clearKittyBufferAndTimeout");
    const clearPasteIdleTimeout = /* @__PURE__ */ __name(() => {
      if (pasteIdleTimeout) {
        clearTimeout(pasteIdleTimeout);
        pasteIdleTimeout = null;
      }
    }, "clearPasteIdleTimeout");
    const forceFlushStuckPaste = /* @__PURE__ */ __name(() => {
      clearPasteIdleTimeout();
      if (!isPaste && pasteBuffer.length === 0) return;
      const buffered = pasteBuffer.toString();
      isPaste = false;
      pasteBuffer = Buffer.alloc(0);
      pasteAlreadyFlushed = true;
      if (buffered.length > 0) {
        broadcast({
          name: "",
          ctrl: false,
          meta: false,
          shift: false,
          paste: true,
          sequence: buffered
        });
      }
    }, "forceFlushStuckPaste");
    const startPasteIdleTimeout = /* @__PURE__ */ __name(() => {
      clearPasteIdleTimeout();
      pasteIdleTimeout = setTimeout(
        forceFlushStuckPaste,
        PASTE_IDLE_TIMEOUT_MS
      );
    }, "startPasteIdleTimeout");
    const createPrintableKey = /* @__PURE__ */ __name((char) => {
      const printableName = char === " " ? "space" : /^[A-Za-z]$/.test(char) ? char.toLowerCase() : char;
      return {
        name: printableName,
        ctrl: false,
        meta: false,
        shift: false,
        paste: false,
        sequence: char,
        kittyProtocol: true
      };
    }, "createPrintableKey");
    const parseKittyPrefix = /* @__PURE__ */ __name((buffer) => {
      const revTabLegacy = new RegExp(`^${ESC3}\\[Z`);
      let m = buffer.match(revTabLegacy);
      if (m) {
        return {
          key: {
            name: "tab",
            ctrl: false,
            meta: false,
            shift: true,
            paste: false,
            sequence: buffer.slice(0, m[0].length),
            kittyProtocol: true
          },
          length: m[0].length
        };
      }
      const revTabParam = new RegExp(`^${ESC3}\\[1;(\\d+)Z`);
      m = buffer.match(revTabParam);
      if (m) {
        let mods = parseInt(m[1], 10);
        if (mods >= KITTY_MODIFIER_EVENT_TYPES_OFFSET) {
          mods -= KITTY_MODIFIER_EVENT_TYPES_OFFSET;
        }
        const bits = mods - KITTY_MODIFIER_BASE;
        const alt = (bits & MODIFIER_ALT_BIT) === MODIFIER_ALT_BIT;
        const ctrl = (bits & MODIFIER_CTRL_BIT) === MODIFIER_CTRL_BIT;
        return {
          key: {
            name: "tab",
            ctrl,
            meta: alt,
            // Reverse tab implies Shift behavior; force shift regardless of mods
            shift: true,
            paste: false,
            sequence: buffer.slice(0, m[0].length),
            kittyProtocol: true
          },
          length: m[0].length
        };
      }
      const arrowPrefix = new RegExp(`^${ESC3}\\[1;(\\d+)([ABCDHFPQSR])`);
      m = buffer.match(arrowPrefix);
      if (m) {
        let mods = parseInt(m[1], 10);
        if (mods >= KITTY_MODIFIER_EVENT_TYPES_OFFSET) {
          mods -= KITTY_MODIFIER_EVENT_TYPES_OFFSET;
        }
        const bits = mods - KITTY_MODIFIER_BASE;
        const shift = (bits & MODIFIER_SHIFT_BIT) === MODIFIER_SHIFT_BIT;
        const alt = (bits & MODIFIER_ALT_BIT) === MODIFIER_ALT_BIT;
        const ctrl = (bits & MODIFIER_CTRL_BIT) === MODIFIER_CTRL_BIT;
        const sym = m[2];
        const symbolToName = {
          A: "up",
          B: "down",
          C: "right",
          D: "left",
          H: "home",
          F: "end",
          P: "f1",
          Q: "f2",
          R: "f3",
          S: "f4"
        };
        const name = symbolToName[sym] || "";
        if (!name) return null;
        return {
          key: {
            name,
            ctrl,
            meta: alt,
            shift,
            paste: false,
            sequence: buffer.slice(0, m[0].length),
            kittyProtocol: true
          },
          length: m[0].length
        };
      }
      const csiUPrefix = new RegExp(
        `^${ESC3}\\[(\\d+)(?::\\d+)*(?:;(\\d+)(?::\\d+)*)?(?:;\\d+)?([u~])`
      );
      m = buffer.match(csiUPrefix);
      if (m) {
        const keyCode = parseInt(m[1], 10);
        let modifiers = m[2] ? parseInt(m[2], 10) : KITTY_MODIFIER_BASE;
        if (modifiers >= KITTY_MODIFIER_EVENT_TYPES_OFFSET) {
          modifiers -= KITTY_MODIFIER_EVENT_TYPES_OFFSET;
        }
        const modifierBits = modifiers - KITTY_MODIFIER_BASE;
        const shift = (modifierBits & MODIFIER_SHIFT_BIT) === MODIFIER_SHIFT_BIT;
        const alt = (modifierBits & MODIFIER_ALT_BIT) === MODIFIER_ALT_BIT;
        const ctrl = (modifierBits & MODIFIER_CTRL_BIT) === MODIFIER_CTRL_BIT;
        const terminator = m[3];
        if (terminator === "~") {
          let name2 = null;
          switch (keyCode) {
            case 1:
              name2 = "home";
              break;
            case 2:
              name2 = "insert";
              break;
            case 3:
              name2 = "delete";
              break;
            case 4:
              name2 = "end";
              break;
            case 5:
              name2 = "pageup";
              break;
            case 6:
              name2 = "pagedown";
              break;
            default:
              break;
          }
          if (name2) {
            return {
              key: {
                name: name2,
                ctrl,
                meta: alt,
                shift,
                paste: false,
                sequence: buffer.slice(0, m[0].length),
                kittyProtocol: true
              },
              length: m[0].length
            };
          }
        }
        const kittyKeyCodeToName = {
          [CHAR_CODE_ESC]: "escape",
          [KITTY_KEYCODE_TAB]: "tab",
          [KITTY_KEYCODE_BACKSPACE]: "backspace",
          [KITTY_KEYCODE_ENTER]: "return",
          [KITTY_KEYCODE_NUMPAD_ENTER]: "return"
        };
        const name = kittyKeyCodeToName[keyCode];
        if (name) {
          return {
            key: {
              name,
              ctrl,
              meta: alt,
              shift,
              paste: false,
              sequence: buffer.slice(0, m[0].length),
              kittyProtocol: true
            },
            length: m[0].length
          };
        }
        if (!ctrl) {
          const keypadChar = KITTY_KEYPAD_PRINTABLE_KEYCODE_TO_CHAR[keyCode];
          if (keypadChar) {
            return {
              key: {
                name: keypadChar,
                ctrl: false,
                meta: alt,
                shift,
                paste: false,
                sequence: keypadChar,
                kittyProtocol: true
              },
              length: m[0].length
            };
          }
        }
        const keypadName = KITTY_KEYPAD_FUNCTIONAL_KEYCODE_TO_NAME[keyCode];
        if (keypadName) {
          return {
            key: {
              name: keypadName,
              ctrl,
              meta: alt,
              shift,
              paste: false,
              sequence: buffer.slice(0, m[0].length),
              kittyProtocol: true
            },
            length: m[0].length
          };
        }
        if (terminator === "u" && !ctrl && keyCode >= 32 && keyCode !== 127 && keyCode <= 1114111 && !(keyCode >= 57344 && keyCode <= 63743)) {
          return {
            key: {
              ...createPrintableKey(String.fromCodePoint(keyCode)),
              meta: alt,
              shift
            },
            length: m[0].length
          };
        }
        if (ctrl && keyCode >= "a".charCodeAt(0) && keyCode <= "z".charCodeAt(0)) {
          const letter = String.fromCharCode(keyCode);
          return {
            key: {
              name: letter,
              ctrl: true,
              meta: alt,
              shift,
              paste: false,
              sequence: buffer.slice(0, m[0].length),
              kittyProtocol: true
            },
            length: m[0].length
          };
        }
      }
      const legacyFuncKey = new RegExp(`^${ESC3}\\[([ABCDHF])`);
      m = buffer.match(legacyFuncKey);
      if (m) {
        const sym = m[1];
        const nameMap = {
          A: "up",
          B: "down",
          C: "right",
          D: "left",
          H: "home",
          F: "end"
        };
        const name = nameMap[sym];
        return {
          key: {
            name,
            ctrl: false,
            meta: false,
            shift: false,
            paste: false,
            sequence: buffer.slice(0, m[0].length),
            kittyProtocol: true
          },
          length: m[0].length
        };
      }
      return null;
    }, "parseKittyPrefix");
    const getCompleteCsiSequenceLength = /* @__PURE__ */ __name((buffer) => {
      if (!buffer.startsWith(`${ESC3}[`)) {
        return null;
      }
      for (let i = 2; i < buffer.length; i++) {
        const code = buffer.charCodeAt(i);
        if (code >= 64 && code <= 126) {
          return i + 1;
        }
        if (code < 32 || code > 63) {
          return 0;
        }
      }
      return null;
    }, "getCompleteCsiSequenceLength");
    const parsePlainTextPrefix = /* @__PURE__ */ __name((buffer) => {
      if (!buffer || buffer.startsWith(ESC3)) {
        return null;
      }
      const [char] = Array.from(buffer);
      if (!char) {
        return null;
      }
      return {
        key: createPrintableKey(char),
        length: char.length
      };
    }, "parsePlainTextPrefix");
    const broadcast = /* @__PURE__ */ __name((key) => {
      noteInteraction();
      for (const handler of subscribers) {
        handler(key);
      }
    }, "broadcast");
    const TERMINAL_RESPONSE_RE = /^\x1b\[[?>][\d;]*[uc]$/;
    const handleKeypress = /* @__PURE__ */ __name(async (_, key) => {
      if (TERMINAL_RESPONSE_RE.test(key.sequence)) {
        return;
      }
      if (key.sequence === FOCUS_IN || key.sequence === FOCUS_OUT) {
        return;
      }
      if (isPaste) {
        resetSgrMouse();
      } else if (swallowingSgrMouse) {
        if (key.ctrl && key.name === "c") {
          resetSgrMouse();
        } else if (key.name === "paste-start") {
          resetSgrMouse();
        } else {
          sgrMouseBuffer += key.sequence;
          if (key.name === "m" || key.sequence === "M") {
            swallowingSgrMouse = false;
            if (sgrMouseTimeout) {
              clearTimeout(sgrMouseTimeout);
              sgrMouseTimeout = null;
            }
            const parsed = parseSGRMouseEvent(sgrMouseBuffer);
            if (parsed) {
              for (const handler of mouseSubscribers) {
                handler(parsed.event);
              }
            }
            sgrMouseBuffer = "";
          } else if (sgrMouseBuffer.length >= MAX_SGR_MOUSE_SEQUENCE_LENGTH) {
            resetSgrMouse();
          }
          return;
        }
      }
      if (!isPaste && key.sequence === `${ESC3}[<`) {
        swallowingSgrMouse = true;
        sgrMouseBuffer = `${ESC3}[<`;
        if (sgrMouseTimeout) {
          clearTimeout(sgrMouseTimeout);
        }
        sgrMouseTimeout = setTimeout(() => {
          swallowingSgrMouse = false;
          sgrMouseBuffer = "";
          sgrMouseTimeout = null;
        }, KITTY_SEQUENCE_TIMEOUT_MS);
        return;
      }
      const isCtrlCKey = key.ctrl && key.name === "c" || key.sequence === `${ESC3}${KITTY_CTRL_C}`;
      if (isCtrlCKey) {
        if (isPaste || pasteBuffer.length > 0) {
          isPaste = false;
          pasteBuffer = Buffer.alloc(0);
          pasteAlreadyFlushed = true;
          clearPasteIdleTimeout();
        }
        if (kittySequenceBufferRef.current && debugKeystrokeLogging) {
          debugLogger2.debug(
            "[DEBUG] Kitty buffer cleared on Ctrl+C:",
            kittySequenceBufferRef.current
          );
        }
        clearKittyBufferAndTimeout();
        if (key.sequence === `${ESC3}${KITTY_CTRL_C}`) {
          broadcast({
            name: "c",
            ctrl: true,
            meta: false,
            shift: false,
            paste: false,
            sequence: key.sequence,
            kittyProtocol: true
          });
        } else {
          broadcast(key);
        }
        return;
      }
      if (key.name === "paste-start") {
        isPaste = true;
        pasteAlreadyFlushed = false;
        startPasteIdleTimeout();
        return;
      }
      if (key.name === "paste-end") {
        clearPasteIdleTimeout();
        if (pasteAlreadyFlushed) {
          pasteAlreadyFlushed = false;
          isPaste = false;
          pasteBuffer = Buffer.alloc(0);
          return;
        }
        isPaste = false;
        if (pasteBuffer.toString().length > 0) {
          broadcast({
            name: "",
            ctrl: false,
            meta: false,
            shift: false,
            paste: true,
            sequence: pasteBuffer.toString()
          });
        } else {
          const hasImage = await clipboardHasImage();
          broadcast({
            name: "",
            ctrl: false,
            meta: false,
            shift: false,
            paste: true,
            pasteImage: hasImage,
            sequence: pasteBuffer.toString()
          });
        }
        pasteBuffer = Buffer.alloc(0);
        return;
      }
      if (isPaste) {
        pasteBuffer = Buffer.concat([pasteBuffer, Buffer.from(key.sequence)]);
        startPasteIdleTimeout();
        return;
      }
      if (key.name === "return" && waitingForEnterAfterBackslash) {
        if (backslashTimeout) {
          clearTimeout(backslashTimeout);
          backslashTimeout = null;
        }
        waitingForEnterAfterBackslash = false;
        broadcast({
          ...key,
          shift: true,
          sequence: "\r"
          // Corrected escaping for newline
        });
        return;
      }
      if (key.sequence === "\\" && !key.name) {
        waitingForEnterAfterBackslash = true;
        backslashTimeout = setTimeout(() => {
          waitingForEnterAfterBackslash = false;
          backslashTimeout = null;
          broadcast(key);
        }, BACKSLASH_ENTER_DETECTION_WINDOW_MS);
        return;
      }
      if (waitingForEnterAfterBackslash && key.name !== "return") {
        if (backslashTimeout) {
          clearTimeout(backslashTimeout);
          backslashTimeout = null;
        }
        waitingForEnterAfterBackslash = false;
        broadcast({
          name: "",
          sequence: "\\",
          ctrl: false,
          meta: false,
          shift: false,
          paste: false
        });
      }
      if (["up", "down", "left", "right"].includes(key.name)) {
        broadcast(key);
        return;
      }
      if (kittyProtocolEnabled) {
        if (kittySequenceBufferRef.current || key.sequence.startsWith(`${ESC3}[`) && !key.sequence.startsWith(PASTE_MODE_PREFIX) && !key.sequence.startsWith(PASTE_MODE_SUFFIX) && !key.sequence.startsWith(FOCUS_IN) && !key.sequence.startsWith(FOCUS_OUT)) {
          updateKittyBuffer(kittySequenceBufferRef.current + key.sequence);
          startKittyTimeout();
          if (debugKeystrokeLogging) {
            debugLogger2.debug(
              "[DEBUG] Kitty buffer accumulating:",
              kittySequenceBufferRef.current
            );
          }
          let bufferedInputHandled = false;
          while (kittySequenceBufferRef.current) {
            const parsed = parseKittyPrefix(kittySequenceBufferRef.current);
            if (parsed) {
              if (debugKeystrokeLogging) {
                const parsedSequence = kittySequenceBufferRef.current.slice(
                  0,
                  parsed.length
                );
                if (kittySequenceBufferRef.current.length > parsed.length) {
                  debugLogger2.debug(
                    "[DEBUG] Kitty sequence parsed successfully (prefix):",
                    parsedSequence
                  );
                } else {
                  debugLogger2.debug(
                    "[DEBUG] Kitty sequence parsed successfully:",
                    parsedSequence
                  );
                }
              }
              updateKittyBuffer(
                kittySequenceBufferRef.current.slice(parsed.length)
              );
              if (!kittySequenceBufferRef.current) {
                clearKittyTimeout();
              }
              broadcast(parsed.key);
              bufferedInputHandled = true;
              continue;
            }
            const completeUnsupportedCsiLength = getCompleteCsiSequenceLength(
              kittySequenceBufferRef.current
            );
            if (completeUnsupportedCsiLength) {
              if (debugKeystrokeLogging) {
                debugLogger2.debug(
                  "[DEBUG] Dropping unsupported complete CSI sequence:",
                  kittySequenceBufferRef.current.slice(
                    0,
                    completeUnsupportedCsiLength
                  )
                );
              }
              updateKittyBuffer(
                kittySequenceBufferRef.current.slice(
                  completeUnsupportedCsiLength
                )
              );
              if (!kittySequenceBufferRef.current) {
                clearKittyTimeout();
              }
              bufferedInputHandled = true;
              continue;
            }
            const plainTextPrefix = parsePlainTextPrefix(
              kittySequenceBufferRef.current
            );
            if (plainTextPrefix) {
              if (debugKeystrokeLogging) {
                debugLogger2.debug(
                  "[DEBUG] Recovered plain text after kitty sequence:",
                  plainTextPrefix.key.sequence
                );
              }
              updateKittyBuffer(
                kittySequenceBufferRef.current.slice(plainTextPrefix.length)
              );
              if (!kittySequenceBufferRef.current) {
                clearKittyTimeout();
              }
              broadcast(plainTextPrefix.key);
              bufferedInputHandled = true;
              continue;
            }
            const nextStart = kittySequenceBufferRef.current.indexOf(
              `${ESC3}[`,
              1
            );
            if (nextStart > 0) {
              if (debugKeystrokeLogging) {
                debugLogger2.debug(
                  "[DEBUG] Skipping incomplete/invalid CSI prefix:",
                  kittySequenceBufferRef.current.slice(0, nextStart)
                );
              }
              updateKittyBuffer(
                kittySequenceBufferRef.current.slice(nextStart)
              );
              if (!kittySequenceBufferRef.current) {
                clearKittyTimeout();
              }
              bufferedInputHandled = true;
              continue;
            }
            break;
          }
          if (bufferedInputHandled) return;
          if (config?.getDebugMode() || debugKeystrokeLogging) {
            const codes = Array.from(kittySequenceBufferRef.current).map(
              (ch) => ch.charCodeAt(0)
            );
            debugLogger2.warn("Kitty sequence buffer has char codes:", codes);
          }
          if (kittySequenceBufferRef.current.length > MAX_KITTY_SEQUENCE_LENGTH) {
            if (debugKeystrokeLogging) {
              debugLogger2.debug(
                "[DEBUG] Kitty buffer overflow, clearing:",
                kittySequenceBufferRef.current
              );
            }
            if (config) {
              const event = new KittySequenceOverflowEvent(
                kittySequenceBufferRef.current.length,
                kittySequenceBufferRef.current
              );
              logKittySequenceOverflow(config, event);
            }
            clearKittyBufferAndTimeout();
          } else {
            return;
          }
        }
      }
      if (key.name === "return" && key.sequence === `${ESC3}\r`) {
        key.meta = true;
      }
      if (process.platform === "darwin" && !isPaste && key.sequence === OPTION_T_COMPOSED_GLYPH) {
        key.name = "t";
        key.meta = true;
      }
      broadcast({ ...key, paste: isPaste });
    }, "handleKeypress");
    const clearRawFlushTimeout = /* @__PURE__ */ __name(() => {
      if (rawFlushTimeout) {
        clearTimeout(rawFlushTimeout);
        rawFlushTimeout = null;
      }
    }, "clearRawFlushTimeout");
    const createPasteKeyEvent = /* @__PURE__ */ __name((name = "", sequence = "") => ({
      name,
      ctrl: false,
      meta: false,
      shift: false,
      paste: false,
      sequence
    }), "createPasteKeyEvent");
    const shouldFlushRawDataAsPaste = /* @__PURE__ */ __name((data) => {
      const hasReturn = data.includes(13);
      const hasEmbeddedTab = data.length > 1 && data.includes(9);
      const isSingleReturn = data.length <= 2 && hasReturn;
      return !isSingleReturn && (hasReturn || hasEmbeddedTab);
    }, "shouldFlushRawDataAsPaste");
    const flushRawBuffer = /* @__PURE__ */ __name(() => {
      if (!rawDataBuffer.length) {
        return;
      }
      const pasteModePrefixBuffer = Buffer.from(PASTE_MODE_PREFIX);
      const pasteModeSuffixBuffer = Buffer.from(PASTE_MODE_SUFFIX);
      const data = rawDataBuffer;
      let cursor = 0;
      while (cursor < data.length) {
        const prefixPos = data.indexOf(pasteModePrefixBuffer, cursor);
        const suffixPos = data.indexOf(pasteModeSuffixBuffer, cursor);
        const hasPrefix = prefixPos !== -1 && prefixPos + pasteModePrefixBuffer.length <= data.length;
        const hasSuffix = suffixPos !== -1 && suffixPos + pasteModeSuffixBuffer.length <= data.length;
        let markerPos = -1;
        let markerLength = 0;
        let markerType = null;
        if (hasPrefix && (!hasSuffix || prefixPos < suffixPos)) {
          markerPos = prefixPos;
          markerLength = pasteModePrefixBuffer.length;
          markerType = "prefix";
        } else if (hasSuffix) {
          markerPos = suffixPos;
          markerLength = pasteModeSuffixBuffer.length;
          markerType = "suffix";
        }
        if (markerPos === -1) {
          break;
        }
        const nextData = data.slice(cursor, markerPos);
        if (nextData.length > 0) {
          keypressStream.write(nextData);
        }
        if (markerType === "prefix") {
          handleKeypress(void 0, createPasteKeyEvent("paste-start"));
        } else if (markerType === "suffix") {
          handleKeypress(void 0, createPasteKeyEvent("paste-end"));
        }
        cursor = markerPos + markerLength;
      }
      rawDataBuffer = data.slice(cursor);
      if (rawDataBuffer.length === 0) {
        return;
      }
      if (isPaste || !shouldFlushRawDataAsPaste(rawDataBuffer)) {
        keypressStream.write(rawDataBuffer);
      } else {
        handleKeypress(void 0, createPasteKeyEvent("paste-start"));
        keypressStream.write(rawDataBuffer);
        handleKeypress(void 0, createPasteKeyEvent("paste-end"));
      }
      rawDataBuffer = Buffer.alloc(0);
      clearRawFlushTimeout();
    }, "flushRawBuffer");
    const handleRawKeypress = /* @__PURE__ */ __name((_data) => {
      const data = Buffer.isBuffer(_data) ? _data : Buffer.from(_data, "utf8");
      rawDataBuffer = Buffer.concat([rawDataBuffer, data]);
      clearRawFlushTimeout();
      const isReturnChar = rawDataBuffer.length <= 2 && rawDataBuffer.includes(13);
      if (isReturnChar) {
        rawFlushTimeout = setTimeout(flushRawBuffer, 100);
      } else {
        flushRawBuffer();
      }
    }, "handleRawKeypress");
    let rl;
    if (usePassthrough) {
      rl = readline.createInterface({
        input: keypressStream,
        escapeCodeTimeout: 0
      });
      readline.emitKeypressEvents(keypressStream, rl);
      keypressStream.on("keypress", handleKeypress);
      stdin.on("data", handleRawKeypress);
    } else {
      rl = readline.createInterface({ input: stdin, escapeCodeTimeout: 0 });
      readline.emitKeypressEvents(stdin, rl);
      stdin.on("keypress", handleKeypress);
    }
    let replayPending = false;
    if (capturedInput.length > 0) {
      debugLogger2.debug(
        `Replaying ${capturedInput.length} bytes of captured input`
      );
      replayPending = true;
      setImmediate(() => {
        if (!replayPending) return;
        try {
          stdin.emit("data", capturedInput);
        } catch (err) {
          debugLogger2.error("Failed to replay captured input:", err);
        }
      });
    }
    return () => {
      replayPending = false;
      if (usePassthrough) {
        keypressStream.removeListener("keypress", handleKeypress);
        stdin.removeListener("data", handleRawKeypress);
      } else {
        stdin.removeListener("keypress", handleKeypress);
      }
      rl.close();
      setRawMode(false);
      if (backslashTimeout) {
        clearTimeout(backslashTimeout);
        backslashTimeout = null;
      }
      clearKittyBufferAndTimeout();
      clearPasteIdleTimeout();
      resetSgrMouse();
      if (rawFlushTimeout) {
        clearTimeout(rawFlushTimeout);
        rawFlushTimeout = null;
      }
      if (isPaste) {
        broadcast({
          name: "",
          ctrl: false,
          meta: false,
          shift: false,
          paste: true,
          sequence: pasteBuffer.toString()
        });
        pasteBuffer = Buffer.alloc(0);
      }
    };
  }, [
    stdin,
    setRawMode,
    kittyProtocolEnabled,
    debugKeystrokeLogging,
    pasteWorkaround,
    config,
    subscribers,
    mouseSubscribers,
    initialCapturedInput
  ]);
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
    KeypressContext.Provider,
    {
      value: {
        subscribe,
        unsubscribe,
        subscribeMouse,
        unsubscribeMouse,
        pasteWorkaround
      },
      children
    }
  );
}
__name(KeypressProvider, "KeypressProvider");

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

// packages/cli/src/services/commandUtils.ts
init_esbuild_shims();
function getEffectiveSupportedModes(cmd) {
  if (cmd.supportedModes !== void 0) {
    return cmd.supportedModes;
  }
  switch (cmd.kind) {
    case "built-in" /* BUILT_IN */:
      return ["interactive"];
    case "file" /* FILE */:
    case "skill" /* SKILL */:
    case "mcp-prompt" /* MCP_PROMPT */:
      return ["interactive", "non_interactive", "acp"];
    default:
      return ["interactive"];
  }
}
__name(getEffectiveSupportedModes, "getEffectiveSupportedModes");
function filterCommandsForMode(commands, mode) {
  return commands.filter(
    (cmd) => getEffectiveSupportedModes(cmd).includes(mode)
  );
}
__name(filterCommandsForMode, "filterCommandsForMode");

// packages/cli/src/ui/utils/resumeHistoryUtils.ts
init_esbuild_shims();
import * as path2 from "node:path";
function extractTextFromParts(parts) {
  if (!parts) return "";
  const textParts = [];
  for (const part of parts) {
    if ("text" in part && part.text) {
      if (!("thought" in part && part.thought)) {
        textParts.push(part.text);
      }
    }
  }
  return textParts.join("\n");
}
__name(extractTextFromParts, "extractTextFromParts");
function extractThoughtTextFromParts(parts) {
  if (!parts) return "";
  const thoughtParts = [];
  for (const part of parts) {
    if ("text" in part && part.text && "thought" in part && part.thought) {
      thoughtParts.push(part.text);
    }
  }
  return thoughtParts.join("\n");
}
__name(extractThoughtTextFromParts, "extractThoughtTextFromParts");
function extractFunctionCalls(parts) {
  if (!parts) return [];
  const calls = [];
  for (const part of parts) {
    if ("functionCall" in part && part.functionCall) {
      const fc = part.functionCall;
      calls.push({
        id: fc.id || `call-${calls.length}`,
        name: fc.name || "unknown",
        args: fc.args || {}
      });
    }
  }
  return calls;
}
__name(extractFunctionCalls, "extractFunctionCalls");
function getTool(config, name) {
  if (!config) return void 0;
  const toolRegistry = config.getToolRegistry();
  return toolRegistry.getTool(name);
}
__name(getTool, "getTool");
function formatToolDescription(tool, args) {
  try {
    const invocation = tool.build(args);
    return invocation.getDescription();
  } catch {
    if (typeof args["description"] === "string") {
      return args["description"];
    }
    return "";
  }
}
__name(formatToolDescription, "formatToolDescription");
function restoreHistoryItem(raw) {
  if (!raw || typeof raw !== "object") {
    return;
  }
  const clone = { ...raw };
  if ("timestamp" in clone) {
    const ts = clone["timestamp"];
    if (typeof ts === "string" || typeof ts === "number") {
      clone["timestamp"] = new Date(ts);
    }
  }
  if (typeof clone["type"] !== "string") {
    return;
  }
  return clone;
}
__name(restoreHistoryItem, "restoreHistoryItem");
function convertToHistoryItems(conversation, config) {
  const items = [];
  const pendingAtCommands = [];
  let atCommandCounter = 0;
  const pendingToolCalls = /* @__PURE__ */ new Map();
  let currentToolGroup = [];
  const buildAtCommandDisplays = /* @__PURE__ */ __name((payload) => {
    if (payload.status === "error") {
      atCommandCounter += 1;
      const filesLabel = payload.filesRead?.length ? payload.filesRead.join(", ") : "files";
      return [
        {
          callId: `at-command-${atCommandCounter}`,
          name: "Read File(s)",
          description: "Error attempting to read files",
          status: "Error" /* Error */,
          resultDisplay: payload.message || `Error reading files (${filesLabel})`,
          confirmationDetails: void 0
        }
      ];
    }
    if (!payload.filesRead?.length) {
      atCommandCounter += 1;
      return [
        {
          callId: `at-command-${atCommandCounter}`,
          name: "Read File",
          description: "Read File(s)",
          status: "Success" /* Success */,
          resultDisplay: void 0,
          confirmationDetails: void 0
        }
      ];
    }
    return payload.filesRead.map((filePath) => {
      atCommandCounter += 1;
      const isDir = filePath.endsWith("/");
      return {
        callId: `at-command-${atCommandCounter}`,
        name: isDir ? "Read Directory" : "Read File",
        description: isDir ? `Read directory ${path2.basename(filePath)}` : `Read file ${path2.basename(filePath)}`,
        status: "Success" /* Success */,
        resultDisplay: void 0,
        confirmationDetails: void 0
      };
    });
  }, "buildAtCommandDisplays");
  for (const record of conversation.messages) {
    if (record.type === "system") {
      if (record.subtype === "slash_command") {
        if (currentToolGroup.length > 0) {
          items.push({
            type: "tool_group",
            tools: [...currentToolGroup]
          });
          currentToolGroup = [];
        }
        const payload = record.systemPayload;
        if (!payload) continue;
        if (payload.phase === "invocation" && payload.rawCommand) {
          const sentToModel = typeof payload.sentToModel === "boolean" ? payload.sentToModel : void 0;
          items.push({
            type: "user",
            text: payload.rawCommand,
            ...sentToModel === void 0 ? {} : { sentToModel }
          });
        }
        if (payload.phase === "result") {
          const outputs = payload.outputHistoryItems ?? [];
          for (const raw of outputs) {
            const restored = restoreHistoryItem(raw);
            if (restored) {
              items.push(restored);
            }
          }
        }
      }
      if (record.subtype === "at_command") {
        const payload = record.systemPayload;
        if (!payload) continue;
        pendingAtCommands.push(payload);
      }
      if (record.subtype === "rewind") {
        items.push({ type: "info", text: "Conversation rewound." });
      }
      continue;
    }
    switch (record.type) {
      case "user": {
        if (record.subtype === "notification" || record.subtype === "cron") {
          const payload = record.systemPayload;
          const fallback = record.subtype === "cron" ? "Cron job fired" : "Background agent completed";
          const text2 = payload?.displayText || extractTextFromParts(record.message?.parts) || fallback;
          items.push({ type: "notification", text: text2 });
          break;
        }
        if (record.subtype === "mid_turn_user_message") {
          const payload = record.systemPayload;
          const text2 = payload?.displayText || extractTextFromParts(record.message?.parts);
          if (text2) {
            items.push({ type: "notification", text: text2 });
          }
          break;
        }
        if (pendingAtCommands.length > 0) {
          if (currentToolGroup.length > 0) {
            items.push({
              type: "tool_group",
              tools: [...currentToolGroup]
            });
            currentToolGroup = [];
          }
          const payload = pendingAtCommands.shift();
          const text2 = payload.userText || extractTextFromParts(record.message?.parts);
          if (text2) {
            items.push({ type: "user", text: text2 });
          }
          const toolDisplays = buildAtCommandDisplays(payload);
          if (toolDisplays.length > 0) {
            items.push({
              type: "tool_group",
              tools: toolDisplays
            });
          }
          break;
        }
        if (currentToolGroup.length > 0) {
          items.push({
            type: "tool_group",
            tools: [...currentToolGroup]
          });
          currentToolGroup = [];
        }
        const text = extractTextFromParts(record.message?.parts);
        if (text) {
          items.push({ type: "user", text });
        }
        break;
      }
      case "assistant": {
        const parts = record.message?.parts;
        const thoughtText = !config ? extractThoughtTextFromParts(parts) : "";
        const text = extractTextFromParts(parts);
        const functionCalls = extractFunctionCalls(parts);
        if (thoughtText) {
          if (currentToolGroup.length > 0) {
            items.push({
              type: "tool_group",
              tools: [...currentToolGroup]
            });
            currentToolGroup = [];
          }
          items.push({ type: "gemini_thought", text: thoughtText });
        }
        if (text) {
          if (currentToolGroup.length > 0) {
            items.push({
              type: "tool_group",
              tools: [...currentToolGroup]
            });
            currentToolGroup = [];
          }
          items.push({
            type: "gemini",
            text,
            timestamp: new Date(record.timestamp).getTime()
          });
        }
        for (const fc of functionCalls) {
          const tool = getTool(config, fc.name);
          pendingToolCalls.set(fc.id, { name: fc.name, args: fc.args });
          currentToolGroup.push({
            callId: fc.id,
            name: tool?.displayName || fc.name,
            description: tool ? formatToolDescription(tool, fc.args) : "",
            resultDisplay: void 0,
            status: "Success" /* Success */,
            // Will be updated by tool_result
            confirmationDetails: void 0
          });
        }
        break;
      }
      case "tool_result": {
        if (record.toolCallResult) {
          const callId = record.toolCallResult.callId;
          const toolCall = currentToolGroup.find((t2) => t2.callId === callId);
          if (toolCall) {
            const rawDisplay = record.toolCallResult.resultDisplay;
            toolCall.resultDisplay = rawDisplay;
            const rawStatus = record.toolCallResult["status"];
            toolCall.status = rawStatus === "error" ? "Error" /* Error */ : "Success" /* Success */;
          }
          pendingToolCalls.delete(callId || "");
        }
        break;
      }
      default:
        break;
    }
  }
  if (pendingAtCommands.length > 0) {
    for (const payload of pendingAtCommands) {
      if (currentToolGroup.length > 0) {
        items.push({
          type: "tool_group",
          tools: [...currentToolGroup]
        });
        currentToolGroup = [];
      }
      const text = payload.userText;
      if (text) {
        items.push({ type: "user", text });
      }
      const toolDisplays = buildAtCommandDisplays(payload);
      if (toolDisplays.length > 0) {
        items.push({
          type: "tool_group",
          tools: toolDisplays
        });
      }
    }
  }
  if (currentToolGroup.length > 0) {
    items.push({
      type: "tool_group",
      tools: currentToolGroup
    });
  }
  return items;
}
__name(convertToHistoryItems, "convertToHistoryItems");
function buildResumedHistoryItems(sessionData, config, baseTimestamp = Date.now()) {
  const items = [];
  let idCounter = 1;
  const getNextId = /* @__PURE__ */ __name(() => baseTimestamp + idCounter++, "getNextId");
  const historyItems = convertToHistoryItems(sessionData.conversation, config);
  for (const item of historyItems) {
    items.push({
      ...item,
      id: getNextId()
    });
  }
  return items;
}
__name(buildResumedHistoryItems, "buildResumedHistoryItems");
function applyResumeDisplayPolicy(items) {
  return items.map((item) => ({
    ...item,
    display: { ...item.display, suppressOnRestore: true }
  }));
}
__name(applyResumeDisplayPolicy, "applyResumeDisplayPolicy");
function createHistoryCollapseSummaryItem(messageCount) {
  const n = String(messageCount);
  return {
    type: "info" /* INFO */,
    text: t(
      "History collapsed: {{n}} messages hidden. Use /history expand-now to show.",
      { n }
    ),
    display: { kind: "collapse-summary" }
  };
}
__name(createHistoryCollapseSummaryItem, "createHistoryCollapseSummaryItem");
function stripSuppressOnRestore(item) {
  if (!item.display?.suppressOnRestore) return item;
  const { suppressOnRestore: _, ...rest } = item.display;
  return {
    ...item,
    display: Object.keys(rest).length > 0 ? rest : void 0
  };
}
__name(stripSuppressOnRestore, "stripSuppressOnRestore");
function expandCollapsedHistory(items) {
  return items.filter((item) => item.display?.kind !== "collapse-summary").map(stripSuppressOnRestore);
}
__name(expandCollapsedHistory, "expandCollapsedHistory");
function applyCollapsePolicyAndSummary(rawItems, collapseOnResume, collapsePreviewCount = 0) {
  if (!collapseOnResume) return rawItems;
  if (collapsePreviewCount === -1) return rawItems;
  let boundary = rawItems.length;
  if (collapsePreviewCount > 0) {
    let userTurnCount = 0;
    for (let i = rawItems.length - 1; i >= 0; i--) {
      if (rawItems[i].type === "user" /* USER */) {
        userTurnCount++;
        if (userTurnCount === collapsePreviewCount) {
          boundary = i;
          break;
        }
      }
    }
    if (userTurnCount < collapsePreviewCount) {
      boundary = 0;
    }
  }
  const hiddenItems = applyResumeDisplayPolicy(rawItems.slice(0, boundary));
  const visibleItems = rawItems.slice(boundary);
  const uiHistoryItems = [...hiddenItems, ...visibleItems];
  if (boundary > 0) {
    const nextId = rawItems[rawItems.length - 1].id + 1;
    return [
      ...uiHistoryItems,
      { id: nextId, ...createHistoryCollapseSummaryItem(boundary) }
    ];
  }
  return uiHistoryItems;
}
__name(applyCollapsePolicyAndSummary, "applyCollapsePolicyAndSummary");

// packages/cli/src/ui/commands/diffCommand.ts
init_esbuild_shims();
async function diffAction(context) {
  const { config } = context.services;
  if (!config) {
    return {
      type: "message",
      messageType: "error",
      content: t("Configuration not available.")
    };
  }
  if (context.executionMode === "interactive") {
    return { type: "dialog", dialog: "diff" };
  }
  const cwd = config.getWorkingDir() || config.getProjectRoot();
  if (!cwd) {
    return {
      type: "message",
      messageType: "error",
      content: t("Could not determine current working directory.")
    };
  }
  let result;
  try {
    result = await fetchGitDiff(cwd);
  } catch (error) {
    return {
      type: "message",
      messageType: "error",
      content: `${t("Failed to compute git diff stats")}: ${error instanceof Error ? error.message : String(error)}`
    };
  }
  if (!result) {
    return {
      type: "message",
      messageType: "info",
      content: t(
        "No diff available. Either this is not a git repository, HEAD is missing, or a merge/rebase/cherry-pick/revert is in progress."
      )
    };
  }
  if (result.stats.filesCount === 0) {
    return {
      type: "message",
      messageType: "info",
      content: t("Clean working tree \u2014 no changes against HEAD.")
    };
  }
  const model = buildDiffRenderModel(result);
  return {
    type: "message",
    messageType: "info",
    content: renderDiffModelText(model)
  };
}
__name(diffAction, "diffAction");
function buildDiffRenderModel(result) {
  const rows = [];
  for (const [filename, s] of result.perFileStats) {
    rows.push(toRow(filename, s));
  }
  const hiddenCount = Math.max(0, result.stats.filesCount - rows.length);
  return {
    filesCount: result.stats.filesCount,
    linesAdded: result.stats.linesAdded,
    linesRemoved: result.stats.linesRemoved,
    rows,
    hiddenCount
  };
}
__name(buildDiffRenderModel, "buildDiffRenderModel");
function toRow(filename, s) {
  if (s.isBinary) {
    return {
      filename,
      isBinary: true,
      isUntracked: Boolean(s.isUntracked),
      isDeleted: Boolean(s.isDeleted),
      truncated: false
    };
  }
  return {
    filename,
    added: s.added,
    removed: s.isUntracked ? 0 : s.removed,
    isBinary: false,
    isUntracked: Boolean(s.isUntracked),
    isDeleted: Boolean(s.isDeleted),
    truncated: Boolean(s.truncated)
  };
}
__name(toRow, "toRow");
function computeDiffColumnWidths(rows) {
  let maxAdded = 0;
  let maxRemoved = 0;
  for (const r of rows) {
    if (r.isBinary) continue;
    if ((r.added ?? 0) > maxAdded) maxAdded = r.added ?? 0;
    if ((r.removed ?? 0) > maxRemoved) maxRemoved = r.removed ?? 0;
  }
  const addWidth = String(maxAdded).length;
  const remWidth = String(maxRemoved).length;
  const statColumnWidth = 1 + addWidth + 1 + 1 + remWidth;
  return { addWidth, remWidth, statColumnWidth };
}
__name(computeDiffColumnWidths, "computeDiffColumnWidths");
function renderDiffModelText(model) {
  const { filesCount, linesAdded, linesRemoved, rows, hiddenCount } = model;
  const header = filesCount === 1 ? t("{{count}} file changed, +{{added}} / -{{removed}}", {
    count: String(filesCount),
    added: String(linesAdded),
    removed: String(linesRemoved)
  }) : t("{{count}} files changed, +{{added}} / -{{removed}}", {
    count: String(filesCount),
    added: String(linesAdded),
    removed: String(linesRemoved)
  });
  const lines = formatRowsText(rows);
  const capNote = hiddenCount > 0 && rows.length > 0 ? `
  ${t("\u2026and {{hidden}} more (showing first {{shown}})", {
    hidden: String(hiddenCount),
    shown: String(rows.length)
  })}` : "";
  return lines.length > 0 ? `${header}
${lines.join("\n")}${capNote}` : header;
}
__name(renderDiffModelText, "renderDiffModelText");
function formatRowsText(rows) {
  if (rows.length === 0) return [];
  const { addWidth, remWidth, statColumnWidth } = computeDiffColumnWidths(rows);
  const out = [];
  for (const r of rows) {
    const safeName = sanitizeFilenameForDisplay(r.filename);
    if (r.isBinary) {
      const suffix2 = r.isUntracked ? ` ${t("(binary, new)")}` : r.isDeleted ? ` ${t("(binary, deleted)")}` : ` ${t("(binary)")}`;
      out.push(`  ${padMarker("~", statColumnWidth)}  ${safeName}${suffix2}`);
      continue;
    }
    const added = `+${String(r.added ?? 0).padStart(addWidth)}`;
    const removed = `-${String(r.removed ?? 0).padStart(remWidth)}`;
    let suffix = "";
    if (r.isUntracked) {
      suffix = r.truncated ? ` ${t("(new, partial)")}` : ` ${t("(new)")}`;
    } else if (r.isDeleted) {
      suffix = ` ${t("(deleted)")}`;
    }
    out.push(`  ${added} ${removed}  ${safeName}${suffix}`);
  }
  return out;
}
__name(formatRowsText, "formatRowsText");
function padMarker(marker, width) {
  if (marker.length >= width) return marker;
  return `${marker}${" ".repeat(width - marker.length)}`;
}
__name(padMarker, "padMarker");
var diffCommand = {
  name: "diff",
  get description() {
    return t("Show working-tree change stats versus HEAD");
  },
  kind: "built-in" /* BUILT_IN */,
  supportedModes: ["interactive", "non_interactive", "acp"],
  action: diffAction
};

// packages/cli/src/utils/systemInfoFields.ts
init_esbuild_shims();
function getSystemInfoFields(info) {
  const fields = [];
  addField(fields, t("Qwen Code"), formatCliVersion(info));
  addField(fields, t("Runtime"), formatRuntime(info));
  addField(fields, t("IDE Client"), info.ideClient);
  addField(fields, "LSP", info.lspStatus ?? "");
  addField(fields, t("OS"), formatOs(info));
  addField(fields, t("Auth"), formatAuth(info));
  addField(fields, t("Base URL"), formatBaseUrl(info));
  addField(fields, t("Model"), info.modelVersion);
  addField(fields, t("Fast Model"), info.fastModel || info.modelVersion);
  addField(fields, t("Session ID"), info.sessionId);
  addField(fields, t("Sandbox"), info.sandboxEnv);
  addField(fields, t("Proxy"), formatProxy(info.proxy));
  addField(fields, t("Memory Usage"), info.memoryUsage);
  return fields;
}
__name(getSystemInfoFields, "getSystemInfoFields");
function addField(fields, label, value) {
  if (value) {
    fields.push({ label, value });
  }
}
__name(addField, "addField");
function formatCliVersion(info) {
  if (!info.cliVersion) {
    return "";
  }
  if (!info.gitCommit) {
    return info.cliVersion;
  }
  return `${info.cliVersion} (${info.gitCommit})`;
}
__name(formatCliVersion, "formatCliVersion");
function formatRuntime(info) {
  if (!info.nodeVersion && !info.npmVersion) {
    return "";
  }
  const node = info.nodeVersion ? `Node.js ${info.nodeVersion}` : "";
  const npm = info.npmVersion ? `npm ${info.npmVersion}` : "";
  return joinParts([node, npm], " / ");
}
__name(formatRuntime, "formatRuntime");
function formatOs(info) {
  return joinParts(
    [info.osPlatform, info.osArch, formatOsRelease(info.osRelease)],
    " "
  ).trim();
}
__name(formatOs, "formatOs");
function formatOsRelease(release) {
  if (!release) {
    return "";
  }
  return `(${release})`;
}
__name(formatOsRelease, "formatOsRelease");
function formatAuth(info) {
  if (!info.selectedAuthType) {
    return "";
  }
  const managedProvider = findProviderByCredentials(
    info.baseUrl,
    info.apiKeyEnvKey
  );
  if (managedProvider && resolveMetadataKey(managedProvider)) {
    return t(managedProvider.label);
  }
  if (info.selectedAuthType.startsWith("oauth") || info.selectedAuthType === "qwen-oauth") {
    return "Qwen OAuth";
  }
  return `API Key - ${info.selectedAuthType}`;
}
__name(formatAuth, "formatAuth");
function formatBaseUrl(info) {
  if (!info.selectedAuthType || !info.baseUrl) {
    return "";
  }
  if (info.selectedAuthType.startsWith("oauth") || info.selectedAuthType === "qwen-oauth") {
    return "";
  }
  return info.baseUrl;
}
__name(formatBaseUrl, "formatBaseUrl");
function formatProxy(proxy) {
  if (!proxy) {
    return "no proxy";
  }
  return redactProxy(proxy);
}
__name(formatProxy, "formatProxy");
function redactProxy(proxy) {
  try {
    const url = new URL(proxy);
    if (url.username || url.password) {
      url.username = url.username ? "***" : "";
      url.password = url.password ? "***" : "";
    }
    return url.toString();
  } catch {
    return proxy.replace(/\/\/[^/]*@/, "//***@");
  }
}
__name(redactProxy, "redactProxy");
function joinParts(parts, separator) {
  return parts.filter((part) => part).join(separator);
}
__name(joinParts, "joinParts");

// packages/cli/src/utils/costCalculator.ts
init_esbuild_shims();
function calculateCost(args) {
  const { inputTokens, outputTokens, pricing } = args;
  if (!pricing) return null;
  const inputCost = pricing.inputPerMillionTokens != null ? inputTokens / 1e6 * pricing.inputPerMillionTokens : 0;
  const outputCost = pricing.outputPerMillionTokens != null ? outputTokens / 1e6 * pricing.outputPerMillionTokens : 0;
  const total = inputCost + outputCost;
  return total > 0 ? total : null;
}
__name(calculateCost, "calculateCost");

// packages/cli/src/ui/utils/skill-level-label.ts
init_esbuild_shims();
function levelLabel(level) {
  switch (level) {
    case "project":
      return t("Project");
    case "user":
      return t("User");
    case "extension":
      return t("Extension");
    case "bundled":
      return t("Bundled");
    default: {
      const _exhaustive = level;
      return _exhaustive;
    }
  }
}
__name(levelLabel, "levelLabel");

export {
  enableMouseEvents,
  disableMouseEvents,
  VSCODE_SHIFT_ENTER_SEQUENCE,
  BEL,
  OSC_PREFIX,
  detectTerminal,
  wrapForMultiplexer,
  oscITerm2Notify,
  oscKittyNotify,
  oscGhosttyNotify,
  generateKittyId,
  writeOsc52,
  clipboardHasImage,
  saveClipboardImage,
  cleanupOldClipboardImages,
  useKeypress,
  useFocus,
  useKeypressContext,
  KeypressProvider,
  getSystemInfoFields,
  calculateErrorRate,
  calculateAverageLatency,
  calculateCacheHitRate,
  computeSessionStats,
  calculateCost,
  getEffectiveSupportedModes,
  filterCommandsForMode,
  levelLabel,
  computeDiffColumnWidths,
  diffCommand,
  buildResumedHistoryItems,
  expandCollapsedHistory,
  applyCollapsePolicyAndSummary
};
/**
 * @license
 * Copyright 2025 Qwen
 * SPDX-License-Identifier: Apache-2.0
 *
 * Adapted from gemini-cli (Google LLC, Apache-2.0):
 * packages/cli/src/ui/utils/mouse.ts + utils/input.ts. Trimmed to the
 * subset the virtual-viewport scroll path needs (SGR + X11 parsing,
 * incomplete-sequence detection, enable/disable helpers).
 */
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * @license
 * Copyright 2026 Qwen Team
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * @license
 * Copyright 2025 Qwen Code
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * @license
 * Copyright 2025 Qwen
 * SPDX-License-Identifier: Apache-2.0
 */
