'use strict';

var process$1 = require('process');
var readline = require('readline');
require('os');
require('posthog-node');
require('fs');
require('path');
require('child_process');
require('util');

function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

var readline__default = /*#__PURE__*/_interopDefault(readline);

// src/platform/ui/status.ts
var ANSI = {
  blue: "\x1B[34m",
  bold: "\x1B[1m",
  cyan: "\x1B[36m",
  dim: "\x1B[2m",
  gray: "\x1B[90m",
  green: "\x1B[32m",
  red: "\x1B[31m",
  reset: "\x1B[0m",
  yellow: "\x1B[33m"
};
var ANSI_PATTERN = new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`, "g");
var COMBINING_MARK_PATTERN = /\p{Mark}/u;
var GRAPHEME_SEGMENTER = typeof Intl !== "undefined" && "Segmenter" in Intl ? new Intl.Segmenter("ko", { granularity: "grapheme" }) : null;
function colorize(text, color) {
  return `${color}${text}${ANSI.reset}`;
}
function segmentGraphemes(value) {
  if (!GRAPHEME_SEGMENTER) {
    return [...value];
  }
  return [...GRAPHEME_SEGMENTER.segment(value)].map(({ segment }) => segment);
}
function getGraphemeWidth(grapheme) {
  let width = 0;
  for (const character of grapheme) {
    const codePoint = character.codePointAt(0);
    if (!codePoint || COMBINING_MARK_PATTERN.test(character) || codePoint === 8205) {
      continue;
    }
    if (codePoint >= 65024 && codePoint <= 65039 || codePoint >= 917760 && codePoint <= 917999) {
      continue;
    }
    if (isWideCodePoint(codePoint) || isEmojiCodePoint(codePoint)) {
      width = Math.max(width, 2);
      continue;
    }
    width = Math.max(width, 1);
  }
  return width;
}
function tokenizePlainText(value) {
  return segmentGraphemes(value).map((segment) => ({
    value: segment,
    visibleWidth: getGraphemeWidth(segment)
  }));
}
function tokenizeVisibleText(value) {
  const tokens = [];
  let lastIndex = 0;
  for (const match of value.matchAll(ANSI_PATTERN)) {
    const index = match.index ?? 0;
    if (index > lastIndex) {
      tokens.push(...tokenizePlainText(value.slice(lastIndex, index)));
    }
    tokens.push({
      value: match[0],
      visibleWidth: 0
    });
    lastIndex = index + match[0].length;
  }
  if (lastIndex < value.length) {
    tokens.push(...tokenizePlainText(value.slice(lastIndex)));
  }
  return tokens;
}
function isWideCodePoint(codePoint) {
  return codePoint >= 4352 && (codePoint <= 4447 || codePoint === 9001 || codePoint === 9002 || codePoint >= 11904 && codePoint <= 12871 && codePoint !== 12351 || codePoint >= 12880 && codePoint <= 19903 || codePoint >= 19968 && codePoint <= 42182 || codePoint >= 43360 && codePoint <= 43388 || codePoint >= 44032 && codePoint <= 55203 || codePoint >= 63744 && codePoint <= 64255 || codePoint >= 65040 && codePoint <= 65049 || codePoint >= 65072 && codePoint <= 65131 || codePoint >= 65281 && codePoint <= 65376 || codePoint >= 65504 && codePoint <= 65510 || codePoint >= 127488 && codePoint <= 127569 || codePoint >= 131072 && codePoint <= 262141);
}
function isEmojiCodePoint(codePoint) {
  return codePoint >= 127462 && codePoint <= 127487 || codePoint >= 127744 && codePoint <= 129791 || codePoint >= 9728 && codePoint <= 10175;
}
function visibleLength(value) {
  return tokenizeVisibleText(value).reduce((total, token) => total + token.visibleWidth, 0);
}
function sliceVisible(value, width) {
  if (width <= 0) {
    return "";
  }
  let currentWidth = 0;
  let output = "";
  let truncated = false;
  let containsAnsi = false;
  for (const token of tokenizeVisibleText(value)) {
    if (token.visibleWidth === 0) {
      output += token.value;
      containsAnsi = true;
      continue;
    }
    if (currentWidth + token.visibleWidth > width) {
      truncated = true;
      break;
    }
    output += token.value;
    currentWidth += token.visibleWidth;
  }
  if (truncated && containsAnsi && !output.endsWith(ANSI.reset)) {
    output += ANSI.reset;
  }
  return output;
}
function padVisible(value, width) {
  const slicedValue = sliceVisible(value, width);
  const length = visibleLength(slicedValue);
  if (length >= width) {
    return slicedValue;
  }
  return `${slicedValue}${" ".repeat(width - length)}`;
}
function truncateValue(value, width) {
  if (visibleLength(value) <= width) {
    return value;
  }
  if (width <= 3) {
    return sliceVisible(value, width);
  }
  return `${sliceVisible(value, width - 3)}...`;
}
function getViewportWidth() {
  const columns = process$1.stdout.columns || 100;
  return Math.max(Math.min(columns - 2, 108), 4);
}
function getTerminalColumns() {
  return Math.max(process$1.stdout.columns || 100, 4);
}
function renderBadge(text, tone) {
  const theme = tone === "service" ? ANSI.cyan : tone === "accent" ? ANSI.green : tone === "warn" ? ANSI.yellow : ANSI.gray;
  return colorize(`[${text}]`, theme);
}
function createBox(title, lines, footerLines = []) {
  const contentLines = lines.length > 0 ? lines : [""];
  const footer = footerLines.length > 0 ? ["", ...footerLines] : [];
  const width = getViewportWidth();
  const top = `+${"-".repeat(width - 2)}+`;
  const titleLine = `| ${padVisible(colorize(title, ANSI.bold), width - 4)} |`;
  const body = [...contentLines, ...footer].map((line) => `| ${padVisible(line, width - 4)} |`);
  return [top, titleLine, top, ...body, top];
}
function renderScreenBox(title, lines, footerLines = []) {
  console.clear();
  console.log(createBox(title, lines, footerLines).join("\n"));
}
function wrapPlainText(value, firstLineWidth, continuationLineWidth) {
  const renderedLines = [];
  const safeFirstLineWidth = Math.max(firstLineWidth, 1);
  const safeContinuationLineWidth = Math.max(continuationLineWidth, 1);
  const normalizedValue = value.replace(/\r\n?/g, "\n");
  const pushWrappedLine = (line) => {
    if (line.length === 0) {
      renderedLines.push("");
      return;
    }
    let currentLine = "";
    let currentWidth = 0;
    let currentLineWidth = renderedLines.length === 0 ? safeFirstLineWidth : safeContinuationLineWidth;
    for (const segment of segmentGraphemes(line)) {
      const segmentWidth = Math.max(getGraphemeWidth(segment), 1);
      if (currentLine && currentWidth + segmentWidth > currentLineWidth) {
        renderedLines.push(currentLine);
        currentLine = "";
        currentWidth = 0;
        currentLineWidth = safeContinuationLineWidth;
      }
      currentLine += segment;
      currentWidth += segmentWidth;
    }
    renderedLines.push(currentLine);
  };
  normalizedValue.split("\n").forEach(pushWrappedLine);
  return renderedLines.length > 0 ? renderedLines : [""];
}
function buildPromptRenderLayout(promptLabel, buffer, placeholder) {
  const columns = getTerminalColumns();
  const promptLabelWidth = visibleLength(promptLabel);
  const continuationIndentWidth = Math.min(promptLabelWidth, Math.max(columns - 1, 0));
  const continuationIndent = " ".repeat(continuationIndentWidth);
  const firstLineWidth = Math.max(columns - promptLabelWidth, 1);
  const continuationLineWidth = Math.max(columns - continuationIndentWidth, 1);
  const hasBuffer = buffer.length > 0;
  const contentLines = hasBuffer ? wrapPlainText(buffer, firstLineWidth, continuationLineWidth) : wrapPlainText(placeholder || "", firstLineWidth, continuationLineWidth);
  const cursorLines = hasBuffer ? contentLines : [""];
  const renderedPromptLines = contentLines.map((line, index) => {
    const linePrefix = index === 0 ? promptLabel : continuationIndent;
    return `${linePrefix}${hasBuffer ? line : colorize(line, ANSI.dim)}`;
  });
  const activeCursorLine = cursorLines.at(-1) || "";
  const activeCursorLinePrefixWidth = cursorLines.length <= 1 ? promptLabelWidth : continuationIndentWidth;
  return {
    cursorColumn: activeCursorLinePrefixWidth + visibleLength(activeCursorLine),
    cursorRowOffset: Math.max(cursorLines.length - 1, 0),
    lines: renderedPromptLines,
    totalLines: renderedPromptLines.length
  };
}
function clearRenderedPrompt(previousState) {
  if (previousState?.cursorRowOffset) {
    readline__default.default.moveCursor(process$1.stdout, 0, -previousState.cursorRowOffset);
  }
  readline__default.default.cursorTo(process$1.stdout, 0);
  readline__default.default.clearScreenDown(process$1.stdout);
}
function renderPromptLayout(layout, previousState) {
  clearRenderedPrompt(previousState);
  process$1.stdout.write(layout.lines.join("\n"));
  const linesBelowCursor = layout.totalLines - 1 - layout.cursorRowOffset;
  if (linesBelowCursor > 0) {
    readline__default.default.moveCursor(process$1.stdout, 0, -linesBelowCursor);
  }
  readline__default.default.cursorTo(process$1.stdout, layout.cursorColumn);
  return {
    cursorRowOffset: layout.cursorRowOffset,
    totalLines: layout.totalLines
  };
}

// src/platform/ui/status.ts
var STATUS_FRAMES = ["-", "\\", "|", "/"];
function formatStatusPrefix(title) {
  return `${colorize(`[${title}]`, `${ANSI.bold}${ANSI.cyan}`)}`;
}
function formatElapsed(startedAt) {
  return `${Math.max(0, Math.floor((Date.now() - startedAt) / 1e3))}s`;
}
function buildStatusRenderLayout(prefix, body) {
  return buildPromptRenderLayout(`${prefix} `, body);
}
function clearRenderedStatus(previousState) {
  if (previousState?.totalLines && previousState.totalLines > 1) {
    readline__default.default.moveCursor(process$1.stdout, 0, -(previousState.totalLines - 1));
  }
  readline__default.default.cursorTo(process$1.stdout, 0);
  readline__default.default.clearScreenDown(process$1.stdout);
}
function renderStatusLayout(layout, previousState) {
  clearRenderedStatus(previousState);
  process$1.stdout.write(layout.lines.join("\n"));
  return {
    totalLines: layout.totalLines
  };
}
function createSessionActionStatus(title) {
  const prefix = formatStatusPrefix(title);
  const print = (message) => {
    console.log(`${prefix} ${message}`);
  };
  return {
    fail(message) {
      print(colorize(message, ANSI.red));
    },
    step(message) {
      print(message);
    },
    async track(message, task) {
      if (!process$1.stdout.isTTY) {
        print(`${message}...`);
        return task();
      }
      const startedAt = Date.now();
      let frameIndex = 0;
      let renderState;
      const render = () => {
        const frame = STATUS_FRAMES[frameIndex % STATUS_FRAMES.length];
        frameIndex += 1;
        renderState = renderStatusLayout(buildStatusRenderLayout(`${prefix} ${frame}`, `${message} (${formatElapsed(startedAt)})`), renderState);
      };
      render();
      const timer = setInterval(render, 120);
      try {
        const result = await task();
        clearInterval(timer);
        renderState = renderStatusLayout(
          buildStatusRenderLayout(`${prefix} done`, `${message} (${formatElapsed(startedAt)})`),
          renderState
        );
        process$1.stdout.write("\n");
        return result;
      } catch (error) {
        clearInterval(timer);
        renderState = renderStatusLayout(
          buildStatusRenderLayout(`${prefix} fail`, `${message} (${formatElapsed(startedAt)})`),
          renderState
        );
        process$1.stdout.write("\n");
        throw error;
      }
    }
  };
}

// src/platform/analytics/posthog.ts
var telemetryRuntimeState = globalThis.__JU_HONG_E_POSTHOG_RUNTIME_STATE__ ?? (globalThis.__JU_HONG_E_POSTHOG_RUNTIME_STATE__ = {});
function appendSlashCommandTelemetryInputValue(value) {
  if (!telemetryRuntimeState.slashCommandTelemetryInputValues) {
    return;
  }
  telemetryRuntimeState.slashCommandTelemetryInputValues.push(...normalizeSlashCommandTelemetryValues(value));
}
function normalizeSlashCommandTelemetryValues(value) {
  if (value === void 0) {
    return [];
  }
  if (value === null) {
    return [null];
  }
  if (Array.isArray(value)) {
    return value.flatMap((item) => normalizeSlashCommandTelemetryValues(item));
  }
  if (typeof value === "string") {
    return [value];
  }
  if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
    return [String(value)];
  }
  if (typeof value === "object") {
    const objectValue = value;
    if (typeof objectValue.url === "string" && objectValue.url) {
      return [objectValue.url];
    }
    if (typeof objectValue.hash === "string" && objectValue.hash) {
      return [objectValue.hash];
    }
    if (typeof objectValue.name === "string" && objectValue.name) {
      return [objectValue.name];
    }
    if (typeof objectValue.label === "string" && objectValue.label) {
      return [objectValue.label];
    }
    try {
      return [JSON.stringify(objectValue)];
    } catch {
      return ["[object]"];
    }
  }
  return [String(value)];
}

// src/platform/core/cancellation.ts
var USER_CANCELLED_ERROR_CODE = "JUHONG_E_USER_CANCELLED";
var USER_TERMINATED_ERROR_CODE = "JUHONG_E_USER_TERMINATED";
function createCancellationError(name, code, message) {
  const error = new Error(message);
  error.name = name;
  error.code = code;
  return error;
}
function createUserCancelledError(message = "\uC0AC\uC6A9\uC790\uAC00 \uD604\uC7AC \uC791\uC5C5\uC744 \uCDE8\uC18C\uD588\uC2B5\uB2C8\uB2E4.") {
  return createCancellationError("UserCancelledError", USER_CANCELLED_ERROR_CODE, message);
}
function createUserTerminatedError(message = "\uC0AC\uC6A9\uC790\uAC00 \uC138\uC158 \uC885\uB8CC\uB97C \uC694\uCCAD\uD588\uC2B5\uB2C8\uB2E4.") {
  return createCancellationError("UserTerminatedError", USER_TERMINATED_ERROR_CODE, message);
}

// src/platform/ui/prompt.ts
function getPromptPrefix(service, testMode = false, traceMode = false) {
  return [
    colorize("ju-hong-e", `${ANSI.bold}${ANSI.cyan}`),
    renderBadge(service, "service"),
    testMode ? renderBadge("TEST", "warn") : "",
    traceMode ? renderBadge("TRACE", "muted") : ""
  ].filter(Boolean).join(" ");
}
function isSlashCommandQuery(input) {
  const trimmed = input.trimStart();
  return trimmed.startsWith("/");
}
function getVisibleCommandOptions(commands, input) {
  if (!isSlashCommandQuery(input)) {
    return [];
  }
  const keyword = input.toLowerCase();
  return commands.filter((command) => {
    const candidates = [command.command, command.insertValue, ...command.matchKeywords || []].filter((candidate) => Boolean(candidate)).map((candidate) => candidate.toLowerCase());
    return candidates.some((candidate) => candidate.startsWith(keyword));
  });
}
function buildPaletteFooter(start, visibleCount, totalCount) {
  return [
    `${colorize("\uD45C\uC2DC \uBC94\uC704", ANSI.gray)} ${start + 1}-${Math.min(start + visibleCount, totalCount)} / ${totalCount}`,
    `${colorize("Tab", ANSI.yellow)} \uC120\uD0DD \uC801\uC6A9`,
    `${colorize("Up/Down", ANSI.yellow)} \uBA85\uB839 \uC774\uB3D9`,
    `${colorize("Shift+Up/Down", ANSI.yellow)} \uD788\uC2A4\uD1A0\uB9AC \uC774\uB3D9`,
    `${colorize("ESC", ANSI.yellow)} \uD604\uC7AC \uC785\uB825 \uC9C0\uC6B0\uAE30`,
    `${colorize("Ctrl+C", ANSI.yellow)} \uC138\uC158 \uC885\uB8CC`,
    `${colorize("Enter", ANSI.yellow)} \uD604\uC7AC \uC785\uB825 \uC2E4\uD589`
  ];
}
function buildCompactPaletteFooter(start, visibleCount, totalCount) {
  return [
    `${colorize("\uD45C\uC2DC \uBC94\uC704", ANSI.gray)} ${start + 1}-${Math.min(start + visibleCount, totalCount)} / ${totalCount}`,
    `${colorize("Tab", ANSI.yellow)} \uC120\uD0DD  ${colorize("Up/Down", ANSI.yellow)} \uC774\uB3D9  ${colorize("Enter", ANSI.yellow)} \uC2E4\uD589  ${colorize("ESC", ANSI.yellow)} \uC9C0\uC6B0\uAE30  ${colorize("Ctrl+C", ANSI.yellow)} \uC885\uB8CC`
  ];
}
var BOX_CHROME_LINES = 4;
var BOX_FOOTER_GAP = 1;
function renderCommandPalette(commands, cursor, maxLines) {
  const fullFooter = buildPaletteFooter(0, 0, commands.length);
  const compactFooter = buildCompactPaletteFooter(0, 0, commands.length);
  const fullOverhead = BOX_CHROME_LINES + BOX_FOOTER_GAP + fullFooter.length;
  const compactOverhead = BOX_CHROME_LINES + BOX_FOOTER_GAP + compactFooter.length;
  let windowSize = 8;
  let useCompactFooter = false;
  if (maxLines !== void 0) {
    const availableWithFull = maxLines - fullOverhead;
    if (availableWithFull >= 1) {
      windowSize = Math.min(windowSize, availableWithFull);
    } else {
      const availableWithCompact = maxLines - compactOverhead;
      if (availableWithCompact >= 1) {
        windowSize = Math.min(windowSize, availableWithCompact);
        useCompactFooter = true;
      } else {
        return [];
      }
    }
  }
  windowSize = Math.min(windowSize, commands.length);
  const start = Math.max(0, Math.min(cursor - Math.floor(windowSize / 2), Math.max(commands.length - windowSize, 0)));
  const visible = commands.slice(start, start + windowSize);
  const footer = useCompactFooter ? buildCompactPaletteFooter(start, visible.length, commands.length) : buildPaletteFooter(start, visible.length, commands.length);
  return createBox(
    "Slash Commands",
    visible.map((command, index) => {
      const commandIndex = start + index;
      const prefix = cursor === commandIndex ? colorize(">", ANSI.green) : " ";
      const label = cursor === commandIndex ? colorize(command.command, ANSI.green) : command.command;
      const description = colorize(command.description, ANSI.gray);
      return `${prefix} ${padVisible(label, 28)} ${description}`;
    }),
    footer
  );
}
function commitInteractiveLine(prefix, buffer) {
  readline__default.default.cursorTo(process$1.stdout, 0);
  readline__default.default.clearScreenDown(process$1.stdout);
  process$1.stdout.write(`${prefix} ${colorize(">", ANSI.blue)} ${buffer}
`);
}
function renderQuestionPrompt(question, buffer, previousState) {
  return renderPromptLayout(buildPromptRenderLayout(question, buffer), previousState);
}
function renderInteractivePrompt(prefix, buffer, commands, commandCursor, previousState) {
  const promptLabel = `${prefix} ${colorize(">", ANSI.blue)} `;
  const promptLayout = buildPromptRenderLayout(promptLabel, buffer, "\uBA54\uC2DC\uC9C0\uB97C \uC785\uB825\uD558\uC138\uC694. '/' \uB85C \uBA85\uB839 \uBA54\uB274 \uC5F4\uAE30");
  const promptLineCount = promptLayout.lines.length;
  const terminalRows = process$1.stdout.rows || 24;
  const maxExtraLines = Math.max(terminalRows - promptLineCount - 1, 0);
  const hintLines = commands.length === 0 ? wrapPlainText(
    "Tip: '/' \uB85C \uBA85\uB839 \uBA54\uB274\uB97C \uC5F4\uC5B4 \uD604\uC7AC \uC138\uC158\uC5D0\uC11C \uC0AC\uC6A9\uD560 \uC218 \uC788\uB294 \uBA85\uB839\uC744 \uD655\uC778\uD569\uB2C8\uB2E4.",
    getTerminalColumns(),
    getTerminalColumns()
  ).map((line) => colorize(line, ANSI.gray)) : [];
  const paletteLines = commands.length > 0 ? renderCommandPalette(commands, commandCursor, maxExtraLines) : [];
  const lines = [...paletteLines, ...hintLines, ...promptLayout.lines];
  const cursorRowOffset = lines.length - 1;
  return renderPromptLayout(
    {
      cursorColumn: promptLayout.cursorColumn,
      cursorRowOffset,
      lines,
      totalLines: lines.length
    },
    previousState
  );
}
function restoreHistoryBuffer(history, historyCursor) {
  if (historyCursor < 0 || historyCursor >= history.length) {
    return "";
  }
  return history[historyCursor] || "";
}
function getHistoryNavigationDirection(key) {
  if (key.shift && key.name === "up") {
    return "up";
  }
  if (key.shift && key.name === "down") {
    return "down";
  }
  return null;
}
async function askQuestion(question) {
  return new Promise((resolve, reject) => {
    const { stdin } = process;
    const rawState = "isRaw" in stdin ? Boolean(stdin.isRaw) : false;
    let buffer = "";
    const cleanup = () => {
      stdin.removeListener("keypress", onKeyPress);
      if (stdin.isTTY) {
        stdin.setRawMode(rawState);
      }
      stdin.pause();
    };
    let renderState;
    const onKeyPress = (input, key) => {
      if (key.ctrl && key.name === "c") {
        clearRenderedPrompt(renderState);
        cleanup();
        reject(createUserTerminatedError("\uC0AC\uC6A9\uC790\uAC00 \uC9C8\uBB38 \uC785\uB825 \uC911 \uC138\uC158 \uC885\uB8CC\uB97C \uC694\uCCAD\uD588\uC2B5\uB2C8\uB2E4."));
        return;
      }
      if (key.name === "escape") {
        clearRenderedPrompt(renderState);
        cleanup();
        reject(createUserCancelledError("\uC0AC\uC6A9\uC790\uAC00 \uC9C8\uBB38 \uC785\uB825\uC744 \uCDE8\uC18C\uD588\uC2B5\uB2C8\uB2E4."));
        return;
      }
      if (key.name === "return" || key.name === "enter") {
        const resolved = buffer.trim();
        clearRenderedPrompt(renderState);
        cleanup();
        console.log(`${question}${resolved}`);
        appendSlashCommandTelemetryInputValue(resolved);
        resolve(resolved);
        return;
      }
      if (key.name === "backspace") {
        if (buffer.length > 0) {
          buffer = buffer.slice(0, -1);
          renderState = renderQuestionPrompt(question, buffer, renderState);
        }
        return;
      }
      if (input && !key.ctrl && !key.meta) {
        buffer += input;
        renderState = renderQuestionPrompt(question, buffer, renderState);
      }
    };
    readline__default.default.emitKeypressEvents(stdin);
    if (stdin.isTTY) {
      stdin.setRawMode(true);
    }
    stdin.resume();
    stdin.on("keypress", onKeyPress);
    renderState = renderQuestionPrompt(question, buffer);
  });
}
function printSessionBanner(options) {
  const commandSummary = options.commands.map((command) => `${command.command} ${colorize("-", ANSI.gray)} ${command.description}`);
  const showStream = `${colorize("AI Stream", ANSI.gray)} ${options.streamOutputEnabled ? renderBadge("ON", "accent") : renderBadge("OFF", "muted")}`;
  const tokenOptimizerEnabled = `${colorize("TokenOptimize", ANSI.gray)} ${options.tokenOptimizerEnabled ? renderBadge("ON", "accent") : renderBadge("OFF", "muted")}`;
  const service = `${colorize("Service", ANSI.gray)} ${renderBadge(options.service, "service")}`;
  const version = `${colorize("Version", ANSI.gray)} ${renderBadge("0.5.0", "service")}`;
  const mode = ` ${colorize("Mode", ANSI.gray)} ${options.testMode ? renderBadge("TEST", "warn") : renderBadge("LIVE", "accent")}${options.traceMode ? ` ${renderBadge("TRACE", "muted")}` : ""}`;
  const statusSummary = `${tokenOptimizerEnabled} | ${showStream}`;
  console.log(
    createBox(
      `Ju-hong-e Interactive Session( \uD55C\uD654\uC0DD\uBA85 \uD1B5\uD569 AI-Tool ${mode})`,
      [
        `${version} | ${service}`,
        statusSummary,
        ``,
        ...commandSummary
      ],
      [
        colorize(
          "Slash \uBA85\uB839\uC740 '/' \uC785\uB825 \uC2DC \uBCFC \uC218 \uC788\uC2B5\uB2C8\uB2E4.",
          ANSI.gray
        ),
        colorize("\uC2E4\uC2DC\uAC04 \uC751\uB2F5 \uCD9C\uB825\uC740 /show-stream \uC73C\uB85C \uCF1C\uACE0 \uB04C \uC218 \uC788\uC2B5\uB2C8\uB2E4.", ANSI.gray),
        colorize("ESC\uB294 \uD604\uC7AC \uC791\uC5C5 \uCDE8\uC18C, Ctrl+C\uB294 \uC138\uC158 \uC885\uB8CC\uC785\uB2C8\uB2E4.", ANSI.gray)
      ]
    ).join("\n")
  );
}
function promptSessionInput(options) {
  return new Promise((resolve, reject) => {
    const { stdin } = process;
    const rawState = "isRaw" in stdin ? Boolean(stdin.isRaw) : false;
    const prefix = getPromptPrefix(options.service, options.testMode, options.traceMode);
    let buffer = "";
    let historyCursor = -1;
    let historyDraft = "";
    let commandCursor = 0;
    let renderState;
    const cleanup = () => {
      stdin.removeListener("keypress", onKeyPress);
      if (stdin.isTTY) {
        stdin.setRawMode(rawState);
      }
      stdin.pause();
    };
    const applySelectedCommand = () => {
      const commands = getVisibleCommandOptions(options.commands, buffer);
      const selectedCommand = commands[commandCursor];
      if (!selectedCommand) {
        return false;
      }
      buffer = selectedCommand.insertValue || selectedCommand.command;
      commandCursor = 0;
      historyCursor = -1;
      historyDraft = "";
      return true;
    };
    const render = () => {
      const commands = getVisibleCommandOptions(options.commands, buffer);
      commandCursor = Math.max(0, Math.min(commandCursor, Math.max(commands.length - 1, 0)));
      renderState = renderInteractivePrompt(
        prefix,
        buffer,
        commands,
        commandCursor,
        renderState
      );
    };
    const moveHistory = (direction) => {
      if (options.history.length === 0) {
        return;
      }
      if (historyCursor === -1) {
        historyDraft = buffer;
      }
      if (direction === "up") {
        historyCursor = historyCursor === -1 ? options.history.length - 1 : Math.max(historyCursor - 1, 0);
        buffer = restoreHistoryBuffer(options.history, historyCursor);
        return;
      }
      if (historyCursor === -1) {
        return;
      }
      if (historyCursor >= options.history.length - 1) {
        historyCursor = -1;
        buffer = historyDraft;
        return;
      }
      historyCursor += 1;
      buffer = restoreHistoryBuffer(options.history, historyCursor);
    };
    const onKeyPress = (input, key) => {
      const visibleCommands = getVisibleCommandOptions(options.commands, buffer);
      const historyDirection = getHistoryNavigationDirection(key);
      if (key.ctrl && key.name === "c") {
        clearRenderedPrompt(renderState);
        cleanup();
        reject(createUserTerminatedError("\uC0AC\uC6A9\uC790\uAC00 \uC138\uC158 \uC885\uB8CC\uB97C \uC694\uCCAD\uD588\uC2B5\uB2C8\uB2E4."));
        return;
      }
      if (key.name === "return" || key.name === "enter") {
        if (buffer.trim() === "/" && visibleCommands.length > 0) {
          applySelectedCommand();
          render();
          return;
        }
        const resolved = buffer.trim();
        clearRenderedPrompt(renderState);
        commitInteractiveLine(prefix, resolved);
        cleanup();
        resolve(resolved);
        return;
      }
      if (key.name === "tab") {
        if (applySelectedCommand()) {
          render();
        }
        return;
      }
      if (key.name === "escape") {
        if (buffer.length > 0) {
          buffer = "";
          commandCursor = 0;
          historyCursor = -1;
          historyDraft = "";
          render();
        }
        return;
      }
      if (key.name === "backspace") {
        if (buffer.length > 0) {
          buffer = buffer.slice(0, -1);
          historyCursor = -1;
          historyDraft = "";
          commandCursor = 0;
          render();
        }
        return;
      }
      if (historyDirection) {
        moveHistory(historyDirection);
        render();
        return;
      }
      if (key.name === "up") {
        if (visibleCommands.length > 0) {
          commandCursor = commandCursor === 0 ? visibleCommands.length - 1 : commandCursor - 1;
        }
        render();
        return;
      }
      if (key.name === "down") {
        if (visibleCommands.length > 0) {
          commandCursor = commandCursor === visibleCommands.length - 1 ? 0 : commandCursor + 1;
        }
        render();
        return;
      }
      if (input && !key.ctrl && !key.meta) {
        buffer += input;
        historyCursor = -1;
        historyDraft = "";
        commandCursor = 0;
        render();
      }
    };
    readline__default.default.emitKeypressEvents(stdin);
    if (stdin.isTTY) {
      stdin.setRawMode(true);
    }
    stdin.resume();
    stdin.on("keypress", onKeyPress);
    render();
  });
}
var SINGLE_OPTION_PREFIX_WIDTH = 2;
var SINGLE_OPTION_GAP_WIDTH = 1;
var SINGLE_OPTION_MIN_LABEL_WIDTH = 8;
var SINGLE_OPTION_LABEL_PADDING = 2;
function computeSingleOptionColumnWidths(options) {
  const boxInnerWidth = getViewportWidth() - 4;
  const maxLabelCellWidth = Math.max(
    SINGLE_OPTION_MIN_LABEL_WIDTH,
    ...options.map((option) => visibleLength(option.label) + SINGLE_OPTION_LABEL_PADDING)
  );
  const labelWidth = Math.min(maxLabelCellWidth, Math.floor(boxInnerWidth * 0.5));
  const descriptionWidth = Math.max(0, boxInnerWidth - SINGLE_OPTION_PREFIX_WIDTH - labelWidth - SINGLE_OPTION_GAP_WIDTH);
  return { descriptionWidth, labelWidth };
}
function selectSingleOption(title, options) {
  return new Promise((resolve, reject) => {
    if (options.length === 0) {
      reject(new Error("\uC120\uD0DD \uAC00\uB2A5\uD55C \uD56D\uBAA9\uC774 \uC5C6\uC2B5\uB2C8\uB2E4."));
      return;
    }
    const { stdin } = process;
    const rawState = "isRaw" in stdin ? Boolean(stdin.isRaw) : false;
    let cursor = 0;
    const cleanup = () => {
      stdin.removeListener("keypress", onKeyPress);
      if (stdin.isTTY) {
        stdin.setRawMode(rawState);
      }
      stdin.pause();
      console.clear();
    };
    const { labelWidth, descriptionWidth } = computeSingleOptionColumnWidths(options);
    const render = () => {
      renderScreenBox(
        title,
        options.map((option, index) => {
          const prefix = cursor === index ? colorize(">", ANSI.green) : " ";
          const label = cursor === index ? colorize(option.label, ANSI.green) : option.label;
          const description = option.description ? truncateValue(option.description, descriptionWidth) : "";
          return `${prefix} ${padVisible(label, labelWidth)} ${colorize(description, ANSI.gray)}`;
        }),
        [
          `${colorize("Up/Down", ANSI.yellow)} \uC774\uB3D9`,
          `${colorize("Enter", ANSI.yellow)} \uC120\uD0DD`,
          `${colorize("ESC", ANSI.yellow)} \uCDE8\uC18C`,
          `${colorize("Ctrl+C", ANSI.yellow)} \uC138\uC158 \uC885\uB8CC`
        ]
      );
    };
    const onKeyPress = (_input, key) => {
      if (key.ctrl && key.name === "c") {
        cleanup();
        reject(createUserTerminatedError("\uC0AC\uC6A9\uC790\uAC00 \uC120\uD0DD \uC785\uB825 \uC911 \uC138\uC158 \uC885\uB8CC\uB97C \uC694\uCCAD\uD588\uC2B5\uB2C8\uB2E4."));
        return;
      }
      if (key.name === "escape") {
        cleanup();
        reject(createUserCancelledError("\uC0AC\uC6A9\uC790\uAC00 \uC120\uD0DD \uC785\uB825\uC744 \uCDE8\uC18C\uD588\uC2B5\uB2C8\uB2E4."));
        return;
      }
      if (key.name === "up") {
        cursor = cursor === 0 ? options.length - 1 : cursor - 1;
        render();
        return;
      }
      if (key.name === "down") {
        cursor = cursor === options.length - 1 ? 0 : cursor + 1;
        render();
        return;
      }
      if (key.name === "return" || key.name === "enter") {
        const selected = options[cursor];
        if (!selected) {
          cleanup();
          reject(new Error("\uC120\uD0DD\uD55C \uD56D\uBAA9\uC744 \uCC3E\uC744 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4."));
          return;
        }
        cleanup();
        appendSlashCommandTelemetryInputValue(selected.value);
        resolve(selected.value);
      }
    };
    readline__default.default.emitKeypressEvents(stdin);
    if (stdin.isTTY) {
      stdin.setRawMode(true);
    }
    stdin.resume();
    stdin.on("keypress", onKeyPress);
    render();
  });
}
function selectMultipleOptions(title, options, windowSize = 10) {
  return new Promise((resolve, reject) => {
    if (options.length === 0) {
      resolve([]);
      return;
    }
    const { stdin } = process;
    const rawState = "isRaw" in stdin ? Boolean(stdin.isRaw) : false;
    let cursor = 0;
    const selectedIndexes = /* @__PURE__ */ new Set();
    const cleanup = () => {
      stdin.removeListener("keypress", onKeyPress);
      if (stdin.isTTY) {
        stdin.setRawMode(rawState);
      }
      stdin.pause();
      console.clear();
    };
    const render = () => {
      const start = Math.max(0, Math.min(cursor - Math.floor(windowSize / 2), Math.max(options.length - windowSize, 0)));
      const visibleOptions = options.slice(start, start + windowSize);
      renderScreenBox(
        title,
        [
          `${colorize("\uD45C\uC2DC \uBC94\uC704", ANSI.gray)} ${start + 1}-${Math.min(start + windowSize, options.length)} / ${options.length}`,
          `${colorize("\uC120\uD0DD \uAC1C\uC218", ANSI.gray)} ${selectedIndexes.size}`,
          ""
        ].concat(
          visibleOptions.map((option, offset) => {
            const index = start + offset;
            const isActive = cursor === index;
            const isSelected = selectedIndexes.has(index);
            const prefix = isActive ? colorize(">", ANSI.green) : " ";
            const checked = isSelected ? colorize("[x]", ANSI.green) : "[ ]";
            const label = isActive ? colorize(truncateValue(option.label, 54), ANSI.green) : truncateValue(option.label, 54);
            const description = option.description ? colorize(truncateValue(option.description, 28), ANSI.gray) : "";
            return `${prefix} ${checked} ${padVisible(label, 56)} ${description}`;
          })
        ),
        [
          `${colorize("Up/Down", ANSI.yellow)} \uC774\uB3D9`,
          `${colorize("Space", ANSI.yellow)} \uC120\uD0DD/\uD574\uC81C`,
          `${colorize("Enter", ANSI.yellow)} \uC644\uB8CC`,
          `${colorize("ESC", ANSI.yellow)} \uCDE8\uC18C`,
          `${colorize("Ctrl+C", ANSI.yellow)} \uC138\uC158 \uC885\uB8CC`
        ]
      );
    };
    const onKeyPress = (_input, key) => {
      if (key.ctrl && key.name === "c") {
        cleanup();
        reject(createUserTerminatedError("\uC0AC\uC6A9\uC790\uAC00 \uC120\uD0DD \uC785\uB825 \uC911 \uC138\uC158 \uC885\uB8CC\uB97C \uC694\uCCAD\uD588\uC2B5\uB2C8\uB2E4."));
        return;
      }
      if (key.name === "escape") {
        cleanup();
        reject(createUserCancelledError("\uC0AC\uC6A9\uC790\uAC00 \uC120\uD0DD \uC785\uB825\uC744 \uCDE8\uC18C\uD588\uC2B5\uB2C8\uB2E4."));
        return;
      }
      if (key.name === "up") {
        cursor = cursor === 0 ? options.length - 1 : cursor - 1;
        render();
        return;
      }
      if (key.name === "down") {
        cursor = cursor === options.length - 1 ? 0 : cursor + 1;
        render();
        return;
      }
      if (key.name === "space") {
        if (selectedIndexes.has(cursor)) {
          selectedIndexes.delete(cursor);
        } else {
          selectedIndexes.add(cursor);
        }
        render();
        return;
      }
      if (key.name === "return" || key.name === "enter") {
        const resolvedValues = [...selectedIndexes].sort((left, right) => left - right).flatMap((index) => {
          const option = options[index];
          return option ? [option.value] : [];
        });
        cleanup();
        appendSlashCommandTelemetryInputValue(resolvedValues);
        resolve(resolvedValues);
      }
    };
    readline__default.default.emitKeypressEvents(stdin);
    if (stdin.isTTY) {
      stdin.setRawMode(true);
    }
    stdin.resume();
    stdin.on("keypress", onKeyPress);
    render();
  });
}

exports.askQuestion = askQuestion;
exports.createSessionActionStatus = createSessionActionStatus;
exports.printSessionBanner = printSessionBanner;
exports.promptSessionInput = promptSessionInput;
exports.selectMultipleOptions = selectMultipleOptions;
exports.selectSingleOption = selectSingleOption;
