import fs2 from 'node:fs';
import path from 'node:path';
import { stdout } from 'node:process';
import 'posthog-node';
import readline from 'node:readline';
import { execFile } from 'node:child_process';
import { promisify } from 'node:util';

// src/platform/core/history-helpers.ts

// src/platform/core/git-helpers.ts
function formatCodeBlock(content, language = "") {
  return `\`\`\`${language}
${content || "(\uC5C6\uC74C)"}
\`\`\``;
}

// src/platform/core/string-helpers.ts
function safeExcerpt(content, limit = 3e3) {
  if (!content) {
    return "";
  }
  if (content.length <= limit) {
    return content;
  }
  return `${content.slice(0, limit)}
... (truncated ${content.length - limit} chars)`;
}

// 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()
  };
  fs2.appendFileSync(paths.conversationHistoryPath, `${JSON.stringify(normalizedEntry)}
`, "utf8");
  return normalizedEntry;
}
function loadConversationHistory(paths, limit = DEFAULT_HISTORY_LIMIT) {
  if (!fs2.existsSync(paths.conversationHistoryPath)) {
    return [];
  }
  const lines = fs2.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);
}
function saveService(paths, service) {
  fs2.writeFileSync(paths.serviceFilePath, `${service}
`, "utf8");
}

// src/platform/types/app.ts
var AI_SERVICE = {
  CLAUDE: "claude",
  CODEX: "codex",
  GEMINI: "gemini"
};
function getAvailableFilePath(directory, baseName, extension) {
  const first = path.join(directory, `${baseName}${extension}`);
  if (!fs2.existsSync(first)) {
    return first;
  }
  let next = first;
  let count = 1;
  while (fs2.existsSync(next)) {
    next = path.join(directory, `${baseName}-${count}${extension}`);
    if (!fs2.existsSync(next)) {
      break;
    }
    count += 1;
  }
  return next;
}
function appendHistoryIndex(paths, summary, relativeFilePath) {
  const line = `- ${getHumanReadableNow()} | ${summary} | file: \`${relativeFilePath}\`
`;
  fs2.appendFileSync(paths.historyIndexPath, line, "utf8");
}
function writeServiceChangeHistory(paths, previousService, nextService, historyContext) {
  const baseName = `${getFileTimestamp()}-service-change`;
  const filePath = getAvailableFilePath(paths.servicesDir, baseName, ".md");
  const markdown = `# Service Change

- \uC2DC\uAC01: ${getHumanReadableNow()}
- \uC774\uC804 \uC11C\uBE44\uC2A4: \`${previousService || "(\uC5C6\uC74C)"}\`
- \uB2E4\uC74C \uC11C\uBE44\uC2A4: \`${nextService}\`

## \uC8FC\uC785 \uC608\uC815 \uD788\uC2A4\uD1A0\uB9AC

${formatCodeBlock(historyContext)}
`;
  fs2.writeFileSync(filePath, markdown, "utf8");
  appendHistoryIndex(paths, `service-change | ${previousService || "(\uC5C6\uC74C)"} -> ${nextService}`, path.relative(paths.rootDir, filePath));
  return filePath;
}

// src/platform/core/helpers.ts
var AI_SERVICES = Object.values(AI_SERVICE);
setAiServicesRef(AI_SERVICES);
var ANSI = {
  bold: "\x1B[1m",
  gray: "\x1B[90m",
  green: "\x1B[32m",
  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 = stdout.columns || 100;
  return Math.max(Math.min(columns - 2, 108), 4);
}
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"));
}
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);
}
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.emitKeypressEvents(stdin);
    if (stdin.isTTY) {
      stdin.setRawMode(true);
    }
    stdin.resume();
    stdin.on("keypress", onKeyPress);
    render();
  });
}

// src/platform/app/service-selection.ts
var SERVICE_DISPLAY_NAMES = {
  [AI_SERVICE.CODEX]: "OpenAI Codex CLI",
  [AI_SERVICE.GEMINI]: "Google Gemini CLI",
  [AI_SERVICE.CLAUDE]: "Anthropic Claude CLI"
};
async function chooseService(title) {
  return selectSingleOption(
    title,
    AI_SERVICES.map((service) => ({
      description: SERVICE_DISPLAY_NAMES[service],
      label: service,
      value: service
    }))
  );
}
async function changeService(currentService, paths, parsedArgs, trace) {
  const nextService = await chooseService(`\uD604\uC7AC \uC11C\uBE44\uC2A4\uB294 ${currentService} \uC785\uB2C8\uB2E4. \uBCC0\uACBD\uD560 \uC11C\uBE44\uC2A4\uB97C \uC120\uD0DD\uD558\uC138\uC694.`);
  trace("service-change:selected", `${currentService} -> ${nextService}`);
  saveService(paths, nextService);
  const historyContext = loadRecentHistoryContext(paths);
  const historyPath = writeServiceChangeHistory(paths, currentService, nextService, historyContext);
  const summary = currentService === nextService ? `\uC11C\uBE44\uC2A4 \uC720\uC9C0: ${nextService}` : `\uC11C\uBE44\uC2A4 \uBCC0\uACBD: ${currentService} -> ${nextService}`;
  appendConversationHistory(paths, {
    nextService,
    previousService: currentService,
    scope: "service-change",
    service: nextService,
    summary,
    title: "\uC11C\uBE44\uC2A4 \uBCC0\uACBD"
  });
  console.log(summary);
  return {
    nextService,
    record: {
      historyPath,
      scope: "service-change",
      service: nextService,
      skipped: parsedArgs.testMode,
      summary,
      title: "\uC11C\uBE44\uC2A4 \uBCC0\uACBD",
      traceMessages: []
    }
  };
}

// src/platform/runtime-profile.ts
globalThis.__JU_HONG_E_RUNTIME_PROFILE__ ?? (globalThis.__JU_HONG_E_RUNTIME_PROFILE__ = {
  binaryName: "ju-hong-e",
  profile: "all"
});
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.normalize(asset.filePath)
  } : asset;
}
promisify(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/
  });
}

// 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/change-service/index.ts
addCommand(
  ({ createCommand: createCommand2 }) => createCommand2({
    command: "/change-service",
    description: "\uD604\uC7AC AI \uC11C\uBE44\uC2A4\uB97C \uBCC0\uACBD",
    /**
     * @description
     * `execute` 는 대상 값를 실행한다.
     * 사용자가 해당 builtin 명령을 선택했을 때 가장 먼저 호출되는 실행 엔트리다.
     *
     * @param context 현재 명령 또는 action 실행 컨텍스트
     * @returns execute 비동기 처리 결과
     */
    execute: async (context) => {
      const result = await changeService(context.service, context.paths, context.parsedArgs, context.trace);
      return {
        nextService: result.nextService,
        record: result.record,
        shouldPrintBanner: true
      };
    },
    order: 20
  })
);
