'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');
require('readline');
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);

// 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
};
globalThis.__JU_HONG_E_STREAM_OUTPUT_STATE__ ?? (globalThis.__JU_HONG_E_STREAM_OUTPUT_STATE__ = {
  ...DEFAULT_STREAM_OUTPUT_STATE
});

// 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)
    }
  ];
}
function resolveShellPath() {
  return process.env.SHELL?.trim() || "/bin/zsh";
}
function createShExecutionSpec(rawCommand) {
  const normalizedRawCommand = rawCommand.trim();
  const shellPath = resolveShellPath();
  const shellName = path__default.default.basename(shellPath);
  if (!normalizedRawCommand) {
    return {
      mode: "interactive",
      previewCommand: `${shellName} -i`,
      rawCommand: "",
      shellPath
    };
  }
  return {
    mode: "command",
    previewCommand: normalizedRawCommand,
    rawCommand: normalizedRawCommand,
    shellPath
  };
}
async function withTemporarySigintGuard(task) {
  const handleSigint = () => void 0;
  process.on("SIGINT", handleSigint);
  try {
    return await task();
  } finally {
    process.off("SIGINT", handleSigint);
  }
}
async function executeShCommand(spec, cwd) {
  return withTemporarySigintGuard(
    () => new Promise((resolve, reject) => {
      const args = spec.mode === "interactive" ? ["-i"] : ["-lc", spec.rawCommand];
      const child = child_process.spawn(spec.shellPath, args, {
        cwd,
        stdio: "inherit"
      });
      child.once("error", reject);
      child.once("close", (exitCode, signal) => {
        resolve({
          exitCode,
          liveOnly: true,
          signal
        });
      });
    })
  );
}
function formatShExitLabel(result) {
  return result.signal ? `signal=${result.signal}` : `exitCode=${result.exitCode ?? "null"}`;
}
function formatShExecutionOutput(spec, result) {
  return [
    spec.mode === "interactive" ? "\uC778\uD130\uB799\uD2F0\uBE0C shell \uC138\uC158\uC774 \uC885\uB8CC\uB418\uC5C8\uC2B5\uB2C8\uB2E4." : "shell \uBA85\uB839 \uC2E4\uD589\uC774 \uC885\uB8CC\uB418\uC5C8\uC2B5\uB2C8\uB2E4.",
    "\uCD9C\uB825\uC740 \uD130\uBBF8\uB110\uC5D0 \uC9C1\uC811 \uD45C\uC2DC\uB418\uC5C8\uACE0, history\uC5D0\uB294 \uC804\uCCB4 transcript\uB97C \uC800\uC7A5\uD558\uC9C0 \uC54A\uC558\uC2B5\uB2C8\uB2E4.",
    `\uC885\uB8CC \uC0C1\uD0DC: ${formatShExitLabel(result)}`
  ].join("\n");
}

// src/features/sh/application/action.ts
function createShSummary(input, exitLabel) {
  return `/sh \uC885\uB8CC(${exitLabel}): ${safeExcerpt(input, 60)}`;
}
function createShTitle(input) {
  return `shell \uBA85\uB839: ${safeExcerpt(input, 80)}`;
}
async function runShAction(options) {
  let stage = "create-spec";
  options.trace("shell-command:action:start", safeExcerpt(options.input, 120));
  try {
    const context = captureActionContext(options.paths);
    const spec = createShExecutionSpec(options.rawArgs);
    options.trace("shell-command:resolved", `${spec.mode} | ${spec.previewCommand}`);
    if (options.parsedArgs.testMode) {
      const output = `[test mode] ${spec.previewCommand}`;
      console.log(output);
      const record2 = finalizeAction(options.paths, context, {
        extraSections: [
          {
            heading: "Shell Passthrough",
            markdown: [
              `- mode: \`${spec.mode}\``,
              `- shellPath: \`${spec.shellPath}\``,
              `- preview: \`${spec.previewCommand}\``,
              "- \uC885\uB8CC \uC0C1\uD0DC: `skipped(test mode)`"
            ].join("\n")
          }
        ],
        input: options.input,
        output,
        previewCommand: spec.previewCommand,
        scope: "shell-command",
        service: options.service,
        skipped: true,
        summary: `/sh \uD14C\uC2A4\uD2B8 \uC2E4\uD589: ${safeExcerpt(options.input, 60)}`,
        title: createShTitle(options.input)
      });
      options.trace("shell-command:action:end", `history=${record2.historyPath || "(\uC5C6\uC74C)"} skipped=test-mode`);
      return record2;
    }
    console.log(spec.mode === "interactive" ? "\uB85C\uCEEC shell \uC138\uC158\uC744 \uC2DC\uC791\uD569\uB2C8\uB2E4. \uC885\uB8CC\uD558\uBA74 \uC8FC\uD64D\uC774\uB85C \uB3CC\uC544\uC635\uB2C8\uB2E4." : `shell \uBA85\uB839\uC744 \uC2E4\uD589\uD569\uB2C8\uB2E4: ${spec.previewCommand}`);
    stage = "execute-command";
    options.trace("shell-command:exec:start", spec.previewCommand);
    const result = await executeShCommand(spec, options.paths.rootDir);
    const exitLabel = formatShExitLabel(result);
    options.trace("shell-command:exec:end", exitLabel);
    console.log(`shell \uC2E4\uD589\uC774 \uB05D\uB0AC\uC2B5\uB2C8\uB2E4. ${exitLabel}`);
    stage = "finalize-record";
    const record = finalizeAction(options.paths, context, {
      extraSections: [
        {
          heading: "Shell Passthrough",
          markdown: [
            `- mode: \`${spec.mode}\``,
            `- shellPath: \`${spec.shellPath}\``,
            `- preview: \`${spec.previewCommand}\``,
            `- \uC885\uB8CC \uC0C1\uD0DC: \`${exitLabel}\``
          ].join("\n")
        }
      ],
      input: options.input,
      output: formatShExecutionOutput(spec, result),
      previewCommand: spec.previewCommand,
      scope: "shell-command",
      service: options.service,
      skipped: false,
      summary: createShSummary(options.input, exitLabel),
      title: createShTitle(options.input)
    });
    options.trace("shell-command:action:end", `history=${record.historyPath || "(\uC5C6\uC74C)"} exit=${exitLabel}`);
    return record;
  } catch (error) {
    if (isUserTerminatedError(error)) {
      options.trace("shell-command:action:terminated", stage);
    } else if (isUserCancelledError(error)) {
      options.trace("shell-command:action:cancelled", stage);
    } else {
      options.trace("shell-command: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"
});
globalThis.__JU_HONG_E_POSTHOG_RUNTIME_STATE__ ?? (globalThis.__JU_HONG_E_POSTHOG_RUNTIME_STATE__ = {});

// 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/sh/index.ts
addCommand(
  ({ createCommand: createCommand2 }) => createCommand2({
    command: "/sh",
    description: "\uB85C\uCEEC shell \uBA85\uB839 \uB610\uB294 \uC778\uD130\uB799\uD2F0\uBE0C shell \uC138\uC158 \uC2E4\uD589",
    insertValue: "/sh ",
    /**
     * @description
     * `execute` 는 대상 값를 실행한다.
     * 사용자가 해당 builtin 명령을 선택했을 때 가장 먼저 호출되는 실행 엔트리다.
     *
     * @param context 현재 명령 실행 컨텍스트
     * @returns execute 비동기 처리 결과
     */
    execute: async (context) => {
      const record = await runShAction({
        input: context.input,
        parsedArgs: context.parsedArgs,
        paths: context.paths,
        rawArgs: context.rawArgs,
        service: context.service,
        trace: context.trace
      });
      return {
        record
      };
    },
    matchKeywords: ["shell", "terminal", "bash", "zsh", "cmd"],
    order: 61
  })
);
