'use strict';

var fs = require('fs');
var child_process = require('child_process');
var util = require('util');
var path5 = require('path');
require('fs/promises');
require('os');
var url = require('url');
require('readline');
var module$1 = require('module');
require('process');
require('posthog-node');
require('http');
require('net');
require('crypto');

var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

var fs__default = /*#__PURE__*/_interopDefault(fs);
var path5__default = /*#__PURE__*/_interopDefault(path5);

var __getOwnPropNames = Object.getOwnPropertyNames;
var __esm = (fn, res) => function __init() {
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
};
function isTokenOptimizerEnabled(paths) {
  return tokenOptimizerRuntimeState.enabled;
}
var DEFAULT_TOKEN_OPTIMIZER_STATE, tokenOptimizerRuntimeState;
var init_config = __esm({
  "src/features/token-optimizer/infrastructure/config.ts"() {
    DEFAULT_TOKEN_OPTIMIZER_STATE = {
      enabled: false
    };
    tokenOptimizerRuntimeState = globalThis.__JU_HONG_E_TOKEN_OPTIMIZER_STATE__ ?? (globalThis.__JU_HONG_E_TOKEN_OPTIMIZER_STATE__ = {
      ...DEFAULT_TOKEN_OPTIMIZER_STATE
    });
  }
});

// src/platform/core/cancellation.ts
var init_cancellation = __esm({
  "src/platform/core/cancellation.ts"() {
  }
});
var init_git_helpers = __esm({
  "src/platform/core/git-helpers.ts"() {
  }
});
function shellQuote(value) {
  return `'${value.replace(/'/g, `'\\''`)}'`;
}
function safeExcerpt(content, limit = 3e3) {
  if (!content) {
    return "";
  }
  if (content.length <= limit) {
    return content;
  }
  return `${content.slice(0, limit)}
... (truncated ${content.length - limit} chars)`;
}
var init_string_helpers = __esm({
  "src/platform/core/string-helpers.ts"() {
  }
});

// src/platform/core/timestamp-helpers.ts
var init_timestamp_helpers = __esm({
  "src/platform/core/timestamp-helpers.ts"() {
  }
});
var init_history_helpers = __esm({
  "src/platform/core/history-helpers.ts"() {
    init_git_helpers();
    init_string_helpers();
    init_timestamp_helpers();
  }
});

// src/platform/types/app.ts
var AI_SERVICE;
var init_app = __esm({
  "src/platform/types/app.ts"() {
    AI_SERVICE = {
      CLAUDE: "claude",
      CODEX: "codex",
      GEMINI: "gemini"
    };
  }
});

// src/platform/types/index.ts
var init_types = __esm({
  "src/platform/types/index.ts"() {
    init_app();
  }
});

// src/platform/core/types.ts
var init_types2 = __esm({
  "src/platform/core/types.ts"() {
    init_types();
  }
});

// src/platform/core/figma-helpers.ts
var init_figma_helpers = __esm({
  "src/platform/core/figma-helpers.ts"() {
  }
});
var init_report_helpers = __esm({
  "src/platform/core/report-helpers.ts"() {
    init_git_helpers();
    init_string_helpers();
    init_timestamp_helpers();
  }
});
var init_helpers = __esm({
  "src/platform/core/helpers.ts"() {
    init_history_helpers();
    init_types2();
    init_string_helpers();
    init_figma_helpers();
    init_git_helpers();
    init_history_helpers();
    init_report_helpers();
    init_timestamp_helpers();
    Object.values(AI_SERVICE);
  }
});

// src/features/security-policy/domain/policy.ts
var init_policy = __esm({
  "src/features/security-policy/domain/policy.ts"() {
  }
});
var init_config2 = __esm({
  "src/features/security-policy/infrastructure/config.ts"() {
    init_policy();
  }
});
var init_resource_resolver = __esm({
  "src/platform/request-security/resource-resolver.ts"() {
    util.promisify(child_process.execFile);
  }
});

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

// src/platform/request-security/default-rules.ts
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/
  });
}
var initialized;
var init_default_rules = __esm({
  "src/platform/request-security/default-rules.ts"() {
    init_registry();
    initialized = false;
  }
});

// src/platform/request-security/guard.ts
var init_guard = __esm({
  "src/platform/request-security/guard.ts"() {
    init_policy();
    init_config2();
    init_helpers();
    init_default_rules();
    init_registry();
  }
});

// src/platform/token-optimizer/strip-ansi.ts
var ANSI_REGEX, stripAnsi;
var init_strip_ansi = __esm({
  "src/platform/token-optimizer/strip-ansi.ts"() {
    ANSI_REGEX = new RegExp(
      String.raw`\u001B\[[0-9;]*[a-zA-Z]|\u001B\].*?(?:\u0007|\u001B\\)`,
      "g"
    );
    stripAnsi = (text) => {
      return text.replace(ANSI_REGEX, "");
    };
  }
});

// src/platform/token-optimizer/token-counter.ts
var countTokens;
var init_token_counter = __esm({
  "src/platform/token-optimizer/token-counter.ts"() {
    countTokens = (text) => {
      if (!text) {
        return 0;
      }
      return text.split(/\s+/).filter(Boolean).length;
    };
  }
});

// src/platform/token-optimizer/truncate.ts
var truncateText, truncateLines;
var init_truncate = __esm({
  "src/platform/token-optimizer/truncate.ts"() {
    truncateText = (text, maxLength) => {
      const charCount = [...text].length;
      if (charCount <= maxLength) {
        return text;
      }
      if (maxLength < 3) {
        return "...";
      }
      return [...text].slice(0, maxLength - 3).join("") + "...";
    };
    truncateLines = (text, options) => {
      const { maxCharsPerLine, headLines, tailLines, maxLines } = options;
      let lines = text.split("\n");
      if (headLines !== void 0 && tailLines !== void 0 && lines.length > headLines + tailLines) {
        const head = lines.slice(0, headLines);
        const tail = lines.slice(-tailLines);
        const omittedCount = lines.length - headLines - tailLines;
        lines = [...head, `... (${omittedCount}\uC904 \uC0DD\uB7B5)`, ...tail];
      } else if (headLines !== void 0 && lines.length > headLines) {
        const omittedCount = lines.length - headLines;
        lines = [...lines.slice(0, headLines), `... (${omittedCount}\uC904 \uC0DD\uB7B5)`];
      } else if (tailLines !== void 0 && lines.length > tailLines) {
        const omittedCount = lines.length - tailLines;
        lines = [`... (${omittedCount}\uC904 \uC0DD\uB7B5)`, ...lines.slice(-tailLines)];
      }
      if (maxCharsPerLine !== void 0) {
        lines = lines.map((line) => truncateText(line, maxCharsPerLine));
      }
      if (maxLines !== void 0 && lines.length > maxLines) {
        if (maxLines <= 0) {
          return "";
        }
        const preservedLineCount = Math.max(maxLines - 1, 0);
        const omittedCount = lines.length - preservedLineCount;
        lines = preservedLineCount === 0 ? [`... (${omittedCount}\uC904 \uC0DD\uB7B5)`] : [...lines.slice(0, preservedLineCount), `... (${omittedCount}\uC904 \uC0DD\uB7B5)`];
      }
      return lines.join("\n");
    };
  }
});

// src/platform/token-optimizer/line-filter.ts
function matchesLine(pattern, line) {
  const safePattern = pattern.global || pattern.sticky ? new RegExp(pattern.source, pattern.flags) : pattern;
  safePattern.lastIndex = 0;
  return safePattern.test(line);
}
var filterLines;
var init_line_filter = __esm({
  "src/platform/token-optimizer/line-filter.ts"() {
    filterLines = (text, options) => {
      const { keepPatterns, stripPatterns, stripEmptyLines } = options;
      let lines = text.split("\n");
      if (keepPatterns && keepPatterns.length > 0) {
        lines = lines.filter((line) => keepPatterns.some((pattern) => matchesLine(pattern, line)));
      }
      if (stripPatterns && stripPatterns.length > 0) {
        lines = lines.filter((line) => !stripPatterns.some((pattern) => matchesLine(pattern, line)));
      }
      if (stripEmptyLines) {
        lines = lines.filter((line) => line.trim().length > 0);
      }
      return lines.join("\n");
    };
  }
});

// src/platform/token-optimizer/deduplication.ts
var NORMALIZATION_RULES, normalizeLine, deduplicateLines;
var init_deduplication = __esm({
  "src/platform/token-optimizer/deduplication.ts"() {
    NORMALIZATION_RULES = [
      // ISO 타임스탬프 (2026-04-09T10:00:01.123 또는 2026-04-09 10:00:01)
      [/\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}[.\d]*/g, "<TIMESTAMP>"],
      // 대괄호 타임스탬프 ([10:00:01], [2026-04-09 10:00:01])
      [/\[\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}[.\d]*\]/g, "[<TIMESTAMP>]"],
      // UUID
      [/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi, "<UUID>"],
      // IP 주소
      [/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/g, "<IP>"],
      // 16진수 해시 (7자 이상)
      [/\b[0-9a-f]{7,}\b/gi, "<HEX>"],
      // 큰 숫자 (4자리 이상)
      [/\b\d{4,}\b/g, "<NUM>"]
    ];
    normalizeLine = (line) => {
      let normalized = line;
      for (const [pattern, replacement] of NORMALIZATION_RULES) {
        normalized = normalized.replace(pattern, replacement);
      }
      return normalized;
    };
    deduplicateLines = (text) => {
      const lines = text.split("\n");
      const groups = /* @__PURE__ */ new Map();
      const orderedKeys = [];
      for (const line of lines) {
        if (line.trim().length === 0) {
          const emptyKey = `__EMPTY_${orderedKeys.length}__`;
          groups.set(emptyKey, { count: 1, originalLine: line });
          orderedKeys.push(emptyKey);
          continue;
        }
        const normalized = normalizeLine(line);
        if (groups.has(normalized)) {
          groups.get(normalized).count += 1;
        } else {
          groups.set(normalized, { count: 1, originalLine: line });
          orderedKeys.push(normalized);
        }
      }
      return orderedKeys.map((key) => {
        const group = groups.get(key);
        if (group.count > 1) {
          return `[x${group.count}] ${normalizeLine(group.originalLine)}`;
        }
        return group.originalLine;
      }).join("\n");
    };
  }
});

// src/platform/token-optimizer/optimize.ts
var optimizeText;
var init_optimize = __esm({
  "src/platform/token-optimizer/optimize.ts"() {
    init_deduplication();
    init_line_filter();
    init_strip_ansi();
    init_token_counter();
    init_truncate();
    optimizeText = (text, options = {}) => {
      const originalTokens = countTokens(text);
      if (!text) {
        return { text: "", originalTokens: 0, optimizedTokens: 0, savingsPercent: 0 };
      }
      const {
        stripAnsi: shouldStripAnsi = true,
        maxCharsPerLine,
        maxLines,
        headLines,
        tailLines,
        deduplicate = false,
        keepPatterns,
        stripPatterns,
        stripEmptyLines = true
      } = options;
      let result = shouldStripAnsi ? stripAnsi(text) : text;
      const hasFilterOptions = keepPatterns && keepPatterns.length > 0 || stripPatterns && stripPatterns.length > 0 || stripEmptyLines;
      if (hasFilterOptions) {
        result = filterLines(result, { keepPatterns, stripPatterns, stripEmptyLines });
      }
      if (deduplicate) {
        result = deduplicateLines(result);
      }
      const hasTruncateOptions = maxCharsPerLine !== void 0 || maxLines !== void 0 || headLines !== void 0 || tailLines !== void 0;
      if (hasTruncateOptions) {
        result = truncateLines(result, { maxCharsPerLine, maxLines, headLines, tailLines });
      }
      const optimizedTokens = countTokens(result);
      const savingsPercent = originalTokens > 0 ? Math.round((1 - optimizedTokens / originalTokens) * 1e3) / 10 : 0;
      return {
        text: result,
        originalTokens,
        optimizedTokens,
        savingsPercent
      };
    };
  }
});

// src/platform/token-optimizer/index.ts
var init_token_optimizer = __esm({
  "src/platform/token-optimizer/index.ts"() {
    init_strip_ansi();
    init_token_counter();
    init_truncate();
    init_line_filter();
    init_deduplication();
    init_optimize();
  }
});
function createPromptHistoryReferenceSection(historyReferences) {
  if (!historyReferences) {
    return void 0;
  }
  return {
    heading: "\uD788\uC2A4\uD1A0\uB9AC \uCC38\uC870",
    markdown: [
      "- \uD604\uC7AC \uC694\uCCAD\uC774 \uC774\uC804 \uC791\uC5C5\uC758 \uC5F0\uC7A5, \uC218\uC815, \uD6C4\uC18D \uC9C8\uBB38, \uC0DD\uB7B5\uB41C \uB9E5\uB77D \uBCF5\uC6D0\uCC98\uB7FC \uBCF4\uC774\uBA74 \uC0AC\uC6A9\uC790\uAC00 \uBA85\uC2DC\uD558\uC9C0 \uC54A\uC544\uB3C4 \uBA3C\uC800 \uC544\uB798 \uD788\uC2A4\uD1A0\uB9AC\uB97C \uD655\uC778\uD55C\uB2E4.",
      '- \uC0AC\uC6A9\uC790\uAC00 "\uC774\uC804", "\uBC29\uAE08", "\uC544\uAE4C", "\uACC4\uC18D", "\uADF8\uAC70", "\uADF8 \uBC29\uC2DD", "\uAC19\uC740 \uAE30\uC900"\uCC98\uB7FC \uAE30\uC874 \uB9E5\uB77D\uC744 \uC554\uC2DC\uD558\uBA74 \uC6B0\uC120\uC801\uC73C\uB85C \uD788\uC2A4\uD1A0\uB9AC\uB97C \uC870\uD68C\uD55C\uB2E4.',
      "- \uC694\uCCAD\uB9CC\uC73C\uB85C\uB294 \uC548\uC804\uD55C \uAD6C\uD604 \uACB0\uC815\uC744 \uB0B4\uB9AC\uAE30 \uC5B4\uB835\uAC70\uB098, \uAE30\uC874 \uACB0\uC815/\uC0B0\uCD9C\uBB3C/\uC2E4\uD328 \uC6D0\uC778\uC744 \uC7AC\uC0AC\uC6A9\uD574\uC57C \uD558\uBA74 \uB0B4\uBD80 \uD310\uB2E8\uC73C\uB85C \uD788\uC2A4\uD1A0\uB9AC\uB97C \uBA3C\uC800 \uD655\uC778\uD55C\uB2E4.",
      "- AI\uC758 \uC804\uCCB4 \uD788\uC2A4\uD1A0\uB9AC\uB97C \uC870\uD68C/\uCC38\uC870\uD574\uC57C \uD558\uB294 \uACBD\uC6B0 \uC544\uB798 \uB514\uB809\uD130\uB9AC\uB97C \uC9C1\uC811 \uD655\uC778\uD55C\uB2E4.",
      `- \uC804\uCCB4 AI \uD788\uC2A4\uD1A0\uB9AC \uB514\uB809\uD130\uB9AC: \`${path5__default.default.normalize(historyReferences.aiHistoryDirectoryPath)}\``,
      "- \uC0AC\uC6A9\uC790\uAC00 \uC791\uC131\uD55C \uD504\uB86C\uD504\uD2B8 \uB0B4\uC5ED\uB9CC \uD544\uC694\uD55C \uACBD\uC6B0 \uC544\uB798 \uD30C\uC77C\uC744 \uC9C1\uC811 \uD655\uC778\uD55C\uB2E4.",
      `- \uC0AC\uC6A9\uC790 \uD504\uB86C\uD504\uD2B8 \uD788\uC2A4\uD1A0\uB9AC \uD30C\uC77C: \`${path5__default.default.normalize(historyReferences.promptHistoryFilePath)}\``,
      "- \uD504\uB86C\uD504\uD2B8 \uBCF8\uBB38\uC5D0\uB294 \uACFC\uAC70 \uD788\uC2A4\uD1A0\uB9AC \uB0B4\uC6A9\uC744 \uC9C1\uC811 \uB2E4\uC2DC \uC2E3\uC9C0 \uB9D0\uACE0, \uD544\uC694\uD560 \uB54C \uC704 \uACBD\uB85C\uB97C \uCC38\uC870\uD574 \uBB38\uB9E5\uC744 \uBCF5\uC6D0\uD55C \uB4A4 \uC791\uC5C5\uD55C\uB2E4."
    ].join("\n")
  };
}
var init_history_reference = __esm({
  "src/platform/prompts/history-reference.ts"() {
  }
});
function findPackageRoot(moduleFilePath) {
  let currentDirectoryPath = path5__default.default.dirname(moduleFilePath);
  while (!fs__default.default.existsSync(path5__default.default.join(currentDirectoryPath, PACKAGE_JSON_FILE_NAME))) {
    const parentDirectoryPath = path5__default.default.dirname(currentDirectoryPath);
    if (parentDirectoryPath === currentDirectoryPath) {
      throw new Error(`markdown \uC790\uC0B0 package root\uB97C \uCC3E\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4. start=${moduleFilePath}`);
    }
    currentDirectoryPath = parentDirectoryPath;
  }
  return currentDirectoryPath;
}
function resolvePromptPackageFilePath(importMetaUrl, packageRelativeFilePath) {
  const moduleFilePath = url.fileURLToPath(importMetaUrl);
  const packageRoot = findPackageRoot(moduleFilePath);
  return path5__default.default.normalize(path5__default.default.resolve(packageRoot, packageRelativeFilePath));
}
function createPromptMarkdownFileAsset(importMetaUrl, packageRelativeFilePath) {
  return {
    filePath: resolvePromptPackageFilePath(importMetaUrl, packageRelativeFilePath),
    kind: "file-reference"
  };
}
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: path5__default.default.normalize(asset.filePath)
  } : asset;
}
var PACKAGE_JSON_FILE_NAME;
var init_markdown_assets = __esm({
  "src/platform/prompts/markdown-assets.ts"() {
    PACKAGE_JSON_FILE_NAME = "package.json";
  }
});

// src/platform/prompts/render.ts
function normalizeMarkdown(markdown) {
  return markdown.trim();
}
function renderMarkdownAssetBlocks(markdownAssets) {
  const assets = markdownAssets || [];
  const inlineMarkdownBlocks = assets.filter((asset) => typeof asset === "string").map(normalizeMarkdown).filter(Boolean);
  const fileReferenceBlocks = assets.filter(isPromptMarkdownFileReference).map((asset) => `- \`${asset.filePath.trim()}\``);
  const blocks = [
    inlineMarkdownBlocks.length > 0 ? inlineMarkdownBlocks.join("\n\n") : "",
    fileReferenceBlocks.length > 0 ? fileReferenceBlocks.join("\n") : ""
  ].filter(Boolean);
  if (blocks.length === 0) {
    return "";
  }
  return blocks.join("\n\n");
}
function renderLabeledSection(section) {
  const markdown = normalizeMarkdown(section.markdown);
  if (!markdown) {
    return "";
  }
  return [`[${section.heading}]`, markdown].join("\n");
}
function buildExecutionOptionsSection(prompt) {
  return {
    heading: "\uC2E4\uD589 \uC635\uC158",
    markdown: [
      `- autoYes: ${prompt.autoYes ? "yes" : "no"}`,
      prompt.autoYes ? "- \uAD8C\uD55C \uC694\uCCAD\uC740 \uBCC4\uB3C4 \uD655\uC778 \uC5C6\uC774 yes \uB85C \uCC98\uB9AC\uD55C\uB2E4." : "- \uAD8C\uD55C \uC694\uCCAD\uC740 \uC11C\uBE44\uC2A4 \uAE30\uBCF8 \uC2B9\uC778 \uC815\uCC45\uC744 \uB530\uB978\uB2E4."
    ].join("\n")
  };
}
function limitLines(lines, maxLines) {
  if (lines.length <= maxLines) {
    return lines;
  }
  return [...lines.slice(0, maxLines), `... (${lines.length - maxLines}\uC904 \uC0DD\uB7B5)`];
}
function renderWorkspaceSnapshotMarkdown(prompt) {
  return prompt.workspaceSnapshot.available ? [
    `Git Root: ${prompt.workspaceSnapshot.gitRoot}`,
    `Branch: ${prompt.workspaceSnapshot.branch || "(detached)"}`,
    "",
    "[git status --short]",
    prompt.workspaceSnapshot.statusLines.join("\n") || "(\uC5C6\uC74C)",
    "",
    "[git diff --stat]",
    prompt.workspaceSnapshot.diffStat || "(\uC5C6\uC74C)",
    "",
    "[\uCD5C\uADFC \uCEE4\uBC0B]",
    prompt.workspaceSnapshot.recentCommits.join("\n") || "(\uC5C6\uC74C)"
  ].join("\n") : prompt.workspaceSnapshot.note;
}
function renderCompactWorkspaceSnapshotMarkdown(prompt, mode) {
  if (!prompt.workspaceSnapshot.available) {
    return "";
  }
  if (mode === "review" || mode === "gen-html" || mode === "gen-storybook" || mode === "minify-md" || mode === "talk-to-figma") {
    return "";
  }
  if (mode === "commit") {
    const compactStatusLines = limitLines(
      prompt.workspaceSnapshot.statusLines,
      COMPACT_WORKSPACE_LIMITS.commit.statusLines
    );
    const compactDiffStatLines = limitLines(
      prompt.workspaceSnapshot.diffStat.split("\n").filter(Boolean),
      COMPACT_WORKSPACE_LIMITS.commit.diffStatLines
    );
    return [
      `- Branch: ${prompt.workspaceSnapshot.branch || "(detached)"}`,
      "",
      "[\uBCC0\uACBD \uD30C\uC77C \uC0C1\uD0DC]",
      compactStatusLines.join("\n") || "(\uC5C6\uC74C)",
      "",
      "[\uBCC0\uACBD \uC694\uC57D]",
      compactDiffStatLines.join("\n") || "(\uC5C6\uC74C)"
    ].join("\n");
  }
  return renderWorkspaceSnapshotMarkdown(prompt);
}
function shouldUseCompactStructuredRender(mode) {
  return !!mode && mode !== "chat";
}
function toPromptSections(prompt, options = {}) {
  const historyReferenceSection = createPromptHistoryReferenceSection(prompt.historyReferences);
  const workspaceMarkdown = options.compact ? renderCompactWorkspaceSnapshotMarkdown(prompt, options.mode) : renderWorkspaceSnapshotMarkdown(prompt);
  const sections = [
    ...options.compact ? [] : [buildExecutionOptionsSection(prompt)],
    {
      heading: "\uC9C0\uCE68 - \uBC18\uB4DC\uC2DC \uC77D\uACE0 \uADF8\uB300\uB85C \uC9C0\uCF1C\uC57C\uD560\uAC83",
      markdown: renderMarkdownAssetBlocks(prompt.instructions)
    },
    ...historyReferenceSection ? [historyReferenceSection] : [],
    ...normalizeMarkdown(workspaceMarkdown) ? [
      {
        heading: "\uD604\uC7AC \uC6CC\uD06C\uC2A4\uD398\uC774\uC2A4 \uC0C1\uD0DC",
        markdown: workspaceMarkdown
      }
    ] : [],
    {
      heading: "\uADDC\uCE59 - \uC774\uD558 \uB0B4\uC6A9\uC774 \uC5C6\uC73C\uBA74 \uBB34\uC2DC\uD558\uACE0, \uC801\uC6A9\uC5EC\uBD80\uB098 \uC801\uC6A9\uC870\uAC74\uC740 [\uC9C0\uCE68]\uC758 \uB0B4\uC6A9\uC744 \uB530\uB978\uB2E4.",
      markdown: renderMarkdownAssetBlocks(prompt.rules)
    },
    {
      heading: "\uC751\uB2F5 \uC591\uC2DD  - \uC774\uD558 \uB0B4\uC6A9\uC774 \uC5C6\uC73C\uBA74 \uBB34\uC2DC\uD558\uACE0, \uC801\uC6A9\uC5EC\uBD80\uB098 \uC801\uC6A9\uC870\uAC74\uC740 [\uC9C0\uCE68]\uC758 \uB0B4\uC6A9\uC744 \uB530\uB978\uB2E4.",
      markdown: renderMarkdownAssetBlocks(prompt.forms)
    },
    ...prompt.sections || []
  ];
  return sections.filter((section) => normalizeMarkdown(section.markdown));
}
function renderStructuredPrompt(prompt, mode, compact = false) {
  return [
    `# ${prompt.title}`,
    ...compact ? [] : ["", `\uD604\uC7AC \uC120\uD0DD\uB41C AI \uC11C\uBE44\uC2A4: ${prompt.service}`],
    ...toPromptSections(prompt, { compact, mode }).flatMap((section) => ["", renderLabeledSection(section)])
  ].join("\n");
}
function getUtf8ByteLength(text) {
  return Buffer.byteLength(text, "utf8");
}
function buildPromptOptimizationAudit(mode, originalPrompt, optimizedPrompt) {
  const originalBytes = getUtf8ByteLength(originalPrompt);
  const optimizedBytes = getUtf8ByteLength(optimizedPrompt.text);
  const reducedBytes = originalBytes - optimizedBytes;
  const reductionPercent = originalBytes > 0 ? Math.round(reducedBytes / originalBytes * 1e3) / 10 : 0;
  const originalEstimatedTokens = countTokens(originalPrompt);
  const reducedEstimatedTokens = originalEstimatedTokens - optimizedPrompt.optimizedTokens;
  const tokenReductionPercent = originalEstimatedTokens > 0 ? Math.round(reducedEstimatedTokens / originalEstimatedTokens * 1e3) / 10 : 0;
  return {
    mode,
    optimizedBytes,
    optimizedEstimatedTokens: optimizedPrompt.optimizedTokens,
    optimizedPrompt: optimizedPrompt.text,
    originalBytes,
    originalEstimatedTokens,
    originalPrompt,
    reducedBytes,
    reducedEstimatedTokens,
    reductionPercent,
    tokenReductionPercent
  };
}
function optimizeRenderedPrompt(prompt, mode, originalPrompt) {
  if (!mode || !isTokenOptimizerEnabled()) {
    return {
      text: prompt
    };
  }
  const optimizedPrompt = optimizeText(prompt, TOKEN_OPTIMIZER_PRESET_BY_MODE[mode]);
  return {
    promptAudit: buildPromptOptimizationAudit(mode, originalPrompt || prompt, optimizedPrompt),
    text: optimizedPrompt.text
  };
}
function renderPromptForService(prompt, mode) {
  if (typeof prompt === "string") {
    return optimizeRenderedPrompt(safeExcerpt(prompt, 2e5), mode);
  }
  const originalPrompt = renderStructuredPrompt(prompt, mode, false);
  const shouldCompact = isTokenOptimizerEnabled() && shouldUseCompactStructuredRender(mode);
  const renderedPrompt = shouldCompact ? renderStructuredPrompt(prompt, mode, true) : originalPrompt;
  return optimizeRenderedPrompt(renderedPrompt, mode, originalPrompt);
}
var TOKEN_OPTIMIZER_PRESET_BY_MODE, COMPACT_WORKSPACE_LIMITS;
var init_render = __esm({
  "src/platform/prompts/render.ts"() {
    init_config();
    init_helpers();
    init_token_optimizer();
    init_history_reference();
    init_markdown_assets();
    TOKEN_OPTIMIZER_PRESET_BY_MODE = {
      chat: {
        stripAnsi: true
      },
      commit: {
        maxCharsPerLine: 400,
        stripAnsi: true,
        stripEmptyLines: true
      },
      "gen-html": {
        stripAnsi: true
      },
      "gen-storybook": {
        stripAnsi: true
      },
      "minify-md": {
        stripAnsi: true
      },
      "talk-to-figma": {
        stripAnsi: true
      },
      review: {
        maxCharsPerLine: 400,
        stripAnsi: true,
        stripEmptyLines: true
      }
    };
    COMPACT_WORKSPACE_LIMITS = {
      commit: {
        diffStatLines: 20,
        statusLines: 24
      }
    };
  }
});

// src/platform/ai-services/internal/shared.ts
function quoteArgs(args) {
  return args.map((arg) => shellQuote(arg)).join(" ");
}
function formatAttemptPreviewHeading(attempt, index) {
  return index === 0 ? `# \uCD5C\uCD08 \uC2E4\uD589 (${attempt.label})` : `# \uD3F4\uBC31 ${index} (${attempt.label})`;
}
function formatServiceCommandPreview(command, attempts) {
  return attempts.map((attempt, index) => [formatAttemptPreviewHeading(attempt, index), `${command} ${quoteArgs(attempt.args)}`].join("\n")).join("\n\n");
}
function toUnique(values) {
  const seen = /* @__PURE__ */ new Set();
  return values.filter((value) => {
    if (!value || seen.has(value)) {
      return false;
    }
    seen.add(value);
    return true;
  });
}
function buildServiceModelCandidates(service, preferredModel) {
  const fallbackModels = SERVICE_FALLBACK_MODELS[service];
  return toUnique(preferredModel ? [preferredModel, ...fallbackModels] : fallbackModels);
}
function isAccountDefaultModel(model) {
  return model === ACCOUNT_DEFAULT_MODEL;
}
function createServiceCommandSpec(command, attempts, promptAudit) {
  const normalizedAttempts = attempts.map(({ args, label, modelName, outputProtocol, stdoutCaptureMode }) => ({
    args,
    label,
    modelName,
    outputProtocol: outputProtocol || "plain-text",
    stdoutCaptureMode,
    preview: `${command} ${quoteArgs(args)}`
  }));
  return {
    attempts: normalizedAttempts,
    command,
    promptAudit,
    preview: formatServiceCommandPreview(command, normalizedAttempts)
  };
}
var ACCOUNT_DEFAULT_MODEL, SERVICE_FALLBACK_MODELS;
var init_shared = __esm({
  "src/platform/ai-services/internal/shared.ts"() {
    init_helpers();
    ACCOUNT_DEFAULT_MODEL = "account-default";
    SERVICE_FALLBACK_MODELS = {
      claude: [ACCOUNT_DEFAULT_MODEL, "haiku", "sonnet"],
      codex: [ACCOUNT_DEFAULT_MODEL, "gpt-5"],
      gemini: [ACCOUNT_DEFAULT_MODEL, "flash", "auto"]
    };
  }
});

// src/platform/ai-services/builders/claude.ts
function normalizeClaudeEffort(effort) {
  if (effort === "minimal") {
    return "low";
  }
  return effort;
}
function buildClaudeArgs(prompt, autoYes, streamOutputEnabled, effort, model) {
  const args = ["--permission-mode", autoYes ? "bypassPermissions" : "acceptEdits"];
  if (effort) {
    args.push("--effort", effort);
  }
  if (model) {
    args.push("--model", model);
  }
  if (streamOutputEnabled) {
    args.push("--verbose", "--output-format", "stream-json", "--include-partial-messages");
  }
  args.push("-p", prompt);
  return args;
}
function buildClaudeCommand(prompt, mode, parsedArgs, autoYes = false, streamOutputEnabled = false) {
  const renderedPrompt = renderPromptForService(prompt, mode);
  const effort = parsedArgs.reasoningEffort ? normalizeClaudeEffort(parsedArgs.reasoningEffort) : void 0;
  const modelCandidates = buildServiceModelCandidates("claude", parsedArgs.model);
  const outputProtocol = streamOutputEnabled ? "claude-stream-json" : "plain-text";
  const attempts = modelCandidates.map((model) => ({
    args: buildClaudeArgs(renderedPrompt.text, autoYes, streamOutputEnabled, effort, isAccountDefaultModel(model) ? void 0 : model),
    label: `model:${model}`,
    modelName: model,
    outputProtocol
  }));
  return createServiceCommandSpec("claude", attempts, renderedPrompt.promptAudit);
}
var init_claude = __esm({
  "src/platform/ai-services/builders/claude.ts"() {
    init_render();
    init_shared();
  }
});

// src/platform/ai-services/builders/codex.ts
function buildCodexArgs(prompt, autoYes, streamOutputEnabled, reasoningEffort, model) {
  const args = autoYes ? ["exec", "-c", 'approval_policy="never"', "-s", "workspace-write"] : ["exec", "--full-auto"];
  if (model) {
    args.push("--model", model);
  }
  if (reasoningEffort) {
    args.push("-c", `model_reasoning_effort="${reasoningEffort}"`);
  }
  if (streamOutputEnabled) {
    args.push("--json");
  }
  args.push(prompt);
  return args;
}
function buildCodexCommand(prompt, mode, parsedArgs, autoYes = false, streamOutputEnabled = false) {
  const renderedPrompt = renderPromptForService(prompt, mode);
  const effort = parsedArgs.reasoningEffort;
  const modelCandidates = buildServiceModelCandidates("codex", parsedArgs.model);
  const outputProtocol = streamOutputEnabled ? "codex-stream-json" : "plain-text";
  const stdoutCaptureMode = streamOutputEnabled ? "codex-last-message-file" : void 0;
  const attempts = modelCandidates.map((model) => ({
    args: buildCodexArgs(
      renderedPrompt.text,
      autoYes,
      streamOutputEnabled,
      effort,
      isAccountDefaultModel(model) ? void 0 : model
    ),
    label: `model:${model}`,
    modelName: model,
    outputProtocol,
    stdoutCaptureMode
  }));
  return createServiceCommandSpec("codex", attempts, renderedPrompt.promptAudit);
}
var init_codex = __esm({
  "src/platform/ai-services/builders/codex.ts"() {
    init_render();
    init_shared();
  }
});

// src/platform/ai-services/builders/gemini.ts
function buildGeminiArgs(prompt, autoYes, streamOutputEnabled, model) {
  const args = ["--approval-mode", autoYes ? "yolo" : "auto_edit", "--sandbox"];
  if (streamOutputEnabled) {
    args.push("--output-format", "stream-json", "--raw-output", "--accept-raw-output-risk");
  }
  if (!model) {
    args.push("-p", prompt);
    return args;
  }
  args.push("--model", model, "-p", prompt);
  return args;
}
function buildGeminiCommand(prompt, mode, parsedArgs, autoYes = false, streamOutputEnabled = false) {
  const renderedPrompt = renderPromptForService(prompt, mode);
  const modelCandidates = buildServiceModelCandidates("gemini", parsedArgs.model);
  const outputProtocol = streamOutputEnabled ? "gemini-stream-json" : "plain-text";
  const attempts = modelCandidates.map((model) => ({
    args: buildGeminiArgs(renderedPrompt.text, autoYes, streamOutputEnabled, isAccountDefaultModel(model) ? void 0 : model),
    label: `model:${model}`,
    modelName: model,
    outputProtocol
  }));
  return createServiceCommandSpec("gemini", attempts, renderedPrompt.promptAudit);
}
var init_gemini = __esm({
  "src/platform/ai-services/builders/gemini.ts"() {
    init_render();
    init_shared();
  }
});
var init_build_service_command = __esm({
  "src/platform/ai-services/internal/build-service-command.ts"() {
    init_types();
    init_claude();
    init_codex();
    init_gemini();
    ({
      [AI_SERVICE.CODEX]: buildCodexCommand,
      [AI_SERVICE.GEMINI]: buildGeminiCommand,
      [AI_SERVICE.CLAUDE]: buildClaudeCommand
    });
  }
});

// src/platform/ai-services/internal/semver.ts
var init_semver = __esm({
  "src/platform/ai-services/internal/semver.ts"() {
  }
});
var init_cli_management = __esm({
  "src/platform/ai-services/internal/cli-management.ts"() {
    init_helpers();
    init_types();
    init_semver();
    ({
      [AI_SERVICE.CODEX]: "codex",
      [AI_SERVICE.GEMINI]: "gemini",
      [AI_SERVICE.CLAUDE]: "claude"
    });
    ({
      [AI_SERVICE.CODEX]: "@openai/codex",
      [AI_SERVICE.GEMINI]: "@google/gemini-cli",
      [AI_SERVICE.CLAUDE]: "@anthropic-ai/claude-code"
    });
  }
});
var init_output_capture = __esm({
  "src/platform/ai-services/internal/output-capture.ts"() {
  }
});

// src/platform/ai-services/internal/structured-output-helpers.ts
var init_structured_output_helpers = __esm({
  "src/platform/ai-services/internal/structured-output-helpers.ts"() {
  }
});

// src/platform/ai-services/internal/claude-stream-json-output-processor.ts
var init_claude_stream_json_output_processor = __esm({
  "src/platform/ai-services/internal/claude-stream-json-output-processor.ts"() {
    init_structured_output_helpers();
  }
});

// src/platform/ai-services/internal/codex-stream-json-output-processor.ts
var init_codex_stream_json_output_processor = __esm({
  "src/platform/ai-services/internal/codex-stream-json-output-processor.ts"() {
    init_structured_output_helpers();
  }
});

// src/platform/ai-services/internal/gemini-stream-json-output-processor.ts
var init_gemini_stream_json_output_processor = __esm({
  "src/platform/ai-services/internal/gemini-stream-json-output-processor.ts"() {
    init_structured_output_helpers();
  }
});

// src/platform/ai-services/internal/structured-output-processors.ts
var init_structured_output_processors = __esm({
  "src/platform/ai-services/internal/structured-output-processors.ts"() {
    init_claude_stream_json_output_processor();
    init_codex_stream_json_output_processor();
    init_gemini_stream_json_output_processor();
  }
});

// src/platform/ai-services/internal/output-processors.ts
var init_output_processors = __esm({
  "src/platform/ai-services/internal/output-processors.ts"() {
    init_structured_output_processors();
  }
});
var init_execute_attempt = __esm({
  "src/platform/ai-services/internal/execute-attempt.ts"() {
    init_cancellation();
    init_helpers();
    init_output_capture();
    init_output_processors();
    init_shared();
  }
});
var DEFAULT_STREAM_OUTPUT_STATE;
var init_stream_output = __esm({
  "src/platform/ai-services/stream-output.ts"() {
    DEFAULT_STREAM_OUTPUT_STATE = {
      enabled: false
    };
    globalThis.__JU_HONG_E_STREAM_OUTPUT_STATE__ ?? (globalThis.__JU_HONG_E_STREAM_OUTPUT_STATE__ = {
      ...DEFAULT_STREAM_OUTPUT_STATE
    });
  }
});

// src/platform/ai-services/index.ts
var init_ai_services = __esm({
  "src/platform/ai-services/index.ts"() {
    init_config();
    init_cancellation();
    init_helpers();
    init_guard();
    init_build_service_command();
    init_cli_management();
    init_execute_attempt();
    init_shared();
    init_stream_output();
    init_cli_management();
  }
});

// src/platform/actions/shared.ts
var init_shared2 = __esm({
  "src/platform/actions/shared.ts"() {
    init_ai_services();
    init_helpers();
    init_history_reference();
  }
});
var init_paths = __esm({
  "src/features/gen-html/infrastructure/local-server/paths.ts"() {
    new Set(
      module$1.builtinModules.flatMap((moduleName) => [moduleName, moduleName.replace(/^node:/, ""), `node:${moduleName.replace(/^node:/, "")}`])
    );
  }
});

// src/features/retouch/domain/constants.ts
var init_constants = __esm({
  "src/features/retouch/domain/constants.ts"() {
  }
});
var init_response_files = __esm({
  "src/features/gen-html/domain/response-files.ts"() {
  }
});
var init_component_input = __esm({
  "src/features/gen-html/domain/component-input.ts"() {
  }
});
var init_build_common_prompt = __esm({
  "src/platform/prompts/build-common-prompt.ts"() {
    init_markdown_assets();
    createPromptMarkdownFileAsset(
      (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)),
      "src/platform/prompts/assets/common/base-instructions.md"
    );
  }
});
var init_rule_selector = __esm({
  "src/platform/prompts/rule-selector.ts"() {
    init_markdown_assets();
  }
});

// src/features/gen-html-multiple/infrastructure/server-utils.ts
var init_server_utils = __esm({
  "src/features/gen-html-multiple/infrastructure/server-utils.ts"() {
    init_helpers();
    init_component_input();
  }
});

// src/features/gen-html-multiple/application/action.ts
init_shared2();
init_cancellation();
init_helpers();

// src/platform/analytics/posthog.ts
init_helpers();
globalThis.__JU_HONG_E_POSTHOG_RUNTIME_STATE__ ?? (globalThis.__JU_HONG_E_POSTHOG_RUNTIME_STATE__ = {});

// src/platform/ui/prompt.ts
init_cancellation();
init_cancellation();

// src/features/mcp/infrastructure/runtime.ts
init_helpers();

// src/features/mcp/domain/server-record.ts
init_helpers();

// src/features/gen-html/infrastructure/local-server/index.ts
init_helpers();

// src/features/gen-html/infrastructure/local-server/dependencies/installer.ts
init_helpers();
init_paths();

// src/features/gen-html/infrastructure/local-server/dependencies/manifest.ts
init_paths();

// src/features/gen-html/infrastructure/local-server/dependencies/style-bridges.ts
init_paths();

// src/features/gen-html/infrastructure/local-server/dependencies/published-install.ts
init_helpers();
init_paths();

// src/features/gen-html/infrastructure/local-server/dependencies/workspace.ts
init_paths();

// src/features/gen-html/infrastructure/local-server/dependencies/generated-output.ts
init_paths();

// src/features/gen-html/infrastructure/local-server/health.ts
init_helpers();
init_paths();

// src/features/gen-html/infrastructure/local-server/lock.ts
init_paths();

// src/features/gen-html/infrastructure/local-server/index.ts
init_paths();

// src/features/gen-html/infrastructure/local-server/storybook-config.ts
init_constants();

// src/features/gen-html/infrastructure/runtime.ts
init_response_files();

// src/features/gen-html/infrastructure/local-server/storybook-config.ts
init_paths();
init_paths();
init_paths();

// src/features/gen-html/infrastructure/local-server/refresh-coordinator.ts
init_helpers();
init_paths();
init_paths();

// src/features/retouch/application/action.ts
init_shared2();
init_helpers();
init_paths();
async function stopRunningRetouchServer() {
  {
    return;
  }
}

// src/features/gen-html-multiple/infrastructure/server.ts
init_cancellation();
init_helpers();

// src/features/gen-html/application/executor.ts
init_shared2();
init_helpers();

// src/features/gen-html/application/finalize-record.ts
init_shared2();
init_component_input();

// src/features/gen-html/application/generate-artifacts.ts
init_helpers();
init_component_input();

// src/features/gen-html/application/generation.ts
init_shared2();
init_history_reference();

// src/features/gen-html/application/prompt.ts
init_build_common_prompt();
init_rule_selector();

// src/features/gen-html-multiple/infrastructure/server.ts
init_component_input();
init_paths();

// src/features/gen-html-multiple/infrastructure/error-report.ts
init_helpers();
init_component_input();

// src/features/gen-html-multiple/infrastructure/scheduler.ts
init_cancellation();
init_helpers();
init_component_input();

// src/features/gen-html-multiple/infrastructure/server.ts
init_server_utils();
async function stopRunningGenHtmlMultipleServer() {
  {
    return;
  }
}

// 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
init_cancellation();
init_markdown_assets();
init_default_rules();
init_guard();
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/exit/index.ts
addCommand(
  ({ createCommand: createCommand2 }) => createCommand2({
    command: "/exit",
    description: "\uC138\uC158 \uC885\uB8CC",
    /**
     * @description
     * `execute` 는 대상 값를 실행한다.
     * 사용자가 해당 builtin 명령을 선택했을 때 가장 먼저 호출되는 실행 엔트리다.
     * 세션 종료 전 백그라운드로 떠 있는 gen-html-multiple 서버를 정리한다.
     *
     * @returns execute 실행 결과
     */
    execute: async () => {
      await stopRunningGenHtmlMultipleServer();
      await stopRunningRetouchServer();
      return {
        shouldExit: true
      };
    },
    order: 70
  })
);
