'use strict';

var fs3 = require('fs');
var path = require('path');
var child_process = require('child_process');
var util = require('util');
require('fs/promises');
require('os');
require('url');
var readline3 = require('readline');
var process = require('process');
require('posthog-node');

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

var fs3__default = /*#__PURE__*/_interopDefault(fs3);
var path__default = /*#__PURE__*/_interopDefault(path);
var readline3__default = /*#__PURE__*/_interopDefault(readline3);

// src/features/token-optimizer/infrastructure/config.ts
var DEFAULT_TOKEN_OPTIMIZER_STATE = {
  enabled: false
};
globalThis.__JU_HONG_E_TOKEN_OPTIMIZER_STATE__ ?? (globalThis.__JU_HONG_E_TOKEN_OPTIMIZER_STATE__ = {
  ...DEFAULT_TOKEN_OPTIMIZER_STATE
});

// src/platform/core/cancellation.ts
var USER_CANCELLED_ERROR_CODE = "JUHONG_E_USER_CANCELLED";
var USER_TERMINATED_ERROR_CODE = "JUHONG_E_USER_TERMINATED";
function hasCancellationErrorCode(error, code) {
  return Boolean(
    error && typeof error === "object" && "code" in error && error.code === code
  );
}
function isUserCancelledError(error) {
  return hasCancellationErrorCode(error, USER_CANCELLED_ERROR_CODE);
}
function isUserTerminatedError(error) {
  return hasCancellationErrorCode(error, USER_TERMINATED_ERROR_CODE);
}
function runGitCommand(rootDir, command) {
  return child_process.execSync(command, {
    cwd: rootDir,
    encoding: "utf8",
    maxBuffer: 1024 * 1024 * 20,
    stdio: ["ignore", "pipe", "pipe"]
  }).trim();
}
function isGitRepository(rootDir) {
  try {
    runGitCommand(rootDir, "git rev-parse --show-toplevel");
    return true;
  } catch {
    return false;
  }
}
function captureWorkspaceSnapshot(rootDir) {
  if (!isGitRepository(rootDir)) {
    return {
      available: false,
      branch: "",
      diffNameStatus: "",
      diffStat: "",
      gitRoot: "",
      note: "\uD604\uC7AC \uC791\uC5C5 \uACBD\uB85C\uAC00 Git \uC800\uC7A5\uC18C\uAC00 \uC544\uB2D9\uB2C8\uB2E4.",
      recentCommits: [],
      statusLines: []
    };
  }
  const gitRoot = runGitCommand(rootDir, "git rev-parse --show-toplevel");
  const branch = runGitCommand(rootDir, "git branch --show-current");
  const statusOutput = runGitCommand(rootDir, "git status --short");
  const diffStat = runGitCommand(rootDir, "git diff --stat");
  const diffNameStatus = runGitCommand(rootDir, "git diff --name-status");
  const recentCommits = runGitCommand(rootDir, "git log --oneline -5");
  return {
    available: true,
    branch,
    diffNameStatus,
    diffStat,
    gitRoot,
    note: "",
    recentCommits: recentCommits ? recentCommits.split("\n").filter(Boolean) : [],
    statusLines: statusOutput ? statusOutput.split("\n").filter(Boolean) : []
  };
}
function statusLineToPath(statusLine) {
  const normalized = statusLine.trim();
  if (!normalized) {
    return "";
  }
  const pathValue = normalized.slice(3).split(" -> ").pop();
  return pathValue?.trim() || normalized;
}
function diffWorkspaceSnapshots(before, after) {
  const beforeSet = new Set(before.statusLines);
  const afterSet = new Set(after.statusLines);
  const beforeOnly = before.statusLines.filter((line) => !afterSet.has(line));
  const afterOnly = after.statusLines.filter((line) => !beforeSet.has(line));
  const touchedFiles = Array.from(
    new Set([...beforeOnly.map(statusLineToPath), ...afterOnly.map(statusLineToPath)].filter(Boolean))
  );
  return {
    afterOnly,
    beforeOnly,
    touchedFiles
  };
}
function formatCodeBlock(content, language = "") {
  return `\`\`\`${language}
${content || "(\uC5C6\uC74C)"}
\`\`\``;
}
function formatWorkspaceSnapshot(snapshot) {
  if (!snapshot.available) {
    return snapshot.note;
  }
  return [
    `- Git Root: \`${snapshot.gitRoot}\``,
    `- Branch: \`${snapshot.branch || "(detached)"}\``,
    "",
    "### git status --short",
    formatCodeBlock(snapshot.statusLines.join("\n")),
    "",
    "### git diff --stat",
    formatCodeBlock(snapshot.diffStat),
    "",
    "### git diff --name-status",
    formatCodeBlock(snapshot.diffNameStatus),
    "",
    "### \uCD5C\uADFC \uCEE4\uBC0B",
    formatCodeBlock(snapshot.recentCommits.join("\n"))
  ].join("\n");
}
function formatWorkspaceDelta(delta) {
  return [
    "### \uC0C8\uB85C \uAC10\uC9C0\uB41C \uC0C1\uD0DC",
    formatCodeBlock(delta.afterOnly.join("\n")),
    "",
    "### \uC0AC\uB77C\uC9C4 \uC774\uC804 \uC0C1\uD0DC",
    formatCodeBlock(delta.beforeOnly.join("\n")),
    "",
    "### \uC601\uD5A5 \uD30C\uC77C",
    formatCodeBlock(delta.touchedFiles.join("\n"))
  ].join("\n");
}
function safeExcerpt(content, limit = 3e3) {
  if (!content) {
    return "";
  }
  if (content.length <= limit) {
    return content;
  }
  return `${content.slice(0, limit)}
... (truncated ${content.length - limit} chars)`;
}
function stringifyUnknown(value) {
  if (value === void 0 || value === null) {
    return "";
  }
  if (typeof value === "string") {
    return value;
  }
  if (Buffer.isBuffer(value)) {
    return value.toString("utf8");
  }
  if (value instanceof Error) {
    return value.stack || value.message;
  }
  return util.inspect(value, { depth: 6, breakLength: 120 });
}
function getErrorSummary(error) {
  if (error instanceof Error) {
    return `${error.name}: ${error.message}`;
  }
  return stringifyUnknown(error) || "Unknown error";
}

// src/platform/core/timestamp-helpers.ts
function padTimestampPart(value) {
  return String(value).padStart(2, "0");
}
function getTimestampParts(now = /* @__PURE__ */ new Date()) {
  return {
    year: now.getFullYear(),
    month: padTimestampPart(now.getMonth() + 1),
    day: padTimestampPart(now.getDate()),
    hour: padTimestampPart(now.getHours()),
    minute: padTimestampPart(now.getMinutes()),
    second: padTimestampPart(now.getSeconds())
  };
}
function getFileTimestamp(now = /* @__PURE__ */ new Date()) {
  const { year, month, day, hour, minute, second } = getTimestampParts(now);
  return `${year}-${month}-${day}_${hour}-${minute}-${second}`;
}
function getHumanReadableNow(now = /* @__PURE__ */ new Date()) {
  const { year, month, day, hour, minute, second } = getTimestampParts(now);
  return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
}

// src/platform/core/history-helpers.ts
var DEFAULT_HISTORY_LIMIT = 5;
var DEFAULT_HISTORY_CHAR_LIMIT = 14e3;
var CONVERSATION_HISTORY_SCOPES = [
  "chat",
  "shell-command",
  "commit",
  "review",
  "gen-html",
  "gen-storybook",
  "minify-md",
  "local-server",
  "mcp",
  "security-policy",
  "show-stream",
  "token-optimizer",
  "service-change"
];
var aiServicesRef = [];
function setAiServicesRef(services) {
  aiServicesRef = services;
}
function isConversationHistoryScope(value) {
  return CONVERSATION_HISTORY_SCOPES.includes(value);
}
function parseConversationHistoryEntry(raw) {
  try {
    const parsed = JSON.parse(raw);
    if (!parsed || typeof parsed !== "object") {
      return void 0;
    }
    if (typeof parsed.timestamp !== "string" || typeof parsed.title !== "string" || typeof parsed.summary !== "string" || typeof parsed.scope !== "string" || typeof parsed.service !== "string") {
      return void 0;
    }
    if (!isConversationHistoryScope(parsed.scope) || !aiServicesRef.includes(parsed.service)) {
      return void 0;
    }
    const previousService = typeof parsed.previousService === "string" && (parsed.previousService === "" || aiServicesRef.includes(parsed.previousService)) ? parsed.previousService : void 0;
    const nextService = typeof parsed.nextService === "string" && aiServicesRef.includes(parsed.nextService) ? parsed.nextService : void 0;
    return {
      input: typeof parsed.input === "string" ? parsed.input : void 0,
      nextService,
      output: typeof parsed.output === "string" ? parsed.output : void 0,
      previousService,
      scope: parsed.scope,
      service: parsed.service,
      summary: parsed.summary,
      timestamp: parsed.timestamp,
      title: parsed.title
    };
  } catch {
    return void 0;
  }
}
function appendConversationHistory(paths, entry) {
  const normalizedEntry = {
    ...entry,
    summary: entry.summary.trim() || entry.title.trim(),
    timestamp: entry.timestamp || getHumanReadableNow(),
    title: entry.title.trim()
  };
  fs3__default.default.appendFileSync(paths.conversationHistoryPath, `${JSON.stringify(normalizedEntry)}
`, "utf8");
  return normalizedEntry;
}
function loadConversationHistory(paths, limit = DEFAULT_HISTORY_LIMIT) {
  if (!fs3__default.default.existsSync(paths.conversationHistoryPath)) {
    return [];
  }
  const lines = fs3__default.default.readFileSync(paths.conversationHistoryPath, "utf8").split("\n").map((line) => line.trim()).filter(Boolean);
  if (lines.length === 0) {
    return [];
  }
  return lines.map(parseConversationHistoryEntry).filter((entry) => entry !== void 0).slice(-limit);
}
function formatConversationHistoryEntry(entry, limit) {
  const inputLimit = Math.max(180, Math.floor(limit * 0.35));
  const outputLimit = Math.max(220, limit - inputLimit);
  const lines = [`## ${entry.timestamp} | ${entry.scope} | ${entry.service}`, `\uC81C\uBAA9: ${entry.title}`];
  if (entry.scope === "service-change") {
    lines.push(`\uC11C\uBE44\uC2A4 \uBCC0\uACBD: ${entry.previousService || "(\uC5C6\uC74C)"} -> ${entry.nextService || entry.service}`);
    lines.push(`\uC694\uC57D: ${safeExcerpt(entry.summary, outputLimit)}`);
    return lines.join("\n");
  }
  if (entry.input) {
    lines.push("");
    lines.push("\uC0AC\uC6A9\uC790 \uC785\uB825");
    lines.push(formatCodeBlock(safeExcerpt(entry.input, inputLimit)));
  }
  if (entry.output) {
    lines.push("");
    lines.push("\uC774\uC804 \uACB0\uACFC \uC694\uC57D");
    lines.push(formatCodeBlock(safeExcerpt(entry.output, outputLimit)));
  } else if (entry.summary) {
    lines.push("");
    lines.push("\uACB0\uACFC \uC694\uC57D");
    lines.push(formatCodeBlock(safeExcerpt(entry.summary, outputLimit)));
  }
  return lines.join("\n");
}
function formatConversationHistory(entries, charLimit) {
  if (entries.length === 0) {
    return "";
  }
  const entryLimit = Math.max(400, Math.floor(charLimit / Math.max(entries.length, 1)));
  const content = entries.map((entry) => formatConversationHistoryEntry(entry, entryLimit)).join("\n\n");
  return safeExcerpt(content, charLimit);
}
function loadRecentHistoryContext(paths, limit = DEFAULT_HISTORY_LIMIT, charLimit = DEFAULT_HISTORY_CHAR_LIMIT) {
  const conversationEntries = loadConversationHistory(paths, limit);
  return formatConversationHistory(conversationEntries, charLimit);
}

// src/platform/types/app.ts
var AI_SERVICE = {
  CLAUDE: "claude",
  CODEX: "codex",
  GEMINI: "gemini"
};
function getAvailableFilePath(directory, baseName, extension) {
  const first = path__default.default.join(directory, `${baseName}${extension}`);
  if (!fs3__default.default.existsSync(first)) {
    return first;
  }
  let next = first;
  let count = 1;
  while (fs3__default.default.existsSync(next)) {
    next = path__default.default.join(directory, `${baseName}-${count}${extension}`);
    if (!fs3__default.default.existsSync(next)) {
      break;
    }
    count += 1;
  }
  return next;
}
function appendHistoryIndex(paths, summary, relativeFilePath) {
  const line = `- ${getHumanReadableNow()} | ${summary} | file: \`${relativeFilePath}\`
`;
  fs3__default.default.appendFileSync(paths.historyIndexPath, line, "utf8");
}
function renderSections(sections = []) {
  if (sections.length === 0) {
    return "";
  }
  return sections.map((section) => `
## ${section.heading}

${section.markdown}
`).join("\n");
}
function writeTurnHistory(paths, record) {
  const baseName = `${getFileTimestamp()}-${record.scope}`;
  const filePath = getAvailableFilePath(paths.turnsDir, baseName, ".md");
  const markdown = `# ${record.title}

- \uC2DC\uAC01: ${getHumanReadableNow()}
- scope: \`${record.scope}\`
- service: \`${record.service}\`
- skipped: \`${record.skipped}\`

## \uC0AC\uC6A9\uC790 \uC785\uB825

${formatCodeBlock(record.input)}

## AI \uC751\uB2F5

${record.output || "(\uC751\uB2F5 \uC5C6\uC74C)"}

## \uCD5C\uADFC \uD788\uC2A4\uD1A0\uB9AC \uC8FC\uC785

${formatCodeBlock(record.historyContext)}

## \uC2E4\uD589 \uBA85\uB839\uC5B4 \uBBF8\uB9AC\uBCF4\uAE30

${formatCodeBlock(record.previewCommand, "sh")}

## \uC791\uC5C5 \uC804 \uC6CC\uD06C\uC2A4\uD398\uC774\uC2A4

${formatWorkspaceSnapshot(record.workspaceBefore)}

## \uC791\uC5C5 \uD6C4 \uC6CC\uD06C\uC2A4\uD398\uC774\uC2A4

${formatWorkspaceSnapshot(record.workspaceAfter)}

## \uC6CC\uD06C\uC2A4\uD398\uC774\uC2A4 \uBCC0\uD654

${formatWorkspaceDelta(record.workspaceDelta)}${renderSections(record.extraSections)}
`;
  fs3__default.default.writeFileSync(filePath, markdown, "utf8");
  appendHistoryIndex(paths, `${record.scope} | ${record.service} | ${record.title}`, path__default.default.relative(paths.rootDir, filePath));
  return filePath;
}

// src/platform/core/helpers.ts
var AI_SERVICES = Object.values(AI_SERVICE);
setAiServicesRef(AI_SERVICES);
util.promisify(child_process.execFile);

// src/platform/request-security/registry.ts
var securityRegistryState = globalThis.__JUHONG_E_SECURITY_REGISTRY__ ?? (globalThis.__JUHONG_E_SECURITY_REGISTRY__ = {
  patternRules: /* @__PURE__ */ new Map(),
  validatorRules: /* @__PURE__ */ new Map()
});
var GLOBAL_PATTERN_RULES = securityRegistryState.patternRules;
securityRegistryState.validatorRules;
function addGlobalSecurityPattern(rule) {
  GLOBAL_PATTERN_RULES.set(rule.name, rule);
}

// src/platform/request-security/default-rules.ts
var initialized = false;
function formatResidentRegistrationNumber(matchedText) {
  const digits = matchedText.replace(/\D/g, "");
  if (digits.length !== 13) {
    return `${matchedText.slice(0, 3)}***`;
  }
  return `${digits.slice(0, 6)}-${digits[6]}******`;
}
function ensureDefaultSecurityRules() {
  if (initialized) {
    return;
  }
  initialized = true;
  addGlobalSecurityPattern({
    formatMatch: formatResidentRegistrationNumber,
    message: "\uBCF4\uC548 \uC815\uCC45\uC5D0 \uC758\uD574 \uC8FC\uBBFC\uB4F1\uB85D\uBC88\uD638 \uD615\uD0DC\uC758 \uAC12\uC774 \uD3EC\uD568\uB41C \uC785\uB825\uC740 \uC2E4\uD589\uD560 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4.",
    name: "resident-registration-number",
    pattern: /\b\d{6}[- ]?[1-4]\d{6}\b/
  });
}
function createPromptHistoryReferences(paths) {
  return {
    aiHistoryDirectoryPath: paths.historyDir,
    promptHistoryFilePath: paths.promptHistoryPath
  };
}
function isPromptMarkdownFileReference(asset) {
  return typeof asset !== "string";
}
function isPromptRuleGroupAsset(asset) {
  return typeof asset !== "string" && !("kind" in asset && asset.kind === "file-reference");
}
function clonePromptMarkdownAsset(asset) {
  return isPromptMarkdownFileReference(asset) ? {
    ...asset,
    filePath: path__default.default.normalize(asset.filePath)
  } : asset;
}
var DEFAULT_STREAM_OUTPUT_STATE = {
  enabled: false
};
var streamOutputRuntimeState = globalThis.__JU_HONG_E_STREAM_OUTPUT_STATE__ ?? (globalThis.__JU_HONG_E_STREAM_OUTPUT_STATE__ = {
  ...DEFAULT_STREAM_OUTPUT_STATE
});
function normalizeStreamOutputState(value) {
  if (!value || typeof value !== "object") {
    return { ...DEFAULT_STREAM_OUTPUT_STATE };
  }
  const enabled = "enabled" in value ? Boolean(value.enabled) : DEFAULT_STREAM_OUTPUT_STATE.enabled;
  return {
    enabled
  };
}
function readStreamOutputConfig(paths) {
  if (!fs3__default.default.existsSync(paths.streamOutputConfigPath)) {
    return { ...DEFAULT_STREAM_OUTPUT_STATE };
  }
  try {
    const parsed = JSON.parse(fs3__default.default.readFileSync(paths.streamOutputConfigPath, "utf8"));
    return normalizeStreamOutputState(parsed);
  } catch {
    return { ...DEFAULT_STREAM_OUTPUT_STATE };
  }
}
function hydrateStreamOutputState(paths) {
  const nextState = readStreamOutputConfig(paths);
  streamOutputRuntimeState.enabled = nextState.enabled;
  return streamOutputRuntimeState.enabled;
}
function saveStreamOutputConfig(paths, enabled) {
  const nextState = {
    enabled: Boolean(enabled)
  };
  fs3__default.default.writeFileSync(paths.streamOutputConfigPath, `${JSON.stringify(nextState, null, 2)}
`, "utf8");
  streamOutputRuntimeState.enabled = nextState.enabled;
  return nextState;
}

// src/platform/actions/shared.ts
function captureActionContext(paths) {
  return {
    historyContext: loadRecentHistoryContext(paths),
    historyReferences: createPromptHistoryReferences(paths),
    workspaceBefore: captureWorkspaceSnapshot(paths.rootDir)
  };
}
function finalizeAction(paths, context, result) {
  const extraSections = [...result.extraSections || [], ...buildPromptAuditSections(result.promptAudit)];
  const workspaceAfter = captureWorkspaceSnapshot(paths.rootDir);
  const workspaceDelta = diffWorkspaceSnapshots(context.workspaceBefore, workspaceAfter);
  const historyPath = writeTurnHistory(paths, {
    extraSections,
    historyContext: context.historyContext,
    input: result.input,
    output: result.output,
    previewCommand: result.previewCommand,
    scope: result.scope,
    service: result.service,
    skipped: result.skipped,
    title: result.title,
    workspaceAfter,
    workspaceBefore: context.workspaceBefore,
    workspaceDelta
  });
  appendConversationHistory(paths, {
    input: result.input,
    output: result.output,
    scope: result.scope,
    service: result.service,
    summary: result.summary,
    title: result.title
  });
  return {
    historyPath,
    previewCommand: result.previewCommand,
    scope: result.scope,
    service: result.service,
    skipped: result.skipped,
    summary: result.summary,
    title: result.title,
    traceMessages: []
  };
}
function formatAuditNumber(value) {
  return value.toLocaleString("ko-KR");
}
function buildPromptAuditSections(promptAudit) {
  if (!promptAudit) {
    return [];
  }
  return [
    {
      heading: "\uD504\uB86C\uD504\uD2B8 \uCD5C\uC801\uD654 \uC694\uC57D",
      markdown: [
        `- mode: \`${promptAudit.mode}\``,
        `- \uCD5C\uC801\uD654 \uC804 \uD504\uB86C\uD504\uD2B8 \uD06C\uAE30: \`${formatAuditNumber(promptAudit.originalBytes)} bytes\``,
        `- \uCD5C\uC801\uD654 \uD6C4 \uD504\uB86C\uD504\uD2B8 \uD06C\uAE30: \`${formatAuditNumber(promptAudit.optimizedBytes)} bytes\``,
        `- \uAC10\uC18C\uD55C \uD504\uB86C\uD504\uD2B8 \uD06C\uAE30: \`${formatAuditNumber(promptAudit.reducedBytes)} bytes\``,
        `- \uAC10\uC18C \uBE44\uC728: \`${promptAudit.reductionPercent}%\``,
        `- \uC608\uC0C1 \uD1A0\uD070(\uC804 -> \uD6C4): \`${formatAuditNumber(promptAudit.originalEstimatedTokens)} -> ${formatAuditNumber(promptAudit.optimizedEstimatedTokens)}\``,
        `- \uAC10\uC18C\uD55C \uC608\uC0C1 \uD1A0\uD070: \`${formatAuditNumber(promptAudit.reducedEstimatedTokens)}\``,
        `- \uC608\uC0C1 \uD1A0\uD070 \uAC10\uC18C \uBE44\uC728: \`${promptAudit.tokenReductionPercent}%\``
      ].join("\n")
    },
    {
      heading: "\uD504\uB86C\uD504\uD2B8 \uCD5C\uC801\uD654 \uC804",
      markdown: formatCodeBlock(promptAudit.originalPrompt)
    },
    {
      heading: "\uD504\uB86C\uD504\uD2B8 \uCD5C\uC801\uD654 \uD6C4",
      markdown: formatCodeBlock(promptAudit.optimizedPrompt)
    }
  ];
}
var ANSI = {
  bold: "\x1B[1m",
  cyan: "\x1B[36m",
  dim: "\x1B[2m",
  red: "\x1B[31m",
  reset: "\x1B[0m"};
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 getTerminalColumns() {
  return Math.max(process.stdout.columns || 100, 4);
}
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("", 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
  };
}

// 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) {
    readline3__default.default.moveCursor(process.stdout, 0, -(previousState.totalLines - 1));
  }
  readline3__default.default.cursorTo(process.stdout, 0);
  readline3__default.default.clearScreenDown(process.stdout);
}
function renderStatusLayout(layout, previousState) {
  clearRenderedStatus(previousState);
  process.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.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.stdout.write("\n");
        return result;
      } catch (error) {
        clearInterval(timer);
        renderState = renderStatusLayout(
          buildStatusRenderLayout(`${prefix} fail`, `${message} (${formatElapsed(startedAt)})`),
          renderState
        );
        process.stdout.write("\n");
        throw error;
      }
    }
  };
}
globalThis.__JU_HONG_E_POSTHOG_RUNTIME_STATE__ ?? (globalThis.__JU_HONG_E_POSTHOG_RUNTIME_STATE__ = {});

// src/features/show-stream/application/action.ts
function parseStreamOutputCommandMode(rawArg) {
  const normalized = rawArg?.trim().toLowerCase();
  if (!normalized) {
    return "toggle";
  }
  if (["on", "enable", "enabled", "true", "1", "\uCF1C\uAE30", "\uCF1C\uC9D0"].includes(normalized)) {
    return "enable";
  }
  if (["off", "disable", "disabled", "false", "0", "\uB044\uAE30", "\uAEBC\uC9D0"].includes(normalized)) {
    return "disable";
  }
  if (["status", "state", "\uC0C1\uD0DC", "\uD655\uC778"].includes(normalized)) {
    return "status";
  }
  if (["toggle", "switch", "\uC804\uD658"].includes(normalized)) {
    return "toggle";
  }
  return void 0;
}
function formatStreamOutputStateLabel(enabled) {
  return enabled ? "\uCF1C\uC9D0" : "\uAEBC\uC9D0";
}
function formatShowStreamOutput(previousEnabled, nextEnabled, requestedMode) {
  const unchanged = previousEnabled === nextEnabled;
  return [
    requestedMode === "status" ? "AI \uC2E4\uC2DC\uAC04 \uC751\uB2F5 \uCD9C\uB825 \uC0C1\uD0DC\uB97C \uD655\uC778\uD588\uC2B5\uB2C8\uB2E4." : unchanged ? "AI \uC2E4\uC2DC\uAC04 \uC751\uB2F5 \uCD9C\uB825 \uC0C1\uD0DC\uB97C \uC720\uC9C0\uD588\uC2B5\uB2C8\uB2E4." : "AI \uC2E4\uC2DC\uAC04 \uC751\uB2F5 \uCD9C\uB825 \uC0C1\uD0DC\uB97C \uBCC0\uACBD\uD588\uC2B5\uB2C8\uB2E4.",
    `\uC774\uC804 \uC0C1\uD0DC: ${formatStreamOutputStateLabel(previousEnabled)}`,
    `\uD604\uC7AC \uC0C1\uD0DC: ${formatStreamOutputStateLabel(nextEnabled)}`,
    "",
    "- Codex: show-stream ON\uC77C \uB54C `codex exec --json` \uC774\uBCA4\uD2B8\uB97C \uB2E8\uACC4/\uBA85\uB839/\uCD5C\uC885 \uB2F5\uBCC0 \uC911\uC2EC\uC758 \uC77D\uAE30 \uC26C\uC6B4 \uBA54\uC2DC\uC9C0\uB85C \uCD9C\uB825\uD569\uB2C8\uB2E4.",
    "- Gemini: show-stream ON\uC77C \uB54C `--output-format stream-json` \uC774\uBCA4\uD2B8\uB97C \uB3C4\uAD6C/\uC751\uB2F5 \uC911\uC2EC\uC758 \uC77D\uAE30 \uC26C\uC6B4 \uBA54\uC2DC\uC9C0\uB85C \uCD9C\uB825\uD569\uB2C8\uB2E4.",
    "- Claude: show-stream ON\uC77C \uB54C `stream-json` \uC774\uBCA4\uD2B8\uB97C \uB3C4\uAD6C/\uBD80\uBD84 \uC751\uB2F5 \uC911\uC2EC\uC758 \uC77D\uAE30 \uC26C\uC6B4 \uBA54\uC2DC\uC9C0\uB85C \uCD9C\uB825\uD569\uB2C8\uB2E4.",
    "- \uC801\uC6A9 \uBC94\uC704: \uD604\uC7AC \uC791\uC5C5 \uB514\uB809\uD130\uB9AC\uC758 `.ju-hong-e/show-stream.json`"
  ].join("\n");
}
async function runShowStreamAction(options) {
  let stage = "parse-mode";
  options.trace("show-stream:action:start", `service=${options.service}`);
  try {
    const requestedMode = parseStreamOutputCommandMode(options.args[0]);
    if (options.args[0] && !requestedMode) {
      throw new Error("\uC9C0\uC6D0\uD558\uC9C0 \uC54A\uB294 \uC635\uC158\uC785\uB2C8\uB2E4. `/show-stream [on|off|status]` \uD615\uD0DC\uB85C \uC785\uB825\uD558\uC138\uC694.");
    }
    const status = createSessionActionStatus("show-stream");
    status.step("1/4 \uD604\uC7AC \uC2E4\uC2DC\uAC04 \uCD9C\uB825 \uC124\uC815\uC744 \uC77D\uB294 \uC911\uC785\uB2C8\uB2E4.");
    const context = captureActionContext(options.paths);
    const previousEnabled = hydrateStreamOutputState(options.paths);
    const nextEnabled = requestedMode === "status" ? previousEnabled : requestedMode === "enable" ? true : requestedMode === "disable" ? false : !previousEnabled;
    options.trace("show-stream:resolved", `${requestedMode || "toggle"} ${previousEnabled} -> ${nextEnabled}`);
    status.step("2/4 \uC694\uCCAD\uD55C \uC2E4\uC2DC\uAC04 \uCD9C\uB825 \uC124\uC815\uC744 \uBC18\uC601\uD558\uB294 \uC911\uC785\uB2C8\uB2E4.");
    stage = "save-config";
    if (requestedMode !== "status") {
      saveStreamOutputConfig(options.paths, nextEnabled);
      options.trace("show-stream:config:saved", options.paths.streamOutputConfigPath);
    }
    const output = formatShowStreamOutput(previousEnabled, nextEnabled, requestedMode || "toggle");
    status.step("3/4 \uBCC0\uACBD \uACB0\uACFC\uC640 \uC6CC\uD06C\uC2A4\uD398\uC774\uC2A4 \uC0C1\uD0DC\uB97C \uC815\uB9AC\uD558\uB294 \uC911\uC785\uB2C8\uB2E4.");
    status.step("4/4 \uC791\uC5C5 \uC774\uB825\uC744 \uC800\uC7A5\uD558\uB294 \uC911\uC785\uB2C8\uB2E4.");
    const input = `/show-stream ${options.args.join(" ")}`.trim();
    const summary = requestedMode === "status" ? `\uC2E4\uC2DC\uAC04 \uCD9C\uB825 \uC0C1\uD0DC \uD655\uC778: ${formatStreamOutputStateLabel(nextEnabled)}` : `\uC2E4\uC2DC\uAC04 \uCD9C\uB825 ${previousEnabled === nextEnabled ? "\uC720\uC9C0" : "\uBCC0\uACBD"}: ${formatStreamOutputStateLabel(nextEnabled)}`;
    console.log(output);
    stage = "finalize-record";
    const record = finalizeAction(options.paths, context, {
      extraSections: [
        {
          heading: "\uC2E4\uC2DC\uAC04 \uCD9C\uB825 \uC124\uC815 \uBCC0\uACBD",
          markdown: [
            `- configPath: \`${options.paths.streamOutputConfigPath}\``,
            `- requestedMode: \`${requestedMode || "toggle"}\``,
            `- previousEnabled: \`${previousEnabled}\``,
            `- nextEnabled: \`${nextEnabled}\``
          ].join("\n")
        }
      ],
      input,
      output,
      previewCommand: "",
      scope: "show-stream",
      service: options.service,
      skipped: options.parsedArgs.testMode,
      summary,
      title: "\uC2E4\uC2DC\uAC04 \uCD9C\uB825 \uC124\uC815"
    });
    options.trace("show-stream:action:end", `history=${record.historyPath || "(\uC5C6\uC74C)"} mode=${requestedMode || "toggle"}`);
    return record;
  } catch (error) {
    if (isUserTerminatedError(error)) {
      options.trace("show-stream:action:terminated", stage);
    } else if (isUserCancelledError(error)) {
      options.trace("show-stream:action:cancelled", stage);
    } else {
      options.trace("show-stream:action:error", `${stage} ${getErrorSummary(error)}`);
    }
    throw error;
  }
}

// src/platform/runtime-profile.ts
globalThis.__JU_HONG_E_RUNTIME_PROFILE__ ?? (globalThis.__JU_HONG_E_RUNTIME_PROFILE__ = {
  binaryName: "ju-hong-e",
  profile: "all"
});

// src/platform/command-runtime/registry.ts
var registryState = globalThis.__JU_HONG_E_COMMAND_REGISTRY__ ?? (globalThis.__JU_HONG_E_COMMAND_REGISTRY__ = {
  juHongECommands: /* @__PURE__ */ new Map()
});
var JU_HONG_E_COMMANDS = registryState.juHongECommands;
function resolveRegistration(registration, api) {
  if (typeof registration === "function") {
    return registration(api);
  }
  return registration;
}
function createCommand(definition) {
  return {
    ...definition,
    forms: definition.forms ? definition.forms.map(clonePromptMarkdownAsset) : void 0,
    instructions: definition.instructions ? definition.instructions.map(clonePromptMarkdownAsset) : void 0,
    kind: "ju-hong-e",
    rules: definition.rules ? definition.rules.map(
      (ruleAsset) => !isPromptRuleGroupAsset(ruleAsset) ? clonePromptMarkdownAsset(ruleAsset) : {
        ...ruleAsset,
        fileNamePatterns: ruleAsset.fileNamePatterns ? [...ruleAsset.fileNamePatterns] : void 0,
        rules: ruleAsset.rules ? ruleAsset.rules.map(clonePromptMarkdownAsset) : void 0
      }
    ) : void 0
  };
}
var REGISTRATION_API = {
  createCommand
};
function addCommand(registration) {
  ensureDefaultSecurityRules();
  const definition = resolveRegistration(registration, REGISTRATION_API);
  if (JU_HONG_E_COMMANDS.has(definition.command)) {
    throw new Error(`\uC774\uBBF8 \uB4F1\uB85D\uB41C \uC8FC\uD64D\uC774 \uBA85\uB839\uC5B4\uC785\uB2C8\uB2E4. command=${definition.command}`);
  }
  JU_HONG_E_COMMANDS.set(definition.command, definition);
}

// src/command-modules/show-stream/index.ts
addCommand(
  ({ createCommand: createCommand2 }) => createCommand2({
    command: "/show-stream",
    description: "AI \uC2E4\uC2DC\uAC04 \uC751\uB2F5 \uCD9C\uB825 on/off/status \uC804\uD658",
    /**
     * @description
     * `execute` 는 대상 값를 실행한다.
     * 사용자가 해당 builtin 명령을 선택했을 때 가장 먼저 호출되는 실행 엔트리다.
     *
     * @param context 현재 명령 또는 action 실행 컨텍스트
     * @returns execute 비동기 처리 결과
     */
    execute: async (context) => {
      const record = await runShowStreamAction({
        args: context.args,
        parsedArgs: context.parsedArgs,
        paths: context.paths,
        service: context.service,
        trace: context.trace
      });
      return {
        record,
        shouldPrintBanner: true
      };
    },
    order: 26
  })
);
