import { existsSync } from 'node:fs';
import process__default from 'node:process';
import a from './index5.mjs';
import { i as inquirer } from './index6.mjs';
import { M as MCP_SERVICE_CONFIGS, i as addCompletedOnboarding, h as setPrimaryApiKey, c as backupMcpConfig, g as getMcpServices, b as buildMcpServerConfig, r as readMcpConfig, l as replaceMcpServers, f as fixWindowsMcpConfig, w as writeMcpConfig, s as syncMcpPermissions } from './claude-config.mjs';
import { SETTINGS_FILE, API_DEFAULT_URL, DEFAULT_CODE_TOOL_TYPE, CODE_TOOL_BANNERS, isClaudeFamilyCodeTool, CODE_TOOL_INFO, ZCF_CONFIG_FILE } from './constants.mjs';
import { ensureI18nInitialized, i18n } from './index2.mjs';
import { displayBannerWithInfo, padToDisplayWidth } from './banner.mjs';
import { readZcfConfig, updateZcfConfig, updateTomlConfig } from './ccjk-config.mjs';
import { readCcrConfig, backupCcrConfig, createDefaultCcrConfig, writeCcrConfig, configureCcrProxy, setupCcrConfiguration } from './config2.mjs';
import { i as isCcrInstalled, a as installCcr } from '../shared/ccjk.DFRPtmK_.mjs';
import { c as setMyclaudeProviderProfiles, d as clearMyclaudeProviderProfiles } from './clavue-config.mjs';
import { i as runCodexFullInit } from './codex.mjs';
import { p as parseOrchestrationLevel, a as resolveStartupCodeType, r as resolveCodeType, w as writeOrchestrationPolicy } from './code-type-resolver.mjs';
import { exec } from 'node:child_process';
import { promisify } from 'node:util';
import { n as normalizeClaudeFamilySettings, r as resolveClaudeFamilySettingsTarget } from '../shared/ccjk.DDL-4C-k.mjs';
import { exists } from './fs-operations.mjs';
import { readJsonConfig, writeJsonConfig } from './json-config.mjs';
import { i as isWindows, w as wrapCommandWithSudo, d as isTermux } from './platform.mjs';
import { p as promptApiConfigurationAction, j as ensureClaudeDir, e as getExistingApiConfig, s as switchToOfficialLogin, b as backupExistingConfig, c as copyConfigFiles, i as applyAiLanguageDirective, f as configureApi } from './config.mjs';
import { n as needsMigration, m as migrateSettingsForTokenRetrieval, d as displayMigrationResult, p as promptMigration } from '../shared/ccjk.BXv8aYs1.mjs';
import { m as modifyApiConfigPartially, c as configureApiCompletely, f as formatApiKeyDisplay } from '../shared/ccjk.L7yC58_i.mjs';
import { h as handleExitPromptError, a as handleGeneralError } from '../shared/ccjk.BtrioX1Z.mjs';
import { getInstallationStatus, installMyclaude, installClaudeCode } from './installer.mjs';
import { s as selectMcpServices } from '../shared/ccjk.DhJ1kyDR.mjs';
import { a as configureOutputStyle } from '../shared/ccjk.C0WLUnFV.mjs';
import { a as addNumbersToChoices } from '../shared/ccjk.BFQ7yr5S.mjs';
import { resolveAiOutputLanguage } from './prompts.mjs';
import { g as getRuntimeVersion } from '../shared/ccjk.gDEDGD_t.mjs';
import { p as promptBoolean } from '../shared/ccjk.DZ2LLOa-.mjs';
import { checkClaudeCodeVersionAndPrompt } from './version-checker.mjs';
import { W as WORKFLOW_CONFIG_BASE, s as selectAndInstallWorkflows } from '../shared/ccjk.BLsIiTqO.mjs';
import { r as resolveClaudeFamilyModelSlots } from '../shared/ccjk.B2U7DsPy.mjs';
import { c as checkSuperpowersInstalled, i as installSuperpowers } from '../shared/ccjk.Bq8TqZG_.mjs';

const COMETIX_PACKAGE_NAME = "@cometix/ccline";
const COMETIX_COMMAND_NAME = "ccline";
const COMETIX_COMMANDS = {
  CHECK_INSTALL: `npm list -g ${COMETIX_PACKAGE_NAME}`,
  INSTALL: `npm install -g ${COMETIX_PACKAGE_NAME}`,
  UPDATE: `npm update -g ${COMETIX_PACKAGE_NAME}`,
  PRINT_CONFIG: `${COMETIX_COMMAND_NAME} --print`,
  TUI_CONFIG: `${COMETIX_COMMAND_NAME} -c`
};

function getPlatformStatusLineConfig() {
  return {
    type: "command",
    command: isWindows() ? "%USERPROFILE%\\.claude\\ccline\\ccline.exe" : "~/.claude/ccline/ccline",
    padding: 0
  };
}

function addCCometixLineConfig() {
  try {
    const statusLineConfig = getPlatformStatusLineConfig();
    let settings = {};
    if (exists(SETTINGS_FILE)) {
      settings = readJsonConfig(SETTINGS_FILE) || {};
    }
    settings.statusLine = statusLineConfig;
    normalizeClaudeFamilySettings(settings);
    writeJsonConfig(SETTINGS_FILE, settings);
    return true;
  } catch (error) {
    console.error("Failed to add CCometixLine configuration:", error);
    return false;
  }
}
function hasCCometixLineConfig() {
  try {
    if (!exists(SETTINGS_FILE)) {
      return false;
    }
    const settings = readJsonConfig(SETTINGS_FILE);
    return !!settings?.statusLine?.command?.includes("ccline");
  } catch {
    return false;
  }
}

const execAsync = promisify(exec);
async function isCometixLineInstalled() {
  try {
    await execAsync(COMETIX_COMMANDS.CHECK_INSTALL);
    return true;
  } catch {
    return false;
  }
}
async function installCometixLine() {
  ensureI18nInitialized();
  const runInstallCommand = async () => {
    const installArgs = ["install", "-g", COMETIX_PACKAGE_NAME];
    const { command, args, usedSudo } = wrapCommandWithSudo("npm", installArgs);
    if (usedSudo) {
      console.log(a.yellow(`\u2139 ${i18n.t("installation:usingSudo")}`));
    }
    await execAsync([command, ...args].join(" "));
  };
  const isInstalled = await isCometixLineInstalled();
  if (isInstalled) {
    console.log(a.green(`\u2714 ${i18n.t("cometix:cometixAlreadyInstalled")}`));
    try {
      console.log(a.green(`${i18n.t("cometix:installingOrUpdating")}`));
      await runInstallCommand();
      console.log(a.green(`\u2714 ${i18n.t("cometix:installUpdateSuccess")}`));
    } catch (error) {
      console.log(a.yellow(`\u26A0 ${i18n.t("cometix:installUpdateFailed")}: ${error}`));
    }
    if (!hasCCometixLineConfig()) {
      try {
        addCCometixLineConfig();
        console.log(a.green(`\u2714 ${i18n.t("cometix:statusLineConfigured") || "Claude Code statusLine configured"}`));
      } catch (error) {
        console.log(a.yellow(`\u26A0 ${i18n.t("cometix:statusLineConfigFailed") || "Failed to configure statusLine"}: ${error}`));
      }
    } else {
      console.log(a.green(`\u2139 ${i18n.t("cometix:statusLineAlreadyConfigured") || "Claude Code statusLine already configured"}`));
    }
    return;
  }
  try {
    console.log(a.green(`${i18n.t("cometix:installingCometix")}`));
    await runInstallCommand();
    console.log(a.green(`\u2714 ${i18n.t("cometix:cometixInstallSuccess")}`));
    try {
      addCCometixLineConfig();
      console.log(a.green(`\u2714 ${i18n.t("cometix:statusLineConfigured") || "Claude Code statusLine configured"}`));
    } catch (configError) {
      console.log(a.yellow(`\u26A0 ${i18n.t("cometix:statusLineConfigFailed") || "Failed to configure statusLine"}: ${configError}`));
      console.log(a.green(`\u{1F4A1} ${i18n.t("cometix:statusLineManualConfig") || "Please manually add statusLine configuration to Claude Code settings"}`));
    }
  } catch (error) {
    console.error(a.red(`\u2717 ${i18n.t("cometix:cometixInstallFailed")}: ${error}`));
    throw error;
  }
}

function formatError(error, context) {
  const errorMsg = typeof error === "string" ? error : error.message;
  const patterns = [
    {
      pattern: /not initialized|Call initialize/i,
      formatter: () => ({
        title: "\u26A0\uFE0F  Configuration Not Ready",
        message: "CCJK needs to be initialized first.",
        suggestion: "Run the initialization command to set up your environment.",
        command: "ccjk init"
      })
    },
    {
      pattern: /Failed to (start|connect|fetch)/i,
      formatter: (match) => ({
        title: "\u274C Connection Failed",
        message: `Unable to ${match[1]} the service.`,
        suggestion: "Check your internet connection and try again.",
        command: "ccjk doctor"
      })
    },
    {
      pattern: /does not exist|not found/i,
      formatter: () => ({
        title: "\u{1F50D} File Not Found",
        message: "The requested file or directory does not exist.",
        suggestion: "Verify the path and try again."
      })
    },
    {
      pattern: /permission denied|EACCES/i,
      formatter: () => ({
        title: "\u{1F512} Permission Denied",
        message: "You do not have permission to access this resource.",
        suggestion: "Check file permissions or run with appropriate privileges.",
        command: "sudo ccjk <command>"
      })
    },
    {
      pattern: /network|timeout|ETIMEDOUT|ECONNREFUSED/i,
      formatter: () => ({
        title: "\u{1F310} Network Error",
        message: "Unable to connect to the server.",
        suggestion: "Check your internet connection and firewall settings."
      })
    }
  ];
  for (const { pattern, formatter } of patterns) {
    const match = errorMsg.match(pattern);
    if (match) {
      return formatter(match);
    }
  }
  return {
    title: "\u274C Error",
    message: errorMsg,
    suggestion: context ? `Context: ${context}` : "Run ccjk doctor for diagnostics.",
    command: "ccjk doctor"
  };
}
function displayError(error, context) {
  const formatted = formatError(error, context);
  console.error();
  console.error(a.red(formatted.title));
  console.error(formatted.message);
  if (formatted.suggestion) {
    console.error();
    console.error(a.yellow("\u{1F4A1} Suggestion:"), formatted.suggestion);
  }
  if (formatted.command) {
    console.error(a.cyan("   Run:"), a.green(formatted.command));
  }
  if (formatted.docsUrl) {
    console.error(a.cyan("   Docs:"), a.blue(formatted.docsUrl));
  }
  console.error();
}

class ProgressTracker {
  currentStep = 0;
  totalSteps;
  steps;
  startTime;
  constructor(steps) {
    this.steps = steps;
    this.totalSteps = steps.length;
    this.startTime = Date.now();
  }
  start() {
    console.log();
    console.log(a.cyan("\u{1F680} Starting setup..."));
    console.log(a.gray(`   ${this.totalSteps} steps to complete`));
    console.log();
  }
  nextStep(message) {
    this.currentStep++;
    const stepName = message || this.steps[this.currentStep - 1];
    const progress = Math.round(this.currentStep / this.totalSteps * 100);
    const bar = this.renderProgressBar(progress);
    console.log();
    console.log(a.cyan(`[${this.currentStep}/${this.totalSteps}]`), stepName);
    console.log(a.gray(`   ${bar} ${progress}%`));
  }
  complete() {
    const duration = ((Date.now() - this.startTime) / 1e3).toFixed(1);
    console.log();
    console.log(a.green("\u2705 Setup complete!"));
    console.log(a.gray(`   Completed in ${duration}s`));
    console.log();
  }
  error(message) {
    console.log();
    console.log(a.red("\u274C Setup failed"));
    console.log(a.white(`   ${message}`));
    console.log();
  }
  renderProgressBar(percent) {
    const width = 20;
    const filled = Math.round(percent / 100 * width);
    const empty = width - filled;
    return a.green("\u2588".repeat(filled)) + a.gray("\u2591".repeat(empty));
  }
}

async function handleMultiConfigurations(options, codeToolType) {
  const { ensureI18nInitialized } = await import('./index2.mjs');
  ensureI18nInitialized();
  try {
    let configs = [];
    if (options.apiConfigs) {
      try {
        configs = JSON.parse(options.apiConfigs);
      } catch (error) {
        throw new Error(
          i18n.t("multi-config:invalidJson", {
            error: error instanceof Error ? error.message : String(error)
          })
        );
      }
    }
    if (options.apiConfigsFile) {
      try {
        const { readFile } = await import('./fs-operations.mjs');
        const fileContent = readFile(options.apiConfigsFile);
        configs = JSON.parse(fileContent);
      } catch (error) {
        throw new Error(
          i18n.t("multi-config:fileReadFailed", {
            error: error instanceof Error ? error.message : String(error)
          })
        );
      }
    }
    await validateApiConfigs(configs);
    if (codeToolType === "claude-code") {
      await handleClaudeCodeConfigs(configs);
    } else if (codeToolType === "clavue") {
      await handleMyclaudeConfigs(configs);
    } else if (codeToolType === "codex") {
      await handleCodexConfigs(configs);
    }
    console.log(a.green(`\u2714 ${i18n.t("multi-config:configsAddedSuccessfully")}`));
  } catch (error) {
    displayError(error, "Multi-config setup");
    throw error;
  }
}
async function validateApiConfigs(configs) {
  if (!Array.isArray(configs)) {
    throw new TypeError(i18n.t("multi-config:mustBeArray"));
  }
  const { getValidProviderIds } = await import('./api-providers.mjs');
  const validProviders = [...getValidProviderIds(), "custom"];
  const names = /* @__PURE__ */ new Set();
  for (const config of configs) {
    if (config.provider && !config.type) {
      config.type = "api_key";
    }
    if (config.provider && !config.name) {
      config.name = config.provider.toUpperCase();
    }
    if (!config.provider && !config.type) {
      throw new Error(i18n.t("multi-config:providerOrTypeRequired"));
    }
    if (config.provider && !validProviders.includes(config.provider)) {
      throw new Error(
        i18n.t("errors:invalidProvider", {
          provider: config.provider,
          validProviders: validProviders.join(", ")
        })
      );
    }
    if (!config.name || typeof config.name !== "string" || config.name.trim() === "") {
      throw new Error(i18n.t("multi-config:mustHaveValidName"));
    }
    if (!["api_key", "auth_token", "ccr_proxy"].includes(config.type)) {
      throw new Error(i18n.t("multi-config:invalidAuthType", { type: config.type }));
    }
    if (names.has(config.name)) {
      throw new Error(i18n.t("multi-config:duplicateName", { name: config.name }));
    }
    names.add(config.name);
    if (config.type !== "ccr_proxy" && !config.key) {
      throw new Error(i18n.t("multi-config:configApiKeyRequired", { name: config.name }));
    }
  }
}
async function handleClaudeCodeConfigs(configs) {
  const { ClaudeCodeConfigManager } = await import('./clavue-config.mjs').then(function (n) { return n.f; });
  const addedProfiles = [];
  for (const config of configs) {
    if (config.type === "ccr_proxy") {
      throw new Error(i18n.t("multi-config:ccrProxyReserved", { name: config.name }));
    }
    const profile = await convertToClaudeCodeProfile(config);
    const result = await ClaudeCodeConfigManager.addProfile(profile);
    if (!result.success) {
      throw new Error(
        i18n.t("multi-config:configProfileAddFailed", { name: config.name, error: result.error })
      );
    }
    const storedProfile = result.addedProfile || ClaudeCodeConfigManager.getProfileByName(config.name) || profile;
    addedProfiles.push(storedProfile);
    console.log(a.green(`\u2714 ${i18n.t("multi-config:profileAdded", { name: config.name })}`));
  }
  if (addedProfiles.length > 0) {
    const summary = addedProfiles.map((profile) => `${profile.name} [${profile.authType}]`).join(", ");
    console.log(a.gray(`  \u2022 ${ClaudeCodeConfigManager.CONFIG_FILE}: ${summary}`));
  }
  const defaultConfig = configs.find((c) => c.default);
  if (defaultConfig) {
    const profile = addedProfiles.find((p) => p.name === defaultConfig.name) || ClaudeCodeConfigManager.getProfileByName(defaultConfig.name);
    if (profile && profile.id) {
      await ClaudeCodeConfigManager.switchProfile(profile.id);
      await ClaudeCodeConfigManager.applyProfileSettings(profile);
      console.log(
        a.green(`\u2714 ${i18n.t("multi-config:defaultProfileSet", { name: defaultConfig.name })}`)
      );
    }
  }
  await ClaudeCodeConfigManager.syncCcrProfile();
}
async function handleMyclaudeConfigs(configs) {
  const profiles = await Promise.all(configs.map((config) => convertToMyclaudeProviderProfile(config)));
  const activeProfile = profiles.find((_, index) => configs[index]?.default) || profiles[0];
  setMyclaudeProviderProfiles(profiles, activeProfile?.id);
  const summary = profiles.map((profile) => `${profile.name} [${profile.provider}]`).join(", ");
  console.log(a.gray(`  \u2022 ~/.clavue/.clavue.json: ${summary}`));
}
async function handleCodexConfigs(configs) {
  const { addProviderToExisting } = await import('./codex-provider-manager.mjs');
  const addedProviderIds = [];
  for (const config of configs) {
    try {
      const provider = await convertToCodexProvider(config);
      const result = await addProviderToExisting(provider, config.key || "");
      if (!result.success) {
        throw new Error(
          i18n.t("multi-config:providerAddFailed", { name: config.name, error: result.error })
        );
      }
      addedProviderIds.push(provider.id);
      console.log(a.green(`\u2714 ${i18n.t("multi-config:providerAdded", { name: config.name })}`));
    } catch (error) {
      console.error(
        a.red(
          i18n.t("multi-config:providerAddFailed", {
            name: config.name,
            error: error instanceof Error ? error.message : String(error)
          })
        )
      );
      throw error;
    }
  }
  const defaultConfig = configs.find((c) => c.default);
  if (defaultConfig) {
    const { switchToProvider } = await import('./codex.mjs').then(function (n) { return n.t; });
    const displayName = defaultConfig.name || defaultConfig.provider || "custom";
    const providerId = displayName.toLowerCase().replace(/[^a-z0-9]/g, "-");
    if (addedProviderIds.includes(providerId)) {
      await switchToProvider(providerId);
      console.log(
        a.green(`\u2714 ${i18n.t("multi-config:defaultProviderSet", { name: displayName })}`)
      );
    } else {
      console.log(
        a.red(
          i18n.t("multi-config:providerAddFailed", {
            name: displayName,
            error: "provider not added"
          })
        )
      );
    }
  }
}
async function saveSingleConfigToToml(apiConfig, provider, options) {
  try {
    const { ClaudeCodeConfigManager } = await import('./clavue-config.mjs').then(function (n) { return n.f; });
    const profile = await convertSingleConfigToProfile(apiConfig, provider, options);
    const result = await ClaudeCodeConfigManager.addProfile(profile);
    if (result.success) {
      const savedProfile = result.addedProfile || ClaudeCodeConfigManager.getProfileByName(profile.name) || profile;
      if (savedProfile.id) {
        await ClaudeCodeConfigManager.switchProfile(savedProfile.id);
        await ClaudeCodeConfigManager.applyProfileSettings(savedProfile);
      }
      console.log(
        a.green(`\u2714 ${i18n.t("configuration:singleConfigSaved", { name: profile.name })}`)
      );
    } else {
      console.warn(
        a.yellow(`${i18n.t("configuration:singleConfigSaveFailed")}: ${result.error}`)
      );
    }
  } catch (error) {
    console.warn(
      a.yellow(
        `${i18n.t("configuration:singleConfigSaveFailed")}: ${error instanceof Error ? error.message : String(error)}`
      )
    );
  }
}
async function buildClaudeCodeProfile(params) {
  const { ClaudeCodeConfigManager } = await import('./clavue-config.mjs').then(function (n) { return n.f; });
  let {
    url: baseUrl,
    authType,
    primaryModel,
    defaultHaikuModel,
    defaultSonnetModel,
    defaultOpusModel
  } = params;
  baseUrl = baseUrl || API_DEFAULT_URL;
  if (params.provider && params.provider !== "custom") {
    const { getProviderPreset } = await import('./api-providers.mjs');
    const preset = getProviderPreset(params.provider);
    if (preset?.claudeCode) {
      baseUrl = params.url || preset.claudeCode.baseUrl;
      authType = preset.claudeCode.authType;
      const modelSlots = resolveClaudeFamilyModelSlots({
        defaultModels: preset.claudeCode.defaultModels,
        selectedModel: primaryModel
      });
      primaryModel = modelSlots.primaryModel;
      defaultHaikuModel = defaultHaikuModel || modelSlots.haikuModel;
      defaultSonnetModel = defaultSonnetModel || modelSlots.sonnetModel;
      defaultOpusModel = defaultOpusModel || modelSlots.opusModel;
    }
  }
  return {
    name: params.name,
    authType,
    provider: params.provider || "custom",
    apiKey: params.key,
    baseUrl,
    primaryModel,
    defaultHaikuModel,
    defaultSonnetModel,
    defaultOpusModel,
    id: ClaudeCodeConfigManager.generateProfileId(params.name)
  };
}
async function convertSingleConfigToProfile(apiConfig, provider, options) {
  return buildClaudeCodeProfile({
    name: provider && provider !== "custom" ? provider : "custom-config",
    key: apiConfig.key,
    authType: apiConfig.authType,
    url: apiConfig.url,
    provider,
    primaryModel: options?.apiModel,
    defaultHaikuModel: options?.apiHaikuModel,
    defaultSonnetModel: options?.apiSonnetModel,
    defaultOpusModel: options?.apiOpusModel
  });
}
async function convertToClaudeCodeProfile(config) {
  return buildClaudeCodeProfile({
    name: config.name,
    key: config.key,
    authType: (config.type === "ccr_proxy" ? "api_key" : config.type) || "api_key",
    url: config.url,
    provider: config.provider,
    primaryModel: config.primaryModel,
    defaultHaikuModel: config.defaultHaikuModel,
    defaultSonnetModel: config.defaultSonnetModel,
    defaultOpusModel: config.defaultOpusModel
  });
}
async function convertToMyclaudeProviderProfile(config) {
  const claudeProfile = await convertToClaudeCodeProfile(config);
  return {
    id: claudeProfile.id || claudeProfile.name,
    name: claudeProfile.name,
    provider: config.provider || "custom",
    apiKey: claudeProfile.apiKey,
    baseUrl: claudeProfile.baseUrl,
    model: claudeProfile.primaryModel,
    fastModel: claudeProfile.defaultHaikuModel,
    authType: claudeProfile.authType,
    primaryModel: claudeProfile.primaryModel,
    defaultHaikuModel: claudeProfile.defaultHaikuModel,
    defaultSonnetModel: claudeProfile.defaultSonnetModel,
    defaultOpusModel: claudeProfile.defaultOpusModel
  };
}
async function convertToCodexProvider(config) {
  const displayName = config.name || config.provider || "custom";
  const providerId = displayName.toLowerCase().replace(/[^a-z0-9]/g, "-");
  let baseUrl = config.url || API_DEFAULT_URL;
  let model = config.primaryModel || "gpt-5-codex";
  let wireApi = "responses";
  if (config.provider && config.provider !== "custom") {
    const { getProviderPreset } = await import('./api-providers.mjs');
    const preset = getProviderPreset(config.provider);
    if (preset?.codex) {
      baseUrl = config.url || preset.codex.baseUrl;
      model = config.primaryModel || preset.codex.defaultModel || model;
      wireApi = preset.codex.wireApi;
    }
  }
  return {
    id: providerId,
    name: displayName,
    baseUrl,
    wireApi,
    tempEnvKey: `${displayName}_API_KEY`.replace(/\W/g, "_").toUpperCase(),
    requiresOpenaiAuth: false,
    model
  };
}

async function validateSkipPromptOptions(options) {
  if (options.allLang) {
    if (options.allLang === "zh-CN" || options.allLang === "en") {
      options.configLang = options.allLang;
      options.aiOutputLang = options.allLang;
    } else {
      options.configLang = "en";
      options.aiOutputLang = options.allLang;
    }
  }
  if (options.provider) {
    const { getValidProviderIds, getProviderPreset } = await import('./api-providers.mjs');
    const validProviders = [...getValidProviderIds(), "custom"];
    if (!validProviders.includes(options.provider)) {
      throw new Error(
        i18n.t("errors:invalidProvider", {
          provider: options.provider,
          validProviders: validProviders.join(", ")
        })
      );
    }
    if (!options.apiType) {
      const preset = options.provider !== "custom" ? getProviderPreset(options.provider) : null;
      options.apiType = preset?.claudeCode?.authType || "api_key";
    }
  }
  if (!options.configAction) {
    options.configAction = "backup";
  }
  if (typeof options.outputStyles === "string") {
    if (options.outputStyles === "skip") {
      options.outputStyles = false;
    } else if (options.outputStyles === "all") {
      options.outputStyles = ["speed-coder", "senior-architect", "pair-programmer"];
    } else {
      options.outputStyles = options.outputStyles.split(",").map((s) => s.trim());
    }
  }
  if (options.outputStyles === void 0) {
    options.outputStyles = ["speed-coder", "senior-architect", "pair-programmer"];
  }
  if (!options.defaultOutputStyle) {
    options.defaultOutputStyle = "senior-architect";
  }
  if (typeof options.installCometixLine === "string") {
    options.installCometixLine = options.installCometixLine.toLowerCase() === "true";
  }
  if (options.installCometixLine === void 0) {
    options.installCometixLine = true;
  }
  if (typeof options.installSuperpowers === "string") {
    options.installSuperpowers = options.installSuperpowers.toLowerCase() === "true";
  }
  if (options.installSuperpowers === void 0) {
    options.installSuperpowers = false;
  }
  if (typeof options.installAgentBrowser === "string") {
    options.installAgentBrowser = options.installAgentBrowser.toLowerCase() === "true";
  }
  if (options.installAgentBrowser === void 0) {
    options.installAgentBrowser = true;
  }
  if (options.configAction && !["new", "backup", "merge", "docs-only", "skip"].includes(options.configAction)) {
    throw new Error(i18n.t("errors:invalidConfigAction", { value: options.configAction }));
  }
  if (options.apiType && !["auth_token", "api_key", "ccr_proxy", "skip"].includes(options.apiType)) {
    throw new Error(i18n.t("errors:invalidApiType", { value: options.apiType }));
  }
  if (options.apiConfigs && options.apiConfigsFile) {
    throw new Error(i18n.t("multi-config:conflictingParams"));
  }
  const modelParams = [
    ["apiModel", options.apiModel],
    ["apiHaikuModel", options.apiHaikuModel],
    ["apiSonnetModel", options.apiSonnetModel],
    ["apiOpusModel", options.apiOpusModel]
  ];
  for (const [key, value] of modelParams) {
    if (value !== void 0 && typeof value !== "string") {
      if (key === "apiModel")
        throw new Error(i18n.t("errors:invalidApiModel", { value }));
      throw new Error(i18n.t("errors:invalidModelParam", { key, value }));
    }
  }
  if (options.apiType === "api_key" && !options.apiKey) {
    throw new Error(i18n.t("errors:apiKeyRequiredForApiKey"));
  }
  if (options.apiType === "auth_token" && !options.apiKey) {
    throw new Error(i18n.t("errors:apiKeyRequiredForAuthToken"));
  }
  if (typeof options.mcpServices === "string") {
    if (options.mcpServices === "skip") {
      options.mcpServices = false;
    } else if (options.mcpServices === "all") {
      options.mcpServices = MCP_SERVICE_CONFIGS.filter((s) => !s.requiresApiKey).map((s) => s.id);
    } else {
      options.mcpServices = options.mcpServices.split(",").map((s) => s.trim());
    }
  }
  if (Array.isArray(options.mcpServices)) {
    const validServices = MCP_SERVICE_CONFIGS.map((s) => s.id);
    for (const service of options.mcpServices) {
      if (!validServices.includes(service)) {
        throw new Error(
          i18n.t("errors:invalidMcpService", { service, validServices: validServices.join(", ") })
        );
      }
    }
  }
  if (Array.isArray(options.outputStyles)) {
    const validStyles = [
      "speed-coder",
      "senior-architect",
      "pair-programmer",
      "default",
      "explanatory",
      "learning"
    ];
    for (const style of options.outputStyles) {
      if (!validStyles.includes(style)) {
        throw new Error(
          i18n.t("errors:invalidOutputStyle", { style, validStyles: validStyles.join(", ") })
        );
      }
    }
  }
  if (options.defaultOutputStyle) {
    const validStyles = [
      "speed-coder",
      "senior-architect",
      "pair-programmer",
      "default",
      "explanatory",
      "learning"
    ];
    if (!validStyles.includes(options.defaultOutputStyle)) {
      throw new Error(
        i18n.t("errors:invalidDefaultOutputStyle", {
          style: options.defaultOutputStyle,
          validStyles: validStyles.join(", ")
        })
      );
    }
  }
  if (options.orchestration !== void 0) {
    parseOrchestrationLevel(options.orchestration);
  }
  if (typeof options.workflows === "string") {
    if (options.workflows === "skip") {
      options.workflows = false;
    } else if (options.workflows === "all") {
      options.workflows = WORKFLOW_CONFIG_BASE.map((w) => w.id);
    } else {
      options.workflows = options.workflows.split(",").map((s) => s.trim());
    }
  }
  if (Array.isArray(options.workflows)) {
    const validWorkflows = WORKFLOW_CONFIG_BASE.map((w) => w.id);
    for (const workflow of options.workflows) {
      if (!validWorkflows.includes(workflow)) {
        throw new Error(
          i18n.t("errors:invalidWorkflow", { workflow, validWorkflows: validWorkflows.join(", ") })
        );
      }
    }
  }
  if (options.mcpServices === void 0) {
    options.mcpServices = "all";
    options.mcpServices = MCP_SERVICE_CONFIGS.filter((s) => !s.requiresApiKey).map((s) => s.id);
  }
  if (options.workflows === void 0) {
    options.workflows = "all";
    options.workflows = WORKFLOW_CONFIG_BASE.map((w) => w.id);
  }
  if (options.orchestration === void 0) {
    options.orchestration = "max";
  }
}
async function silentInit(options = {}) {
  try {
    try {
      const { cleanupZcfNamespace } = await import('./cleanup-migration.mjs');
      cleanupZcfNamespace();
    } catch {
    }
    const { detectSmartDefaults } = await import('./code-type-resolver.mjs').then(function (n) { return n.b; });
    const defaults = await detectSmartDefaults();
    if (!defaults.apiKey) {
      throw new Error("Silent mode requires ANTHROPIC_API_KEY environment variable");
    }
    options.skipPrompt = true;
    options.skipBanner = true;
    options.initSource = "silent-init";
    options.yes = true;
    options.silent = false;
    options.apiType = "api_key";
    options.apiKey = defaults.apiKey;
    if (defaults.apiProvider && defaults.apiProvider !== "anthropic") {
      options.provider = defaults.apiProvider;
    }
    const topMcpServices = defaults.mcpServices.slice(0, 3);
    options.mcpServices = topMcpServices;
    options.codeType = defaults.codeToolType || "claude-code";
    options.configAction = "backup";
    options.installCometixLine = false;
    options.installSuperpowers = false;
    options.installAgentBrowser = options.installAgentBrowser ?? true;
    options.workflows = false;
    options.orchestration = options.orchestration || defaults.workflows.orchestrationLevel || "minimal";
    console.log(`Initializing CCJK (silent mode)...`);
    console.log(`  Code Tool: ${defaults.codeToolType}`);
    console.log(`  API Provider: ${defaults.apiProvider || "anthropic"}`);
    console.log(`  MCP Services: ${topMcpServices.join(", ")}`);
    const { init } = await Promise.resolve().then(function () { return init$1; });
    await init(options);
    console.log("\u2713 CCJK initialized successfully");
  } catch (error) {
    displayError(error, "Silent initialization");
    throw error;
  }
}
async function handleSuperpowersInstallation(options) {
  try {
    const status = await checkSuperpowersInstalled();
    if (status.installed) {
      console.log(a.green(`\u2714 ${i18n.t("superpowers:alreadyInstalled")}`));
      if (status.version) {
        console.log(
          a.gray(`  ${i18n.t("superpowers:status.version", { version: status.version })}`)
        );
      }
      if (status.skillCount) {
        console.log(
          a.gray(`  ${i18n.t("superpowers:status.skillCount", { count: status.skillCount })}`)
        );
      }
      return;
    }
    let shouldInstall = false;
    if (options.skipPrompt) {
      shouldInstall = options.installSuperpowers === true;
    } else {
      console.log(a.green(`
${i18n.t("superpowers:title")}`));
      console.log(a.gray(i18n.t("superpowers:description")));
      console.log(a.gray(i18n.t("superpowers:installPromptDescription")));
      shouldInstall = await promptBoolean({
        message: i18n.t("superpowers:installPrompt"),
        defaultValue: false
      });
    }
    if (!shouldInstall) {
      console.log(a.yellow(i18n.t("common:skip")));
      return;
    }
    const result = await installSuperpowers({
      lang: i18n.language,
      skipPrompt: options.skipPrompt
    });
    if (result.success) {
      console.log(a.green(`\u2714 ${result.message}`));
    } else {
      console.error(a.red(`\u2716 ${result.message}`));
      if (result.error) {
        console.error(a.gray(`  ${result.error}`));
      }
    }
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : String(error);
    console.error(a.red(`${i18n.t("superpowers:installFailed")}: ${errorMessage}`));
  }
}
async function smartInit(options = {}) {
  try {
    console.log(a.bold.green("\n\u{1F9E0} Smart Initialization Mode\n"));
    console.log(a.gray("Analyzing your project to generate optimal configuration...\n"));
    const { analyzeProject } = await import('./index13.mjs');
    const analysis = await analyzeProject();
    console.log(a.cyan("\u{1F4CA} Project Analysis:"));
    console.log(a.gray(`  \u2022 Type: ${analysis.projectType}`));
    console.log(a.gray(`  \u2022 Languages: ${analysis.techStack.languages.join(", ")}`));
    console.log(a.gray(`  \u2022 Runtime: ${analysis.techStack.runtime}`));
    if (analysis.frameworks.length > 0) {
      console.log(a.gray(`  \u2022 Frameworks: ${analysis.frameworks.join(", ")}`));
    }
    if (analysis.buildTool) {
      console.log(a.gray(`  \u2022 Build Tool: ${analysis.buildTool}`));
    }
    console.log(a.gray(`  \u2022 Has Tests: ${analysis.hasTests ? "Yes" : "No"}`));
    console.log(a.gray(`  \u2022 Has Database: ${analysis.hasDatabase ? "Yes" : "No"}`));
    console.log(a.gray(`  \u2022 Has API: ${analysis.hasApi ? "Yes" : "No"}`));
    if (analysis.cicd.length > 0) {
      console.log(a.gray(`  \u2022 CI/CD: ${analysis.cicd.join(", ")}`));
    }
    console.log("");
    const { selectTemplates } = await import('./index13.mjs');
    const selection = await selectTemplates(analysis);
    console.log(a.cyan("\u{1F3AF} Template Selection:"));
    console.log(a.gray(`  \u2022 Agents: ${selection.agents.length} selected`));
    for (const agent of selection.agents) {
      console.log(a.gray(`    - ${agent.name} (${agent.category})`));
    }
    console.log(a.gray(`  \u2022 Skills: ${selection.skills.length} selected`));
    for (const skill of selection.skills) {
      console.log(a.gray(`    - ${skill.name} (${skill.category})`));
    }
    console.log("");
    console.log(a.cyan("\u{1F4A1} Reasoning:"));
    console.log(
      a.gray(
        selection.reasoning.split("\n").map((line) => `  ${line}`).join("\n")
      )
    );
    console.log("");
    if (!options.skipPrompt && !options.yes) {
      const shouldContinue = await promptBoolean({
        message: "Proceed with this configuration?",
        defaultValue: true
      });
      if (!shouldContinue) {
        console.log(a.yellow("Smart initialization cancelled."));
        return;
      }
    }
    console.log(a.gray("\n\u{1F527} Generating configurations...\n"));
    const { generateConfigs, writeConfigs } = await import('./index13.mjs');
    const config = await generateConfigs(selection);
    await writeConfigs(config);
    console.log(a.green("\u2714 Configurations generated successfully!"));
    console.log(a.gray(`  \u2022 ${config.agents.length} agents installed`));
    console.log(a.gray(`  \u2022 ${config.skills.length} skills installed`));
    console.log("");
    console.log(a.gray("Running standard initialization...\n"));
    options.smart = false;
    options.skipPrompt = options.skipPrompt ?? false;
    const { init } = await Promise.resolve().then(function () { return init$1; });
    await init(options);
    console.log("");
    console.log(a.bold.green("\u2705 Smart Initialization Complete!"));
    console.log("");
    console.log(a.cyan("\u{1F3AF} What was configured:"));
    console.log(a.gray("  \u2022 Project-specific agents and skills"));
    console.log(a.gray("  \u2022 Claude Code base configuration"));
    console.log(a.gray("  \u2022 MCP services"));
    console.log(a.gray("  \u2022 Workflows and output styles"));
    console.log("");
    console.log(a.cyan("\u{1F680} Next Steps:"));
    console.log(a.gray("  1. Run: claude"));
    console.log(a.gray("  2. Start coding with AI assistance!"));
    console.log(a.gray("  3. Use generated skills with their triggers"));
    console.log("");
  } catch (error) {
    console.error(
      a.red("\u274C Smart initialization failed:"),
      error instanceof Error ? error.message : error
    );
    throw error;
  }
}

const ccjkVersion = getRuntimeVersion();
function getDefaultArchetypeProfile(codeToolType) {
  if (codeToolType === "clavue") {
    return {
      id: "pc-dev",
      name: "PC Software Development",
      goal: "Use Clavue as the primary execution runtime for coding, debugging, testing, and shipping"
    };
  }
  return {
    id: "pc-dev",
    name: "PC Software Development",
    goal: "Build, debug, test, and ship software efficiently"
  };
}
function getSetupCompletionGuidance(codeToolType) {
  if (codeToolType === "clavue") {
    return {
      step1: i18n.t("configuration:guidanceStep1", { runtime: "clavue" }),
      step1Detail: i18n.t("configuration:guidanceStep1MyclaudeDetail"),
      step1Detail2: i18n.t("configuration:guidanceStep1MyclaudeDetail2"),
      step2: i18n.t("configuration:guidanceStep2"),
      step2Example: i18n.t("configuration:guidanceStep2Example"),
      step3: i18n.t("configuration:guidanceStep3Myclaude"),
      step3Command: i18n.t("configuration:guidanceStep3MyclaudeCommand"),
      step4: i18n.t("configuration:guidanceStep4"),
      step4Command: i18n.t("configuration:guidanceStep4Command"),
      step5: i18n.t("configuration:guidanceStep5"),
      step5Command: i18n.t("configuration:guidanceStep5Command")
    };
  }
  const runtimeLabel = CODE_TOOL_INFO[codeToolType]?.name || "Claude Code";
  return {
    step1: i18n.t("configuration:guidanceStep1", { runtime: runtimeLabel }),
    step1Detail: i18n.t("configuration:guidanceStep1Detail"),
    step1Detail2: i18n.t("configuration:guidanceStep1Detail2"),
    step2: i18n.t("configuration:guidanceStep2"),
    step2Example: i18n.t("configuration:guidanceStep2Example"),
    step3: i18n.t("configuration:guidanceStep3"),
    step3Command: i18n.t("configuration:guidanceStep3Command"),
    step4: i18n.t("configuration:guidanceStep4"),
    step4Command: i18n.t("configuration:guidanceStep4Command"),
    step5: i18n.t("configuration:guidanceStep5"),
    step5Command: i18n.t("configuration:guidanceStep5Command")
  };
}
async function init(options = {}) {
  options.initSource = options.initSource || "init";
  options.orchestration = parseOrchestrationLevel(options.orchestration);
  try {
    const { cleanupZcfNamespace } = await import('./cleanup-migration.mjs');
    const { removed } = cleanupZcfNamespace();
    if (removed.length > 0) {
      console.log(a.dim(`Cleaned up legacy zcf namespace: ${removed.join(", ")}`));
    }
  } catch {
  }
  if (options.silent) {
    return await silentInit(options);
  }
  if (options.smart) {
    return await smartInit(options);
  }
  if (options.skipPrompt) {
    await validateSkipPromptOptions(options);
  }
  try {
    const tracker = new ProgressTracker([
      "Reading configuration",
      "Selecting code tool",
      "Configuring API",
      "Installing MCP services",
      "Setting up workflows",
      "Finalizing setup"
    ]);
    if (!options.skipPrompt && !options.skipBanner) {
      tracker.start();
    }
    if (!options.skipPrompt && !options.skipBanner)
      tracker.nextStep();
    const zcfConfig = readZcfConfig();
    if (!options.skipPrompt && !options.skipBanner)
      tracker.nextStep();
    let codeToolType;
    try {
      codeToolType = await resolveStartupCodeType({
        codeTypeParam: options.codeType,
        interactive: !options.skipPrompt
      });
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : String(error);
      console.error(a.red(`${i18n.t("errors:generalError")} ${errorMessage}`));
      codeToolType = await resolveCodeType(options.codeType).catch(() => DEFAULT_CODE_TOOL_TYPE);
    }
    options.codeType = codeToolType;
    async function selectApiConfigurationMode() {
      const { apiMode } = await inquirer.prompt({
        type: "list",
        name: "apiMode",
        message: i18n.t("api:selectApiMode"),
        choices: [
          {
            name: i18n.t("api:useOfficialLogin"),
            value: "official"
          },
          {
            name: i18n.t("api:customApiConfig"),
            value: "custom"
          },
          {
            name: i18n.t("api:useCcrProxy"),
            value: "ccr"
          },
          {
            name: i18n.t("api:skipApi"),
            value: "skip"
          }
        ]
      });
      return apiMode;
    }
    async function handleCustomApiConfiguration(existingConfig) {
      if (codeToolType === "claude-code" || codeToolType === "clavue") {
        const { configureIncrementalManagement } = await import('./claude-code-incremental-manager.mjs');
        await configureIncrementalManagement();
        return null;
      }
      if (existingConfig) {
        const customConfigAction = await promptApiConfigurationAction();
        if (customConfigAction === "modify-partial") {
          await modifyApiConfigPartially(existingConfig);
          return null;
        } else if (customConfigAction === "modify-all") {
          return await configureApiCompletely();
        } else if (customConfigAction === "keep-existing") {
          try {
            addCompletedOnboarding(codeToolType);
          } catch (error) {
            console.error(a.red(i18n.t("errors:failedToSetOnboarding")), error);
          }
          try {
            setPrimaryApiKey(codeToolType);
          } catch (error) {
            const { ensureI18nInitialized, i18n: i18nModule } = await import('./index2.mjs');
            ensureI18nInitialized();
            console.error(i18nModule.t("mcp:primaryApiKeySetFailed"), error);
          }
          return null;
        }
      } else {
        const { apiChoice } = await inquirer.prompt({
          type: "list",
          name: "apiChoice",
          message: i18n.t("api:configureApi"),
          choices: [
            {
              name: `${i18n.t("api:useAuthToken")} - ${a.gray(i18n.t("api:authTokenDesc"))}`,
              value: "auth_token",
              short: i18n.t("api:useAuthToken")
            },
            {
              name: `${i18n.t("api:useApiKey")} - ${a.gray(i18n.t("api:apiKeyDesc"))}`,
              value: "api_key",
              short: i18n.t("api:useApiKey")
            }
          ]
        });
        if (!apiChoice) {
          console.log(a.yellow(i18n.t("common:cancelled")));
          process__default.exit(0);
        }
        return await configureApiCompletely(apiChoice);
      }
    }
    if (!options.skipBanner) {
      displayBannerWithInfo(CODE_TOOL_BANNERS[codeToolType] || "CCJK");
    }
    if (isTermux()) {
      console.log(a.yellow(`
\u2139 ${i18n.t("installation:termuxDetected")}`));
      console.log(a.gray(i18n.t("installation:termuxEnvironmentInfo")));
    }
    let configLang = options.configLang;
    if (codeToolType === "codex") {
      if (!configLang) {
        if (options.skipPrompt) {
          configLang = zcfConfig?.templateLang || "en";
        } else {
          configLang = zcfConfig?.templateLang || i18n.language || "en";
        }
      }
    } else {
      if (!configLang) {
        const { resolveTemplateLanguage } = await import('./prompts.mjs');
        configLang = await resolveTemplateLanguage(
          options.configLang,
          zcfConfig,
          options.skipPrompt,
          codeToolType
        );
      }
    }
    if (!configLang) {
      configLang = "en";
    }
    if (codeToolType === "codex") {
      if (options.skipPrompt)
        process__default.env.CCJK_CODEX_SKIP_PROMPT_SINGLE_BACKUP = "true";
      const hasApiConfigs = Boolean(options.apiConfigs || options.apiConfigsFile);
      const apiMode = hasApiConfigs ? "skip" : options.apiType === "auth_token" ? "official" : options.apiType === "api_key" ? "custom" : options.apiType === "skip" ? "skip" : options.skipPrompt ? "skip" : void 0;
      const customApiConfig = !hasApiConfigs && options.apiType === "api_key" && options.apiKey ? {
        type: "api_key",
        token: options.apiKey,
        baseUrl: options.apiUrl,
        model: options.apiModel
        // Add model parameter for Codex
      } : void 0;
      let selectedWorkflows;
      if (Array.isArray(options.workflows)) {
        selectedWorkflows = options.workflows;
      } else if (typeof options.workflows === "string") {
        selectedWorkflows = [options.workflows];
      } else if (options.workflows === true) {
        selectedWorkflows = [];
      }
      if (hasApiConfigs) {
        await handleMultiConfigurations(options, "codex");
      }
      const resolvedAiOutputLang = await runCodexFullInit({
        aiOutputLang: options.aiOutputLang,
        skipPrompt: options.skipPrompt,
        apiMode,
        customApiConfig,
        workflows: selectedWorkflows
      });
      updateZcfConfig({
        version: ccjkVersion,
        preferredLang: i18n.language,
        // CCJK界面语言
        templateLang: configLang,
        // 模板语言
        aiOutputLang: resolvedAiOutputLang ?? options.aiOutputLang ?? zcfConfig?.aiOutputLang ?? "en",
        codeToolType
      });
      console.log(a.green(i18n.t("codex:setupComplete")));
      return;
    }
    const aiOutputLang = await resolveAiOutputLanguage(
      i18n.language,
      options.aiOutputLang,
      zcfConfig,
      options.skipPrompt
    );
    const installerCodeType = isClaudeFamilyCodeTool(codeToolType) ? codeToolType : "claude-code";
    const installationStatus = await getInstallationStatus(installerCodeType);
    const codeToolName = CODE_TOOL_INFO[codeToolType].name;
    if (isClaudeFamilyCodeTool(codeToolType)) {
      if (installationStatus.hasGlobal) {
        const { verifyInstallation, displayVerificationResult } = await import('./installer.mjs');
        const verification = await verifyInstallation(installerCodeType);
        if (verification.symlinkCreated) {
          console.log(a.green(`\u2714 ${codeToolName} ${i18n.t("installation:alreadyInstalled")}`));
          displayVerificationResult(verification, installerCodeType);
        } else if (!verification.success) {
          console.log(a.yellow(`\u26A0 ${i18n.t("installation:verificationFailed")}`));
          if (verification.error) {
            console.log(a.gray(`  ${verification.error}`));
          }
        }
      } else {
        if (options.skipPrompt) {
          if (codeToolType === "clavue") {
            await installMyclaude(true);
          } else {
            await installClaudeCode(true);
          }
        } else {
          const shouldInstall = await promptBoolean({
            message: i18n.t("installation:installPrompt"),
            defaultValue: true
          });
          if (shouldInstall) {
            if (codeToolType === "clavue") {
              await installMyclaude(false);
            } else {
              await installClaudeCode(false);
            }
          } else {
            console.log(a.yellow(i18n.t("common:skip")));
          }
        }
      }
      if (installationStatus.hasGlobal && codeToolType === "claude-code") {
        await checkClaudeCodeVersionAndPrompt(options.skipPrompt);
      }
    }
    ensureClaudeDir(codeToolType);
    if (needsMigration(codeToolType)) {
      if (options.skipPrompt) {
        console.log(a.yellow("\n\u26A0\uFE0F  Problematic configuration detected. Auto-fixing...\n"));
        const result = migrateSettingsForTokenRetrieval(codeToolType);
        displayMigrationResult(result);
      } else {
        const shouldMigrate = await promptMigration();
        if (shouldMigrate) {
          const result = migrateSettingsForTokenRetrieval(codeToolType);
          displayMigrationResult(result);
        }
      }
    }
    let action = "new";
    const runtimeTarget = resolveClaudeFamilySettingsTarget(codeToolType);
    if (existsSync(runtimeTarget.settingsFile) && !options.force) {
      if (options.skipPrompt) {
        action = options.configAction || "backup";
        if (action === "skip") {
          console.log(a.yellow(i18n.t("common:skip")));
          return;
        }
      } else {
        const { action: userAction } = await inquirer.prompt({
          type: "list",
          name: "action",
          message: i18n.t("configuration:existingConfig"),
          choices: addNumbersToChoices([
            { name: i18n.t("configuration:backupAndOverwrite"), value: "backup" },
            { name: i18n.t("configuration:updateDocsOnly"), value: "docs-only" },
            { name: i18n.t("configuration:mergeConfig"), value: "merge" },
            { name: i18n.t("common:skip"), value: "skip" }
          ])
        });
        if (!userAction) {
          console.log(a.yellow(i18n.t("common:cancelled")));
          process__default.exit(0);
        }
        action = userAction;
        if (action === "skip") {
          console.log(a.yellow(i18n.t("common:skip")));
          return;
        }
      }
    } else if (options.skipPrompt && options.configAction) {
      action = options.configAction;
    }
    const isNewInstall = !existsSync(runtimeTarget.settingsFile);
    if (!options.skipPrompt && (isNewInstall || ["backup", "merge", "new"].includes(action))) {
      const isZh = i18n.language === "zh-CN";
      console.log("");
      console.log(
        a.bold.cyan(
          isZh ? "\u{1F48E} \u9876\u7EA7\u5927\u795E\u7F16\u6392\u7406\u5FF5\uFF08\u9ED8\u8BA4\u9996\u9009\uFF09" : "\u{1F48E} Expert Workflow Orchestration (Default First Choice)"
        )
      );
      console.log(
        a.dim(
          isZh ? "\u53EF\u540C\u6B65\u4F18\u5316\u89C4\u5212\u3001\u9A8C\u8BC1\u3001\u5B50\u4EE3\u7406\u4E0E\u89C4\u5219\u6267\u884C\u8D28\u91CF\uFF0C\u5EFA\u8BAE\u9996\u6B21\u5B89\u88C5\u7ACB\u5373\u542F\u7528\u3002" : "Improves planning, verification, subagent strategy, and rule execution quality. Recommended on first install."
        )
      );
      const { orchestrationChoice } = await inquirer.prompt({
        type: "list",
        name: "orchestrationChoice",
        message: isZh ? "\u8BF7\u9009\u62E9\u9ED8\u8BA4\u7F16\u6392\u7EA7\u522B\uFF1A" : "Select default orchestration level:",
        default: "max",
        choices: addNumbersToChoices([
          {
            name: isZh ? "\u9876\u7EA7\u6A21\u5F0F\uFF08\u63A8\u8350\uFF09- \u6700\u5927\u5316\u8D28\u91CF\u4E0E\u6D41\u7A0B\u7EA6\u675F" : "Expert Mode (Recommended) - Maximum quality and workflow enforcement",
            value: "max"
          },
          {
            name: isZh ? "\u6807\u51C6\u6A21\u5F0F - \u5E73\u8861\u8D28\u91CF\u4E0E\u901F\u5EA6" : "Standard Mode - Balanced quality and speed",
            value: "standard"
          },
          {
            name: isZh ? "\u8F7B\u91CF\u6A21\u5F0F - \u66F4\u5C11\u6D41\u7A0B\uFF0C\u66F4\u5FEB\u6267\u884C" : "Minimal Mode - Lighter process, faster execution",
            value: "minimal"
          },
          {
            name: isZh ? "\u5173\u95ED - \u4E0D\u542F\u7528\u7F16\u6392\u7B56\u7565" : "Off - Disable orchestration policy",
            value: "off"
          }
        ])
      });
      options.orchestration = orchestrationChoice;
      console.log(
        a.green(
          `\u2714 ${isZh ? "\u5DF2\u8BBE\u4E3A\u9ED8\u8BA4\u9996\u9009" : "Set as default first choice"}: ${orchestrationChoice}`
        )
      );
    }
    if (!options.skipPrompt && !options.skipBanner)
      tracker.nextStep("Configuring API");
    let apiConfig = null;
    if (action !== "docs-only" && (isNewInstall || ["backup", "merge", "new"].includes(action))) {
      if (options.skipPrompt) {
        if (options.apiConfigs || options.apiConfigsFile) {
          await handleMultiConfigurations(options, codeToolType);
          apiConfig = null;
          if (codeToolType === "claude-code") {
            clearMyclaudeProviderProfiles();
          }
        } else if (options.provider && options.apiKey) {
          const { getProviderPreset } = await import('./api-providers.mjs');
          const preset = options.provider !== "custom" ? getProviderPreset(options.provider) : null;
          apiConfig = {
            authType: preset?.claudeCode?.authType || "api_key",
            key: options.apiKey,
            url: preset?.claudeCode?.baseUrl || options.apiUrl || API_DEFAULT_URL
          };
          await saveSingleConfigToToml(apiConfig, options.provider, options);
        } else if (options.apiType === "auth_token" && options.apiKey) {
          apiConfig = {
            authType: "auth_token",
            key: options.apiKey,
            url: options.apiUrl || API_DEFAULT_URL
          };
          await saveSingleConfigToToml(apiConfig, void 0, options);
        } else if (options.apiType === "api_key" && options.apiKey) {
          apiConfig = {
            authType: "api_key",
            key: options.apiKey,
            url: options.apiUrl || API_DEFAULT_URL
          };
          await saveSingleConfigToToml(apiConfig, void 0, options);
        } else if (options.apiType === "ccr_proxy") {
          const ccrStatus = await isCcrInstalled();
          if (!ccrStatus.hasCorrectPackage) {
            await installCcr();
          } else {
            console.log(a.green(`\u2714 ${i18n.t("ccr:ccrAlreadyInstalled")}`));
          }
          const existingCcrConfig = readCcrConfig();
          if (existingCcrConfig) {
            const backupPath = await backupCcrConfig();
            if (backupPath) {
              console.log(a.gray(`\u2714 ${i18n.t("ccr:ccrBackupSuccess")}: ${backupPath}`));
            }
          }
          const defaultCcrConfig = createDefaultCcrConfig();
          writeCcrConfig(defaultCcrConfig);
          console.log(a.green(`\u2714 ${i18n.t("ccr:ccrConfigSuccess")}`));
          await configureCcrProxy(defaultCcrConfig, codeToolType);
          console.log(a.green(`\u2714 ${i18n.t("ccr:proxyConfigSuccess")}`));
          try {
            addCompletedOnboarding(codeToolType);
          } catch (error) {
            console.error(a.red(i18n.t("errors:failedToSetOnboarding")), error);
          }
          apiConfig = null;
        }
      } else {
        const existingApiConfig = getExistingApiConfig(codeToolType);
        const apiMode = await selectApiConfigurationMode();
        switch (apiMode) {
          case "official": {
            const success = switchToOfficialLogin(codeToolType);
            if (success) {
              console.log(a.green(`\u2714 ${i18n.t("api:officialLoginConfigured")}`));
              apiConfig = null;
            } else {
              console.log(a.red(i18n.t("api:officialLoginFailed")));
            }
            break;
          }
          case "custom":
            apiConfig = await handleCustomApiConfiguration(existingApiConfig);
            break;
          case "ccr": {
            const ccrStatus = await isCcrInstalled();
            if (!ccrStatus.hasCorrectPackage) {
              await installCcr();
            } else {
              console.log(a.green(`\u2714 ${i18n.t("ccr:ccrAlreadyInstalled")}`));
            }
            const ccrConfigured = await setupCcrConfiguration(codeToolType);
            if (ccrConfigured) {
              console.log(a.green(`\u2714 ${i18n.t("ccr:ccrSetupComplete")}`));
              apiConfig = null;
            }
            break;
          }
          case "skip":
            apiConfig = null;
            break;
          default:
            console.log(a.yellow(i18n.t("common:cancelled")));
            process__default.exit(0);
        }
      }
    }
    if (["backup", "docs-only", "merge"].includes(action)) {
      const backupDir = backupExistingConfig(codeToolType);
      if (backupDir) {
        console.log(a.gray(`\u2714 ${i18n.t("configuration:backupSuccess")}: ${backupDir}`));
      }
    }
    if (action === "docs-only") {
      copyConfigFiles(true, codeToolType);
      if (options.skipPrompt) {
        if (options.workflows !== false) {
          await selectAndInstallWorkflows(configLang, options.workflows, { codeToolType });
        }
      } else {
        await selectAndInstallWorkflows(configLang, void 0, { codeToolType });
      }
    } else if (["backup", "merge", "new"].includes(action)) {
      copyConfigFiles(false, codeToolType);
      if (options.skipPrompt) {
        if (options.workflows !== false) {
          await selectAndInstallWorkflows(configLang, options.workflows, { codeToolType });
        }
      } else {
        await selectAndInstallWorkflows(configLang, void 0, { codeToolType });
      }
    }
    applyAiLanguageDirective(aiOutputLang, codeToolType);
    if (options.skipPrompt) {
      if (options.outputStyles !== false) {
        await configureOutputStyle(options.outputStyles, options.defaultOutputStyle, codeToolType);
      }
    } else {
      await configureOutputStyle(void 0, void 0, codeToolType);
    }
    if (apiConfig && action !== "docs-only") {
      const configuredApi = configureApi(apiConfig, codeToolType);
      if (configuredApi) {
        console.log(a.green(`\u2714 ${i18n.t("api:apiConfigSuccess")}`));
        console.log(a.gray(`  URL: ${configuredApi.url}`));
        console.log(a.gray(`  Key: ${formatApiKeyDisplay(configuredApi.key)}`));
        if (codeToolType === "clavue") {
          try {
            if (!configuredApi.authType) {
              throw new Error("Configured API is missing authType");
            }
            const profile = await convertSingleConfigToProfile(
              {
                authType: configuredApi.authType,
                key: configuredApi.key,
                url: configuredApi.url
              },
              options.provider,
              {
                apiModel: options.apiModel,
                apiHaikuModel: options.apiHaikuModel,
                apiSonnetModel: options.apiSonnetModel,
                apiOpusModel: options.apiOpusModel
              }
            );
            setMyclaudeProviderProfiles([
              {
                id: profile.id || profile.name,
                name: profile.name,
                provider: options.provider || "custom",
                apiKey: profile.apiKey,
                baseUrl: profile.baseUrl,
                model: profile.primaryModel,
                fastModel: profile.defaultHaikuModel,
                authType: profile.authType,
                primaryModel: profile.primaryModel,
                defaultHaikuModel: profile.defaultHaikuModel,
                defaultSonnetModel: profile.defaultSonnetModel,
                defaultOpusModel: profile.defaultOpusModel
              }
            ], profile.id || profile.name);
          } catch (error) {
            console.log(a.yellow(`\u26A0 Failed to write Clavue provider profile: ${error}`));
          }
        } else if (codeToolType === "claude-code") {
          clearMyclaudeProviderProfiles();
        }
      }
    }
    const hasModelParams = options.apiModel || options.apiHaikuModel || options.apiSonnetModel || options.apiOpusModel;
    if (hasModelParams && action !== "docs-only" && (codeToolType === "claude-code" || codeToolType === "clavue")) {
      if (options.skipPrompt) {
        const { updateCustomModel } = await import('./config.mjs').then(function (n) { return n.k; });
        updateCustomModel(
          options.apiModel || void 0,
          options.apiHaikuModel || void 0,
          options.apiSonnetModel || void 0,
          options.apiOpusModel || void 0,
          codeToolType
        );
        console.log(a.green(`\u2714 ${i18n.t("api:modelConfigSuccess")}`));
        if (options.apiModel) {
          console.log(a.gray(`  ${i18n.t("api:primaryModel")}: ${options.apiModel}`));
        }
        if (options.apiHaikuModel)
          console.log(a.gray(`  Haiku: ${options.apiHaikuModel}`));
        if (options.apiSonnetModel)
          console.log(a.gray(`  Sonnet: ${options.apiSonnetModel}`));
        if (options.apiOpusModel)
          console.log(a.gray(`  Opus: ${options.apiOpusModel}`));
      }
    }
    if (!options.skipPrompt && !options.skipBanner)
      tracker.nextStep("Installing MCP services");
    if (action !== "docs-only") {
      let shouldConfigureMcp = false;
      if (options.skipPrompt) {
        shouldConfigureMcp = options.mcpServices !== false;
      } else {
        const userChoice = await promptBoolean({
          message: i18n.t("mcp:configureMcp"),
          defaultValue: true
        });
        shouldConfigureMcp = userChoice;
      }
      if (shouldConfigureMcp) {
        if (isWindows()) {
          console.log(a.green(`\u2139 ${i18n.t("installation:windowsDetected")}`));
        }
        let selectedServices;
        if (options.skipPrompt) {
          selectedServices = options.mcpServices;
        } else {
          selectedServices = await selectMcpServices();
          if (selectedServices === void 0) {
            process__default.exit(0);
          }
        }
        if (selectedServices.length > 0) {
          const mcpBackupPath = backupMcpConfig(codeToolType);
          if (mcpBackupPath) {
            console.log(a.gray(`\u2714 ${i18n.t("mcp:mcpBackupSuccess")}: ${mcpBackupPath}`));
          }
          const newServers = {};
          for (const serviceId of selectedServices) {
            const services = await getMcpServices();
            const service = services.find((s) => s.id === serviceId);
            if (!service)
              continue;
            let config = service.config;
            if (service.id === "serena" && Array.isArray(config.args)) {
              const adjusted = { ...config, args: [...config.args || []] };
              const idx = adjusted.args.indexOf("--context");
              if (idx >= 0 && idx + 1 < adjusted.args.length) {
                adjusted.args[idx + 1] = codeToolType === "codex" ? "codex" : "ide-assistant";
              } else {
                adjusted.args.push(
                  "--context",
                  codeToolType === "codex" ? "codex" : "ide-assistant"
                );
              }
              config = adjusted;
            }
            if (service.requiresApiKey) {
              if (options.skipPrompt) {
                console.log(
                  a.yellow(`${i18n.t("common:skip")}: ${service.name} (requires API key)`)
                );
                continue;
              } else {
                const response = await inquirer.prompt({
                  type: "input",
                  name: "apiKey",
                  message: service.apiKeyPrompt,
                  validate: (value) => !!value || i18n.t("api:keyRequired")
                });
                if (!response.apiKey) {
                  console.log(a.yellow(`${i18n.t("common:skip")}: ${service.name}`));
                  continue;
                }
                config = buildMcpServerConfig(
                  service.config,
                  response.apiKey,
                  service.apiKeyPlaceholder,
                  service.apiKeyEnvVar
                );
              }
            }
            newServers[service.id] = config;
          }
          const existingConfig = readMcpConfig(codeToolType);
          let mergedConfig = replaceMcpServers(existingConfig, newServers);
          mergedConfig = fixWindowsMcpConfig(mergedConfig);
          try {
            writeMcpConfig(mergedConfig, codeToolType);
            syncMcpPermissions(codeToolType);
            console.log(a.green(`\u2714 ${i18n.t("mcp:mcpConfigSuccess")}`));
            const { checkMcpPerformance, formatPerformanceWarning } = await import('./mcp-performance.mjs').then(function (n) { return n.e; });
            const serviceCount = Object.keys(newServers).length;
            const perfWarning = checkMcpPerformance(serviceCount);
            if (perfWarning) {
              console.log("");
              console.log(formatPerformanceWarning(perfWarning, i18n.language));
            }
          } catch (error) {
            displayError(error, "MCP configuration");
          }
        }
      }
    }
    const cometixInstalled = await isCometixLineInstalled();
    if (!cometixInstalled) {
      let shouldInstallCometix = false;
      if (options.skipPrompt) {
        shouldInstallCometix = options.installCometixLine !== false;
      } else {
        const userChoice = await promptBoolean({
          message: i18n.t("cometix:installCometixPrompt"),
          defaultValue: true
        });
        shouldInstallCometix = userChoice;
      }
      if (shouldInstallCometix) {
        await installCometixLine();
      } else {
        console.log(a.yellow(i18n.t("cometix:cometixSkipped")));
      }
    } else {
      console.log(a.green(`\u2714 ${i18n.t("cometix:cometixAlreadyInstalled")}`));
    }
    if (!options.skipPrompt || options.installSuperpowers) {
      await handleSuperpowersInstallation(options);
    }
    let agentBrowserReady = false;
    try {
      const isZh = i18n.language === "zh-CN";
      let shouldInstallAgentBrowser = false;
      if (options.skipPrompt) {
        shouldInstallAgentBrowser = options.installAgentBrowser !== false;
      } else {
        shouldInstallAgentBrowser = await promptBoolean({
          message: isZh ? "\u5B89\u88C5 Agent Browser \u6D4F\u89C8\u5668\u81EA\u52A8\u5316\u6A21\u5757\uFF1F\uFF08\u63A8\u8350\uFF0C\u6D4F\u89C8\u5668\u4EFB\u52A1\u53EF\u65E0\u7F1D\u4F7F\u7528\uFF09" : "Install Agent Browser module? (recommended for seamless browser automation)",
          defaultValue: true
        });
      }
      if (shouldInstallAgentBrowser) {
        const { checkAgentBrowserInstalled, installAgentBrowser } = await import('./installer2.mjs');
        const installed = await checkAgentBrowserInstalled();
        const success = installed ? true : await installAgentBrowser();
        if (success) {
          const { addSkill } = await import('./manager.mjs');
          const { browserSkill } = await import('./skill.mjs');
          addSkill(browserSkill);
          agentBrowserReady = true;
          console.log(
            a.green(
              `\u2714 ${isZh ? "Agent Browser \u5DF2\u5C31\u7EEA\uFF0C\u6D4F\u89C8\u5668 Skill \u5DF2\u542F\u7528" : "Agent Browser ready, browser skill enabled"}`
            )
          );
          console.log(
            a.gray(
              `  ${isZh ? "\u53EF\u76F4\u63A5\u4F7F\u7528:" : "Use directly:"} ccjk browser start https://example.com`
            )
          );
        }
      } else {
        console.log(
          a.yellow(
            isZh ? "\u26A0 \u5DF2\u8DF3\u8FC7 Agent Browser \u5B89\u88C5" : "\u26A0 Agent Browser installation skipped"
          )
        );
      }
    } catch (error) {
      const msg = error instanceof Error ? error.message : String(error);
      console.log(a.gray(`\u2139 Agent Browser setup skipped: ${msg}`));
    }
    try {
      const { injectSmartGuide } = await import('./smart-guide.mjs');
      const smartGuideSuccess = await injectSmartGuide(configLang, codeToolType);
      if (smartGuideSuccess) {
        console.log(a.green(`\u2714 ${i18n.t("smartGuide:enabled")}`));
      }
    } catch {
      console.log(a.gray(`\u2139 ${i18n.t("smartGuide:skipped")}`));
    }
    try {
      const finalOrchestrationLevel = parseOrchestrationLevel(options.orchestration);
      const policyPath = writeOrchestrationPolicy({
        level: finalOrchestrationLevel,
        language: configLang,
        source: options.initSource
      });
      console.log(
        a.green(`\u2714 Workflow orchestration: ${finalOrchestrationLevel} (${policyPath})`)
      );
    } catch (error) {
      const msg = error instanceof Error ? error.message : String(error);
      console.log(a.gray(`\u2139 Workflow orchestration skipped: ${msg}`));
    }
    if (!options.skipPrompt && !options.skipBanner)
      tracker.nextStep("Finalizing setup");
    updateZcfConfig({
      version: ccjkVersion,
      preferredLang: i18n.language,
      // CCJK界面语言
      templateLang: configLang,
      // 模板语言
      aiOutputLang,
      codeToolType
    });
    const defaultArchetype = getDefaultArchetypeProfile(codeToolType);
    const runtimeDistribution = codeToolType === "clavue" ? "clavue" : codeToolType === "claude-code" ? "claude-code" : "generic";
    updateTomlConfig(ZCF_CONFIG_FILE, {
      adaptation: {
        runtimeProfile: {
          target: codeToolType,
          distribution: runtimeDistribution,
          compatMode: codeToolType === "clavue" ? "native" : "compatible",
          providerStrategy: codeToolType === "clavue" ? "profile-based" : "env-based"
        },
        archetypeProfile: defaultArchetype,
        capabilityProfile: {
          coding: true,
          planning: true,
          taskTracking: true,
          memory: true,
          browserAutomation: false,
          research: true,
          documentAuthoring: false,
          serviceOps: false,
          multiAgent: codeToolType === "clavue"
        },
        policyProfile: {
          permissionPreset: "dev",
          verificationMode: "required",
          destructiveActionPolicy: "confirm",
          workflowFallbackMode: "graceful"
        },
        contextProfile: {
          memoryMode: "project-aware",
          compressionMode: "runtime-native",
          instructionLayering: "runtime-first"
        },
        profileSelection: {
          workflowPack: "desktop-engineering",
          toolPack: "typescript-node-react"
        },
        uiProfile: {
          language: configLang,
          outputStyle: "concise",
          operatorMode: "execution-first"
        }
      }
    });
    if (!options.skipPrompt) {
      const { importRecommendedEnv, importRecommendedPermissions } = await import('./simple-config.mjs');
      const confirmImport = await promptBoolean({
        message: i18n.t("configuration:recommendImportEnvPerm") || "\u5BFC\u5165 CCJK \u63A8\u8350\u7684\u73AF\u5883\u53D8\u91CF\u548C\u6743\u9650\u914D\u7F6E\uFF1F\uFF08\u63A8\u8350\uFF0C\u53EF\u51CF\u5C11\u6743\u9650\u5F39\u7A97\uFF09",
        defaultValue: true
      });
      if (confirmImport) {
        try {
          await importRecommendedEnv();
          console.log(a.green(`\u2714 ${i18n.t("configuration:envImportSuccess")}`));
        } catch (error) {
          console.error(a.yellow(`\u26A0 ${i18n.t("configuration:envImportFailed")}: ${error}`));
        }
        try {
          await importRecommendedPermissions();
          console.log(
            a.green(`\u2714 ${i18n.t("configuration:permissionsImportSuccess") || "\u6743\u9650\u914D\u7F6E\u5DF2\u5BFC\u5165"}`)
          );
        } catch (error) {
          console.error(
            a.yellow(`\u26A0 ${i18n.t("configuration:permissionsImportFailed")}: ${error}`)
          );
        }
        console.log();
      }
    }
    if (!options.skipPrompt && !options.skipBanner)
      tracker.complete();
    const completionGuidance = getSetupCompletionGuidance(codeToolType);
    console.log("");
    console.log(
      a.bold.green("\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557")
    );
    console.log(
      a.bold.green("\u2551") + a.bold.white(padToDisplayWidth(`  ${i18n.t("configuration:setupCompleteTitle")}`, 62)) + a.bold.green("\u2551")
    );
    console.log(
      a.bold.green("\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563")
    );
    console.log(
      `${a.bold.green("\u2551")}                                                              ${a.bold.green("\u2551")}`
    );
    console.log(
      a.bold.green("\u2551") + a.green(padToDisplayWidth(`  ${i18n.t("configuration:nextSteps")}`, 62)) + a.bold.green("\u2551")
    );
    console.log(
      `${a.bold.green("\u2551")}                                                              ${a.bold.green("\u2551")}`
    );
    console.log(
      a.bold.green("\u2551") + padToDisplayWidth(`  ${completionGuidance.step1}`, 62) + a.bold.green("\u2551")
    );
    console.log(
      a.bold.green("\u2551") + a.dim(padToDisplayWidth(`     ${completionGuidance.step1Detail}`, 62)) + a.bold.green("\u2551")
    );
    console.log(
      a.bold.green("\u2551") + a.dim(padToDisplayWidth(`     ${completionGuidance.step1Detail2}`, 62)) + a.bold.green("\u2551")
    );
    console.log(
      `${a.bold.green("\u2551")}                                                              ${a.bold.green("\u2551")}`
    );
    console.log(
      a.bold.green("\u2551") + padToDisplayWidth(`  ${completionGuidance.step2}`, 62) + a.bold.green("\u2551")
    );
    console.log(
      a.bold.green("\u2551") + a.green(padToDisplayWidth(`     ${completionGuidance.step2Example}`, 62)) + a.bold.green("\u2551")
    );
    console.log(
      `${a.bold.green("\u2551")}                                                              ${a.bold.green("\u2551")}`
    );
    console.log(
      a.bold.green("\u2551") + padToDisplayWidth(`  ${completionGuidance.step3} `, 44) + a.yellow(padToDisplayWidth(completionGuidance.step3Command, 18)) + a.bold.green("\u2551")
    );
    console.log(
      a.bold.green("\u2551") + padToDisplayWidth(`  ${completionGuidance.step4} `, 44) + a.yellow(padToDisplayWidth(completionGuidance.step4Command, 18)) + a.bold.green("\u2551")
    );
    console.log(
      a.bold.green("\u2551") + padToDisplayWidth(`  ${completionGuidance.step5} `, 44) + a.yellow(padToDisplayWidth(completionGuidance.step5Command, 18)) + a.bold.green("\u2551")
    );
    console.log(
      `${a.bold.green("\u2551")}                                                              ${a.bold.green("\u2551")}`
    );
    console.log(
      a.bold.green("\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D")
    );
    if (isNewInstall || ["backup", "merge", "new"].includes(action)) {
      const isZh = i18n.language === "zh-CN";
      console.log(
        a.cyan(
          isZh ? "\u{1F9E0} \u4E0A\u4E0B\u6587\u4F18\u5316\u5DF2\u542F\u7528\uFF08\u9ED8\u8BA4\uFF09" : "\u{1F9E0} Context optimization is enabled (default)"
        )
      );
      console.log(
        a.dim(
          isZh ? "   \u5EFA\u8BAE\u7ACB\u5373\u8FD0\u884C: ccjk morning  \u67E5\u770B\u5065\u5EB7\u5206\u4E0E\u6536\u76CA\u6458\u8981" : "   Recommended now: ccjk morning  to view health score and value summary"
        )
      );
      console.log(
        a.dim(
          isZh ? "   \u6DF1\u5EA6\u590D\u76D8: ccjk review  | \u4E0A\u4E0B\u6587\u8BE6\u60C5: ccjk context --show" : "   Deep review: ccjk review  | Context details: ccjk context --show"
        )
      );
      if (agentBrowserReady) {
        console.log(
          a.cyan(
            isZh ? "\u{1F310} \u6D4F\u89C8\u5668\u81EA\u52A8\u5316\u5DF2\u5C31\u7EEA\uFF08\u65E0\u7F1D\uFF09" : "\u{1F310} Browser automation is ready (seamless)"
          )
        );
        console.log(
          a.dim(
            isZh ? "   \u76F4\u63A5\u5F00\u59CB: ccjk browser start https://example.com" : "   Start directly: ccjk browser start https://example.com"
          )
        );
        console.log(
          a.dim(
            isZh ? "   \u5E38\u7528\u64CD\u4F5C: ccjk browser status  |  ccjk browser stop" : "   Common actions: ccjk browser status  |  ccjk browser stop"
          )
        );
      }
    }
    console.log("");
  } catch (error) {
    if (!handleExitPromptError(error)) {
      displayError(error, "Initialization");
      handleGeneralError(error);
    }
  }
}

const init$1 = {
  __proto__: null,
  convertSingleConfigToProfile: convertSingleConfigToProfile,
  getSetupCompletionGuidance: getSetupCompletionGuidance,
  handleMultiConfigurations: handleMultiConfigurations,
  init: init,
  saveSingleConfigToToml: saveSingleConfigToToml,
  silentInit: silentInit,
  smartInit: smartInit,
  validateApiConfigs: validateApiConfigs,
  validateSkipPromptOptions: validateSkipPromptOptions
};

export { COMETIX_COMMAND_NAME as C, COMETIX_COMMANDS as a, installCometixLine as b, init$1 as c, init as i };
