import { St as loadSKYKOIPlugins } from "./reply-Bnpxcafr.js";
import { t as createSubsystemLogger } from "./subsystem-hATE68va.js";
import { l as normalizeKoiId } from "./session-key-B2OXLVi_.js";
import { b as sleep } from "./utils-D019Z2NU.js";
import { n as listKoiIds } from "./koi-scope-je0O-Kk9.js";
import { A as SYNTHETIC_BASE_URL, Ct as DEFAULT_PROVIDER, D as VENICE_DEFAULT_MODEL_REF, E as VENICE_BASE_URL, F as buildCloudflareAiGatewayModelDefinition, I as resolveCloudflareAiGatewayBaseUrl, M as SYNTHETIC_MODEL_CATALOG, N as buildSyntheticModelDefinition, O as VENICE_MODEL_CATALOG, P as CLOUDFLARE_AI_GATEWAY_DEFAULT_MODEL_REF, _ as QIANFAN_DEFAULT_MODEL_ID, at as upsertAuthProfile, b as buildXiaomiProvider, dt as resolveSKYKOIKoiDir, g as QIANFAN_BASE_URL, j as SYNTHETIC_DEFAULT_MODEL_REF, k as buildVeniceModelDefinition, m as resolveModelRefFromString, ot as ensureAuthProfileStore, r as buildModelAliasIndex, s as normalizeProviderId, v as XIAOMI_DEFAULT_MODEL_ID, y as buildQianfanProvider } from "./model-selection-DHqY0wuU.js";
import { t as formatCliCommand } from "./command-format-DOYW_19_.js";
import { c as readConfigFileSnapshot, u as writeConfigFile } from "./config-ZjEd8561.js";
import { n as isWSLEnv } from "./wsl-HoIhaCSz.js";
import { r as stylePromptTitle } from "./prompt-style-hXUwxLRe.js";
import { n as logConfigUpdated } from "./logging-CSvbGeqF.js";
import { intro, note, outro, spinner } from "@clack/prompts";

//#region src/commands/auth-token.ts
const ANTHROPIC_SETUP_TOKEN_PREFIX = "sk-ant-oat01-";
const ANTHROPIC_SETUP_TOKEN_MIN_LENGTH = 80;
const DEFAULT_TOKEN_PROFILE_NAME = "default";
function normalizeTokenProfileName(raw) {
	const trimmed = raw.trim();
	if (!trimmed) return DEFAULT_TOKEN_PROFILE_NAME;
	return trimmed.toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/-+/g, "-").replace(/^-+|-+$/g, "") || DEFAULT_TOKEN_PROFILE_NAME;
}
function buildTokenProfileId(params) {
	return `${normalizeProviderId(params.provider)}:${normalizeTokenProfileName(params.name)}`;
}
function validateAnthropicSetupToken(raw) {
	const trimmed = raw.trim();
	if (!trimmed) return "Required";
	if (!trimmed.startsWith(ANTHROPIC_SETUP_TOKEN_PREFIX)) return `Expected token starting with ${ANTHROPIC_SETUP_TOKEN_PREFIX}`;
	if (trimmed.length < ANTHROPIC_SETUP_TOKEN_MIN_LENGTH) return "Token looks too short; paste the full setup-token";
}

//#endregion
//#region src/commands/onboard-auth.models.ts
const MINIMAX_API_BASE_URL = "https://api.minimax.io/anthropic";
const MINIMAX_HOSTED_MODEL_ID = "MiniMax-M2.1";
const MINIMAX_HOSTED_MODEL_REF = `minimax/${MINIMAX_HOSTED_MODEL_ID}`;
const DEFAULT_MINIMAX_CONTEXT_WINDOW = 2e5;
const DEFAULT_MINIMAX_MAX_TOKENS = 8192;
const MOONSHOT_BASE_URL = "https://api.moonshot.ai/v1";
const MOONSHOT_CN_BASE_URL = "https://api.moonshot.cn/v1";
const MOONSHOT_DEFAULT_MODEL_ID = "kimi-k2.5";
const MOONSHOT_DEFAULT_MODEL_REF = `moonshot/${MOONSHOT_DEFAULT_MODEL_ID}`;
const MOONSHOT_DEFAULT_CONTEXT_WINDOW = 256e3;
const MOONSHOT_DEFAULT_MAX_TOKENS = 8192;
const KIMI_CODING_MODEL_ID = "k2p5";
const KIMI_CODING_MODEL_REF = `kimi-coding/${KIMI_CODING_MODEL_ID}`;
const QIANFAN_DEFAULT_MODEL_REF = `qianfan/${QIANFAN_DEFAULT_MODEL_ID}`;
const MINIMAX_API_COST = {
	input: 15,
	output: 60,
	cacheRead: 2,
	cacheWrite: 10
};
const MINIMAX_LM_STUDIO_COST = {
	input: 0,
	output: 0,
	cacheRead: 0,
	cacheWrite: 0
};
const MOONSHOT_DEFAULT_COST = {
	input: 0,
	output: 0,
	cacheRead: 0,
	cacheWrite: 0
};
const MINIMAX_MODEL_CATALOG = {
	"MiniMax-M2.1": {
		name: "MiniMax M2.1",
		reasoning: false
	},
	"MiniMax-M2.1-lightning": {
		name: "MiniMax M2.1 Lightning",
		reasoning: false
	}
};
function buildMinimaxModelDefinition(params) {
	const catalog = MINIMAX_MODEL_CATALOG[params.id];
	return {
		id: params.id,
		name: params.name ?? catalog?.name ?? `MiniMax ${params.id}`,
		reasoning: params.reasoning ?? catalog?.reasoning ?? false,
		input: ["text"],
		cost: params.cost,
		contextWindow: params.contextWindow,
		maxTokens: params.maxTokens
	};
}
function buildMinimaxApiModelDefinition(modelId) {
	return buildMinimaxModelDefinition({
		id: modelId,
		cost: MINIMAX_API_COST,
		contextWindow: DEFAULT_MINIMAX_CONTEXT_WINDOW,
		maxTokens: DEFAULT_MINIMAX_MAX_TOKENS
	});
}
function buildMoonshotModelDefinition() {
	return {
		id: MOONSHOT_DEFAULT_MODEL_ID,
		name: "Kimi K2.5",
		reasoning: false,
		input: ["text"],
		cost: MOONSHOT_DEFAULT_COST,
		contextWindow: MOONSHOT_DEFAULT_CONTEXT_WINDOW,
		maxTokens: MOONSHOT_DEFAULT_MAX_TOKENS
	};
}
const XAI_BASE_URL = "https://api.x.ai/v1";
const XAI_DEFAULT_MODEL_ID = "grok-4";
const XAI_DEFAULT_MODEL_REF = `xai/${XAI_DEFAULT_MODEL_ID}`;
const XAI_DEFAULT_CONTEXT_WINDOW = 131072;
const XAI_DEFAULT_MAX_TOKENS = 8192;
const XAI_DEFAULT_COST = {
	input: 0,
	output: 0,
	cacheRead: 0,
	cacheWrite: 0
};
function buildXaiModelDefinition() {
	return {
		id: XAI_DEFAULT_MODEL_ID,
		name: "Grok 4",
		reasoning: false,
		input: ["text"],
		cost: XAI_DEFAULT_COST,
		contextWindow: XAI_DEFAULT_CONTEXT_WINDOW,
		maxTokens: XAI_DEFAULT_MAX_TOKENS
	};
}

//#endregion
//#region src/commands/onboard-auth.credentials.ts
const resolveAuthKoiDir = (koiDir) => koiDir ?? resolveSKYKOIKoiDir();
async function writeOAuthCredentials(provider, creds, koiDir) {
	upsertAuthProfile({
		profileId: `${provider}:${typeof creds.email === "string" && creds.email.trim() ? creds.email.trim() : "default"}`,
		credential: {
			type: "oauth",
			provider,
			...creds
		},
		koiDir: resolveAuthKoiDir(koiDir)
	});
}
async function setAnthropicApiKey(key, koiDir) {
	upsertAuthProfile({
		profileId: "anthropic:default",
		credential: {
			type: "api_key",
			provider: "anthropic",
			key
		},
		koiDir: resolveAuthKoiDir(koiDir)
	});
}
async function setGeminiApiKey(key, koiDir) {
	upsertAuthProfile({
		profileId: "google:default",
		credential: {
			type: "api_key",
			provider: "google",
			key
		},
		koiDir: resolveAuthKoiDir(koiDir)
	});
}
async function setMinimaxApiKey(key, koiDir) {
	upsertAuthProfile({
		profileId: "minimax:default",
		credential: {
			type: "api_key",
			provider: "minimax",
			key
		},
		koiDir: resolveAuthKoiDir(koiDir)
	});
}
async function setMoonshotApiKey(key, koiDir) {
	upsertAuthProfile({
		profileId: "moonshot:default",
		credential: {
			type: "api_key",
			provider: "moonshot",
			key
		},
		koiDir: resolveAuthKoiDir(koiDir)
	});
}
async function setKimiCodingApiKey(key, koiDir) {
	upsertAuthProfile({
		profileId: "kimi-coding:default",
		credential: {
			type: "api_key",
			provider: "kimi-coding",
			key
		},
		koiDir: resolveAuthKoiDir(koiDir)
	});
}
async function setSyntheticApiKey(key, koiDir) {
	upsertAuthProfile({
		profileId: "synthetic:default",
		credential: {
			type: "api_key",
			provider: "synthetic",
			key
		},
		koiDir: resolveAuthKoiDir(koiDir)
	});
}
async function setVeniceApiKey(key, koiDir) {
	upsertAuthProfile({
		profileId: "venice:default",
		credential: {
			type: "api_key",
			provider: "venice",
			key
		},
		koiDir: resolveAuthKoiDir(koiDir)
	});
}
const ZAI_DEFAULT_MODEL_REF = "zai/glm-4.7";
const XIAOMI_DEFAULT_MODEL_REF = "xiaomi/mimo-v2-flash";
const OPENROUTER_DEFAULT_MODEL_REF = "openrouter/auto";
const VERCEL_AI_GATEWAY_DEFAULT_MODEL_REF = "vercel-ai-gateway/anthropic/claude-opus-4.6";
async function setZaiApiKey(key, koiDir) {
	upsertAuthProfile({
		profileId: "zai:default",
		credential: {
			type: "api_key",
			provider: "zai",
			key
		},
		koiDir: resolveAuthKoiDir(koiDir)
	});
}
async function setXiaomiApiKey(key, koiDir) {
	upsertAuthProfile({
		profileId: "xiaomi:default",
		credential: {
			type: "api_key",
			provider: "xiaomi",
			key
		},
		koiDir: resolveAuthKoiDir(koiDir)
	});
}
async function setOpenrouterApiKey(key, koiDir) {
	upsertAuthProfile({
		profileId: "openrouter:default",
		credential: {
			type: "api_key",
			provider: "openrouter",
			key
		},
		koiDir: resolveAuthKoiDir(koiDir)
	});
}
async function setCloudflareAiGatewayConfig(accountId, gatewayId, apiKey, koiDir) {
	const normalizedAccountId = accountId.trim();
	const normalizedGatewayId = gatewayId.trim();
	upsertAuthProfile({
		profileId: "cloudflare-ai-gateway:default",
		credential: {
			type: "api_key",
			provider: "cloudflare-ai-gateway",
			key: apiKey.trim(),
			metadata: {
				accountId: normalizedAccountId,
				gatewayId: normalizedGatewayId
			}
		},
		koiDir: resolveAuthKoiDir(koiDir)
	});
}
async function setVercelAiGatewayApiKey(key, koiDir) {
	upsertAuthProfile({
		profileId: "vercel-ai-gateway:default",
		credential: {
			type: "api_key",
			provider: "vercel-ai-gateway",
			key
		},
		koiDir: resolveAuthKoiDir(koiDir)
	});
}
async function setOpencodeZenApiKey(key, koiDir) {
	upsertAuthProfile({
		profileId: "opencode:default",
		credential: {
			type: "api_key",
			provider: "opencode",
			key
		},
		koiDir: resolveAuthKoiDir(koiDir)
	});
}
function setQianfanApiKey(key, koiDir) {
	upsertAuthProfile({
		profileId: "qianfan:default",
		credential: {
			type: "api_key",
			provider: "qianfan",
			key
		},
		koiDir: resolveAuthKoiDir(koiDir)
	});
}
function setXaiApiKey(key, koiDir) {
	upsertAuthProfile({
		profileId: "xai:default",
		credential: {
			type: "api_key",
			provider: "xai",
			key
		},
		koiDir: resolveAuthKoiDir(koiDir)
	});
}

//#endregion
//#region src/commands/onboard-auth.config-core.ts
function applyZaiConfig(cfg) {
	const models = { ...cfg.kois?.defaults?.models };
	models[ZAI_DEFAULT_MODEL_REF] = {
		...models[ZAI_DEFAULT_MODEL_REF],
		alias: models[ZAI_DEFAULT_MODEL_REF]?.alias ?? "GLM"
	};
	const existingModel = cfg.kois?.defaults?.model;
	return {
		...cfg,
		kois: {
			...cfg.kois,
			defaults: {
				...cfg.kois?.defaults,
				models,
				model: {
					...existingModel && "fallbacks" in existingModel ? { fallbacks: existingModel.fallbacks } : void 0,
					primary: ZAI_DEFAULT_MODEL_REF
				}
			}
		}
	};
}
function applyOpenrouterProviderConfig(cfg) {
	const models = { ...cfg.kois?.defaults?.models };
	models[OPENROUTER_DEFAULT_MODEL_REF] = {
		...models[OPENROUTER_DEFAULT_MODEL_REF],
		alias: models[OPENROUTER_DEFAULT_MODEL_REF]?.alias ?? "OpenRouter"
	};
	return {
		...cfg,
		kois: {
			...cfg.kois,
			defaults: {
				...cfg.kois?.defaults,
				models
			}
		}
	};
}
function applyVercelAiGatewayProviderConfig(cfg) {
	const models = { ...cfg.kois?.defaults?.models };
	models[VERCEL_AI_GATEWAY_DEFAULT_MODEL_REF] = {
		...models[VERCEL_AI_GATEWAY_DEFAULT_MODEL_REF],
		alias: models[VERCEL_AI_GATEWAY_DEFAULT_MODEL_REF]?.alias ?? "Vercel AI Gateway"
	};
	return {
		...cfg,
		kois: {
			...cfg.kois,
			defaults: {
				...cfg.kois?.defaults,
				models
			}
		}
	};
}
function applyCloudflareAiGatewayProviderConfig(cfg, params) {
	const models = { ...cfg.kois?.defaults?.models };
	models[CLOUDFLARE_AI_GATEWAY_DEFAULT_MODEL_REF] = {
		...models[CLOUDFLARE_AI_GATEWAY_DEFAULT_MODEL_REF],
		alias: models[CLOUDFLARE_AI_GATEWAY_DEFAULT_MODEL_REF]?.alias ?? "Cloudflare AI Gateway"
	};
	const providers = { ...cfg.models?.providers };
	const existingProvider = providers["cloudflare-ai-gateway"];
	const existingModels = Array.isArray(existingProvider?.models) ? existingProvider.models : [];
	const defaultModel = buildCloudflareAiGatewayModelDefinition();
	const mergedModels = existingModels.some((model) => model.id === defaultModel.id) ? existingModels : [...existingModels, defaultModel];
	const baseUrl = params?.accountId && params?.gatewayId ? resolveCloudflareAiGatewayBaseUrl({
		accountId: params.accountId,
		gatewayId: params.gatewayId
	}) : existingProvider?.baseUrl;
	if (!baseUrl) return {
		...cfg,
		kois: {
			...cfg.kois,
			defaults: {
				...cfg.kois?.defaults,
				models
			}
		}
	};
	const { apiKey: existingApiKey, ...existingProviderRest } = existingProvider ?? {};
	const normalizedApiKey = (typeof existingApiKey === "string" ? existingApiKey : void 0)?.trim();
	providers["cloudflare-ai-gateway"] = {
		...existingProviderRest,
		baseUrl,
		api: "anthropic-messages",
		...normalizedApiKey ? { apiKey: normalizedApiKey } : {},
		models: mergedModels.length > 0 ? mergedModels : [defaultModel]
	};
	return {
		...cfg,
		kois: {
			...cfg.kois,
			defaults: {
				...cfg.kois?.defaults,
				models
			}
		},
		models: {
			mode: cfg.models?.mode ?? "merge",
			providers
		}
	};
}
function applyVercelAiGatewayConfig(cfg) {
	const next = applyVercelAiGatewayProviderConfig(cfg);
	const existingModel = next.kois?.defaults?.model;
	return {
		...next,
		kois: {
			...next.kois,
			defaults: {
				...next.kois?.defaults,
				model: {
					...existingModel && "fallbacks" in existingModel ? { fallbacks: existingModel.fallbacks } : void 0,
					primary: VERCEL_AI_GATEWAY_DEFAULT_MODEL_REF
				}
			}
		}
	};
}
function applyCloudflareAiGatewayConfig(cfg, params) {
	const next = applyCloudflareAiGatewayProviderConfig(cfg, params);
	const existingModel = next.kois?.defaults?.model;
	return {
		...next,
		kois: {
			...next.kois,
			defaults: {
				...next.kois?.defaults,
				model: {
					...existingModel && "fallbacks" in existingModel ? { fallbacks: existingModel.fallbacks } : void 0,
					primary: CLOUDFLARE_AI_GATEWAY_DEFAULT_MODEL_REF
				}
			}
		}
	};
}
function applyOpenrouterConfig(cfg) {
	const next = applyOpenrouterProviderConfig(cfg);
	const existingModel = next.kois?.defaults?.model;
	return {
		...next,
		kois: {
			...next.kois,
			defaults: {
				...next.kois?.defaults,
				model: {
					...existingModel && "fallbacks" in existingModel ? { fallbacks: existingModel.fallbacks } : void 0,
					primary: OPENROUTER_DEFAULT_MODEL_REF
				}
			}
		}
	};
}
function applyMoonshotProviderConfig(cfg) {
	return applyMoonshotProviderConfigWithBaseUrl(cfg, MOONSHOT_BASE_URL);
}
function applyMoonshotProviderConfigCn(cfg) {
	return applyMoonshotProviderConfigWithBaseUrl(cfg, MOONSHOT_CN_BASE_URL);
}
function applyMoonshotProviderConfigWithBaseUrl(cfg, baseUrl) {
	const models = { ...cfg.kois?.defaults?.models };
	models[MOONSHOT_DEFAULT_MODEL_REF] = {
		...models[MOONSHOT_DEFAULT_MODEL_REF],
		alias: models[MOONSHOT_DEFAULT_MODEL_REF]?.alias ?? "Kimi"
	};
	const providers = { ...cfg.models?.providers };
	const existingProvider = providers.moonshot;
	const existingModels = Array.isArray(existingProvider?.models) ? existingProvider.models : [];
	const defaultModel = buildMoonshotModelDefinition();
	const mergedModels = existingModels.some((model) => model.id === MOONSHOT_DEFAULT_MODEL_ID) ? existingModels : [...existingModels, defaultModel];
	const { apiKey: existingApiKey, ...existingProviderRest } = existingProvider ?? {};
	const normalizedApiKey = (typeof existingApiKey === "string" ? existingApiKey : void 0)?.trim();
	providers.moonshot = {
		...existingProviderRest,
		baseUrl,
		api: "openai-completions",
		...normalizedApiKey ? { apiKey: normalizedApiKey } : {},
		models: mergedModels.length > 0 ? mergedModels : [defaultModel]
	};
	return {
		...cfg,
		kois: {
			...cfg.kois,
			defaults: {
				...cfg.kois?.defaults,
				models
			}
		},
		models: {
			mode: cfg.models?.mode ?? "merge",
			providers
		}
	};
}
function applyMoonshotConfig(cfg) {
	const next = applyMoonshotProviderConfig(cfg);
	const existingModel = next.kois?.defaults?.model;
	return {
		...next,
		kois: {
			...next.kois,
			defaults: {
				...next.kois?.defaults,
				model: {
					...existingModel && "fallbacks" in existingModel ? { fallbacks: existingModel.fallbacks } : void 0,
					primary: MOONSHOT_DEFAULT_MODEL_REF
				}
			}
		}
	};
}
function applyMoonshotConfigCn(cfg) {
	const next = applyMoonshotProviderConfigCn(cfg);
	const existingModel = next.kois?.defaults?.model;
	return {
		...next,
		kois: {
			...next.kois,
			defaults: {
				...next.kois?.defaults,
				model: {
					...existingModel && "fallbacks" in existingModel ? { fallbacks: existingModel.fallbacks } : void 0,
					primary: MOONSHOT_DEFAULT_MODEL_REF
				}
			}
		}
	};
}
function applyKimiCodeProviderConfig(cfg) {
	const models = { ...cfg.kois?.defaults?.models };
	models[KIMI_CODING_MODEL_REF] = {
		...models[KIMI_CODING_MODEL_REF],
		alias: models[KIMI_CODING_MODEL_REF]?.alias ?? "Kimi K2.5"
	};
	return {
		...cfg,
		kois: {
			...cfg.kois,
			defaults: {
				...cfg.kois?.defaults,
				models
			}
		}
	};
}
function applyKimiCodeConfig(cfg) {
	const next = applyKimiCodeProviderConfig(cfg);
	const existingModel = next.kois?.defaults?.model;
	return {
		...next,
		kois: {
			...next.kois,
			defaults: {
				...next.kois?.defaults,
				model: {
					...existingModel && "fallbacks" in existingModel ? { fallbacks: existingModel.fallbacks } : void 0,
					primary: KIMI_CODING_MODEL_REF
				}
			}
		}
	};
}
function applySyntheticProviderConfig(cfg) {
	const models = { ...cfg.kois?.defaults?.models };
	models[SYNTHETIC_DEFAULT_MODEL_REF] = {
		...models[SYNTHETIC_DEFAULT_MODEL_REF],
		alias: models[SYNTHETIC_DEFAULT_MODEL_REF]?.alias ?? "MiniMax M2.1"
	};
	const providers = { ...cfg.models?.providers };
	const existingProvider = providers.synthetic;
	const existingModels = Array.isArray(existingProvider?.models) ? existingProvider.models : [];
	const syntheticModels = SYNTHETIC_MODEL_CATALOG.map(buildSyntheticModelDefinition);
	const mergedModels = [...existingModels, ...syntheticModels.filter((model) => !existingModels.some((existing) => existing.id === model.id))];
	const { apiKey: existingApiKey, ...existingProviderRest } = existingProvider ?? {};
	const normalizedApiKey = (typeof existingApiKey === "string" ? existingApiKey : void 0)?.trim();
	providers.synthetic = {
		...existingProviderRest,
		baseUrl: SYNTHETIC_BASE_URL,
		api: "anthropic-messages",
		...normalizedApiKey ? { apiKey: normalizedApiKey } : {},
		models: mergedModels.length > 0 ? mergedModels : syntheticModels
	};
	return {
		...cfg,
		kois: {
			...cfg.kois,
			defaults: {
				...cfg.kois?.defaults,
				models
			}
		},
		models: {
			mode: cfg.models?.mode ?? "merge",
			providers
		}
	};
}
function applySyntheticConfig(cfg) {
	const next = applySyntheticProviderConfig(cfg);
	const existingModel = next.kois?.defaults?.model;
	return {
		...next,
		kois: {
			...next.kois,
			defaults: {
				...next.kois?.defaults,
				model: {
					...existingModel && "fallbacks" in existingModel ? { fallbacks: existingModel.fallbacks } : void 0,
					primary: SYNTHETIC_DEFAULT_MODEL_REF
				}
			}
		}
	};
}
function applyXiaomiProviderConfig(cfg) {
	const models = { ...cfg.kois?.defaults?.models };
	models[XIAOMI_DEFAULT_MODEL_REF] = {
		...models[XIAOMI_DEFAULT_MODEL_REF],
		alias: models[XIAOMI_DEFAULT_MODEL_REF]?.alias ?? "Xiaomi"
	};
	const providers = { ...cfg.models?.providers };
	const existingProvider = providers.xiaomi;
	const defaultProvider = buildXiaomiProvider();
	const existingModels = Array.isArray(existingProvider?.models) ? existingProvider.models : [];
	const defaultModels = defaultProvider.models ?? [];
	const hasDefaultModel = existingModels.some((model) => model.id === XIAOMI_DEFAULT_MODEL_ID);
	const mergedModels = existingModels.length > 0 ? hasDefaultModel ? existingModels : [...existingModels, ...defaultModels] : defaultModels;
	const { apiKey: existingApiKey, ...existingProviderRest } = existingProvider ?? {};
	const normalizedApiKey = (typeof existingApiKey === "string" ? existingApiKey : void 0)?.trim();
	providers.xiaomi = {
		...existingProviderRest,
		baseUrl: defaultProvider.baseUrl,
		api: defaultProvider.api,
		...normalizedApiKey ? { apiKey: normalizedApiKey } : {},
		models: mergedModels.length > 0 ? mergedModels : defaultProvider.models
	};
	return {
		...cfg,
		kois: {
			...cfg.kois,
			defaults: {
				...cfg.kois?.defaults,
				models
			}
		},
		models: {
			mode: cfg.models?.mode ?? "merge",
			providers
		}
	};
}
function applyXiaomiConfig(cfg) {
	const next = applyXiaomiProviderConfig(cfg);
	const existingModel = next.kois?.defaults?.model;
	return {
		...next,
		kois: {
			...next.kois,
			defaults: {
				...next.kois?.defaults,
				model: {
					...existingModel && "fallbacks" in existingModel ? { fallbacks: existingModel.fallbacks } : void 0,
					primary: XIAOMI_DEFAULT_MODEL_REF
				}
			}
		}
	};
}
/**
* Apply Venice provider configuration without changing the default model.
* Registers Venice models and sets up the provider, but preserves existing model selection.
*/
function applyVeniceProviderConfig(cfg) {
	const models = { ...cfg.kois?.defaults?.models };
	models[VENICE_DEFAULT_MODEL_REF] = {
		...models[VENICE_DEFAULT_MODEL_REF],
		alias: models[VENICE_DEFAULT_MODEL_REF]?.alias ?? "Llama 3.3 70B"
	};
	const providers = { ...cfg.models?.providers };
	const existingProvider = providers.venice;
	const existingModels = Array.isArray(existingProvider?.models) ? existingProvider.models : [];
	const veniceModels = VENICE_MODEL_CATALOG.map(buildVeniceModelDefinition);
	const mergedModels = [...existingModels, ...veniceModels.filter((model) => !existingModels.some((existing) => existing.id === model.id))];
	const { apiKey: existingApiKey, ...existingProviderRest } = existingProvider ?? {};
	const normalizedApiKey = (typeof existingApiKey === "string" ? existingApiKey : void 0)?.trim();
	providers.venice = {
		...existingProviderRest,
		baseUrl: VENICE_BASE_URL,
		api: "openai-completions",
		...normalizedApiKey ? { apiKey: normalizedApiKey } : {},
		models: mergedModels.length > 0 ? mergedModels : veniceModels
	};
	return {
		...cfg,
		kois: {
			...cfg.kois,
			defaults: {
				...cfg.kois?.defaults,
				models
			}
		},
		models: {
			mode: cfg.models?.mode ?? "merge",
			providers
		}
	};
}
/**
* Apply Venice provider configuration AND set Venice as the default model.
* Use this when Venice is the primary provider choice during onboarding.
*/
function applyVeniceConfig(cfg) {
	const next = applyVeniceProviderConfig(cfg);
	const existingModel = next.kois?.defaults?.model;
	return {
		...next,
		kois: {
			...next.kois,
			defaults: {
				...next.kois?.defaults,
				model: {
					...existingModel && "fallbacks" in existingModel ? { fallbacks: existingModel.fallbacks } : void 0,
					primary: VENICE_DEFAULT_MODEL_REF
				}
			}
		}
	};
}
function applyXaiProviderConfig(cfg) {
	const models = { ...cfg.kois?.defaults?.models };
	models[XAI_DEFAULT_MODEL_REF] = {
		...models[XAI_DEFAULT_MODEL_REF],
		alias: models[XAI_DEFAULT_MODEL_REF]?.alias ?? "Grok"
	};
	const providers = { ...cfg.models?.providers };
	const existingProvider = providers.xai;
	const existingModels = Array.isArray(existingProvider?.models) ? existingProvider.models : [];
	const defaultModel = buildXaiModelDefinition();
	const mergedModels = existingModels.some((model) => model.id === XAI_DEFAULT_MODEL_ID) ? existingModels : [...existingModels, defaultModel];
	const { apiKey: existingApiKey, ...existingProviderRest } = existingProvider ?? {};
	const normalizedApiKey = (typeof existingApiKey === "string" ? existingApiKey : void 0)?.trim();
	providers.xai = {
		...existingProviderRest,
		baseUrl: XAI_BASE_URL,
		api: "openai-completions",
		...normalizedApiKey ? { apiKey: normalizedApiKey } : {},
		models: mergedModels.length > 0 ? mergedModels : [defaultModel]
	};
	return {
		...cfg,
		kois: {
			...cfg.kois,
			defaults: {
				...cfg.kois?.defaults,
				models
			}
		},
		models: {
			mode: cfg.models?.mode ?? "merge",
			providers
		}
	};
}
function applyXaiConfig(cfg) {
	const next = applyXaiProviderConfig(cfg);
	const existingModel = next.kois?.defaults?.model;
	return {
		...next,
		kois: {
			...next.kois,
			defaults: {
				...next.kois?.defaults,
				model: {
					...existingModel && "fallbacks" in existingModel ? { fallbacks: existingModel.fallbacks } : void 0,
					primary: XAI_DEFAULT_MODEL_REF
				}
			}
		}
	};
}
function applyAuthProfileConfig(cfg, params) {
	const profiles = {
		...cfg.auth?.profiles,
		[params.profileId]: {
			provider: params.provider,
			mode: params.mode,
			...params.email ? { email: params.email } : {}
		}
	};
	const existingProviderOrder = cfg.auth?.order?.[params.provider];
	const preferProfileFirst = params.preferProfileFirst ?? true;
	const reorderedProviderOrder = existingProviderOrder && preferProfileFirst ? [params.profileId, ...existingProviderOrder.filter((profileId) => profileId !== params.profileId)] : existingProviderOrder;
	const order = existingProviderOrder !== void 0 ? {
		...cfg.auth?.order,
		[params.provider]: reorderedProviderOrder?.includes(params.profileId) ? reorderedProviderOrder : [...reorderedProviderOrder ?? [], params.profileId]
	} : cfg.auth?.order;
	return {
		...cfg,
		auth: {
			...cfg.auth,
			profiles,
			...order ? { order } : {}
		}
	};
}
function applyQianfanProviderConfig(cfg) {
	const models = { ...cfg.kois?.defaults?.models };
	models[QIANFAN_DEFAULT_MODEL_REF] = {
		...models[QIANFAN_DEFAULT_MODEL_REF],
		alias: models[QIANFAN_DEFAULT_MODEL_REF]?.alias ?? "QIANFAN"
	};
	const providers = { ...cfg.models?.providers };
	const existingProvider = providers.qianfan;
	const defaultProvider = buildQianfanProvider();
	const existingModels = Array.isArray(existingProvider?.models) ? existingProvider.models : [];
	const defaultModels = defaultProvider.models ?? [];
	const hasDefaultModel = existingModels.some((model) => model.id === QIANFAN_DEFAULT_MODEL_ID);
	const mergedModels = existingModels.length > 0 ? hasDefaultModel ? existingModels : [...existingModels, ...defaultModels] : defaultModels;
	const { apiKey: existingApiKey, baseUrl: existingBaseUrl, api: existingApi, ...existingProviderRest } = existingProvider ?? {};
	const normalizedApiKey = (typeof existingApiKey === "string" ? existingApiKey : void 0)?.trim();
	providers.qianfan = {
		...existingProviderRest,
		baseUrl: existingBaseUrl ?? QIANFAN_BASE_URL,
		api: existingApi ?? "openai-completions",
		...normalizedApiKey ? { apiKey: normalizedApiKey } : {},
		models: mergedModels.length > 0 ? mergedModels : defaultProvider.models
	};
	return {
		...cfg,
		kois: {
			...cfg.kois,
			defaults: {
				...cfg.kois?.defaults,
				models
			}
		},
		models: {
			mode: cfg.models?.mode ?? "merge",
			providers
		}
	};
}
function applyQianfanConfig(cfg) {
	const next = applyQianfanProviderConfig(cfg);
	const existingModel = next.kois?.defaults?.model;
	return {
		...next,
		kois: {
			...next.kois,
			defaults: {
				...next.kois?.defaults,
				model: {
					...existingModel && "fallbacks" in existingModel ? { fallbacks: existingModel.fallbacks } : void 0,
					primary: QIANFAN_DEFAULT_MODEL_REF
				}
			}
		}
	};
}

//#endregion
//#region src/commands/onboard-auth.config-minimax.ts
function applyMinimaxProviderConfig(cfg) {
	const models = { ...cfg.kois?.defaults?.models };
	models["anthropic/claude-opus-4-6"] = {
		...models["anthropic/claude-opus-4-6"],
		alias: models["anthropic/claude-opus-4-6"]?.alias ?? "Opus"
	};
	models["lmstudio/minimax-m2.1-gs32"] = {
		...models["lmstudio/minimax-m2.1-gs32"],
		alias: models["lmstudio/minimax-m2.1-gs32"]?.alias ?? "Minimax"
	};
	const providers = { ...cfg.models?.providers };
	if (!providers.lmstudio) providers.lmstudio = {
		baseUrl: "http://127.0.0.1:1234/v1",
		apiKey: "lmstudio",
		api: "openai-responses",
		models: [buildMinimaxModelDefinition({
			id: "minimax-m2.1-gs32",
			name: "MiniMax M2.1 GS32",
			reasoning: false,
			cost: MINIMAX_LM_STUDIO_COST,
			contextWindow: 196608,
			maxTokens: 8192
		})]
	};
	return {
		...cfg,
		kois: {
			...cfg.kois,
			defaults: {
				...cfg.kois?.defaults,
				models
			}
		},
		models: {
			mode: cfg.models?.mode ?? "merge",
			providers
		}
	};
}
function applyMinimaxConfig(cfg) {
	const next = applyMinimaxProviderConfig(cfg);
	return {
		...next,
		kois: {
			...next.kois,
			defaults: {
				...next.kois?.defaults,
				model: {
					...next.kois?.defaults?.model && "fallbacks" in next.kois.defaults.model ? { fallbacks: next.kois.defaults.model.fallbacks } : void 0,
					primary: "lmstudio/minimax-m2.1-gs32"
				}
			}
		}
	};
}
function applyMinimaxApiProviderConfig(cfg, modelId = "MiniMax-M2.1") {
	const providers = { ...cfg.models?.providers };
	const existingProvider = providers.minimax;
	const existingModels = Array.isArray(existingProvider?.models) ? existingProvider.models : [];
	const apiModel = buildMinimaxApiModelDefinition(modelId);
	const mergedModels = existingModels.some((model) => model.id === modelId) ? existingModels : [...existingModels, apiModel];
	const { apiKey: existingApiKey, ...existingProviderRest } = existingProvider ?? {};
	const resolvedApiKey = typeof existingApiKey === "string" ? existingApiKey : void 0;
	const normalizedApiKey = resolvedApiKey?.trim() === "minimax" ? "" : resolvedApiKey;
	providers.minimax = {
		...existingProviderRest,
		baseUrl: MINIMAX_API_BASE_URL,
		api: "anthropic-messages",
		...normalizedApiKey?.trim() ? { apiKey: normalizedApiKey } : {},
		models: mergedModels.length > 0 ? mergedModels : [apiModel]
	};
	const models = { ...cfg.kois?.defaults?.models };
	models[`minimax/${modelId}`] = {
		...models[`minimax/${modelId}`],
		alias: "Minimax"
	};
	return {
		...cfg,
		kois: {
			...cfg.kois,
			defaults: {
				...cfg.kois?.defaults,
				models
			}
		},
		models: {
			mode: cfg.models?.mode ?? "merge",
			providers
		}
	};
}
function applyMinimaxApiConfig(cfg, modelId = "MiniMax-M2.1") {
	const next = applyMinimaxApiProviderConfig(cfg, modelId);
	return {
		...next,
		kois: {
			...next.kois,
			defaults: {
				...next.kois?.defaults,
				model: {
					...next.kois?.defaults?.model && "fallbacks" in next.kois.defaults.model ? { fallbacks: next.kois.defaults.model.fallbacks } : void 0,
					primary: `minimax/${modelId}`
				}
			}
		}
	};
}

//#endregion
//#region src/koi/opencode-zen-models.ts
const OPENCODE_ZEN_DEFAULT_MODEL = "claude-opus-4-6";
const OPENCODE_ZEN_DEFAULT_MODEL_REF = `opencode/${OPENCODE_ZEN_DEFAULT_MODEL}`;

//#endregion
//#region src/commands/onboard-auth.config-opencode.ts
function applyOpencodeZenProviderConfig(cfg) {
	const models = { ...cfg.kois?.defaults?.models };
	models[OPENCODE_ZEN_DEFAULT_MODEL_REF] = {
		...models[OPENCODE_ZEN_DEFAULT_MODEL_REF],
		alias: models[OPENCODE_ZEN_DEFAULT_MODEL_REF]?.alias ?? "Opus"
	};
	return {
		...cfg,
		kois: {
			...cfg.kois,
			defaults: {
				...cfg.kois?.defaults,
				models
			}
		}
	};
}
function applyOpencodeZenConfig(cfg) {
	const next = applyOpencodeZenProviderConfig(cfg);
	return {
		...next,
		kois: {
			...next.kois,
			defaults: {
				...next.kois?.defaults,
				model: {
					...next.kois?.defaults?.model && "fallbacks" in next.kois.defaults.model ? { fallbacks: next.kois.defaults.model.fallbacks } : void 0,
					primary: OPENCODE_ZEN_DEFAULT_MODEL_REF
				}
			}
		}
	};
}

//#endregion
//#region src/plugins/providers.ts
const log = createSubsystemLogger("plugins");
function resolvePluginProviders(params) {
	return loadSKYKOIPlugins({
		config: params.config,
		workspaceDir: params.workspaceDir,
		logger: {
			info: (msg) => log.info(msg),
			warn: (msg) => log.warn(msg),
			error: (msg) => log.error(msg),
			debug: (msg) => log.debug(msg)
		}
	}).providers.map((entry) => entry.provider);
}

//#endregion
//#region src/commands/oauth-env.ts
function isRemoteEnvironment() {
	if (process.env.SSH_CLIENT || process.env.SSH_TTY || process.env.SSH_CONNECTION) return true;
	if (process.env.REMOTE_CONTAINERS || process.env.CODESPACES) return true;
	if (process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY && !isWSLEnv()) return true;
	return false;
}

//#endregion
//#region src/commands/oauth-flow.ts
const validateRequiredInput = (value) => value.trim().length > 0 ? void 0 : "Required";
function createVpsAwareOAuthHandlers(params) {
	const manualPromptMessage = params.manualPromptMessage ?? "Paste the redirect URL (or authorization code)";
	let manualCodePromise;
	return {
		onAuth: async ({ url }) => {
			if (params.isRemote) {
				params.spin.stop("OAuth URL ready");
				params.runtime.log(`\nOpen this URL in your LOCAL browser:\n\n${url}\n`);
				manualCodePromise = params.prompter.text({
					message: manualPromptMessage,
					validate: validateRequiredInput
				}).then((value) => String(value));
				return;
			}
			params.spin.update(params.localBrowserMessage);
			await params.openUrl(url);
			params.runtime.log(`Open: ${url}`);
		},
		onPrompt: async (prompt) => {
			if (manualCodePromise) return manualCodePromise;
			const code = await params.prompter.text({
				message: prompt.message,
				placeholder: prompt.placeholder,
				validate: validateRequiredInput
			});
			return String(code);
		}
	};
}

//#endregion
//#region src/commands/models/shared.ts
const ensureFlagCompatibility = (opts) => {
	if (opts.json && opts.plain) throw new Error("Choose either --json or --plain, not both.");
};
const formatTokenK = (value) => {
	if (!value || !Number.isFinite(value)) return "-";
	if (value < 1024) return `${Math.round(value)}`;
	return `${Math.round(value / 1024)}k`;
};
const formatMs = (value) => {
	if (value === null || value === void 0) return "-";
	if (!Number.isFinite(value)) return "-";
	if (value < 1e3) return `${Math.round(value)}ms`;
	return `${Math.round(value / 100) / 10}s`;
};
async function updateConfig(mutator) {
	const snapshot = await readConfigFileSnapshot();
	if (!snapshot.valid) {
		const issues = snapshot.issues.map((issue) => `- ${issue.path}: ${issue.message}`).join("\n");
		throw new Error(`Invalid config at ${snapshot.path}\n${issues}`);
	}
	const next = mutator(snapshot.config);
	await writeConfigFile(next);
	return next;
}
function resolveModelTarget(params) {
	const aliasIndex = buildModelAliasIndex({
		cfg: params.cfg,
		defaultProvider: DEFAULT_PROVIDER
	});
	const resolved = resolveModelRefFromString({
		raw: params.raw,
		defaultProvider: DEFAULT_PROVIDER,
		aliasIndex
	});
	if (!resolved) throw new Error(`Invalid model reference: ${params.raw}`);
	return resolved.ref;
}
function normalizeAlias(alias) {
	const trimmed = alias.trim();
	if (!trimmed) throw new Error("Alias cannot be empty.");
	if (!/^[A-Za-z0-9_.:-]+$/.test(trimmed)) throw new Error("Alias must use letters, numbers, dots, underscores, colons, or dashes.");
	return trimmed;
}
function resolveKnownKoiId(params) {
	const raw = params.rawKoiId?.trim();
	if (!raw) return;
	const koiId = normalizeKoiId(raw);
	if (!listKoiIds(params.cfg).includes(koiId)) throw new Error(`Unknown koi id "${raw}". Use "${formatCliCommand("skykoi kois list")}" to see configured kois.`);
	return koiId;
}
/**
* Model key format: "provider/model"
*
* The model key is displayed in `/model status` and used to reference models.
* When using `/model <key>`, use the exact format shown (e.g., "openrouter/moonshotai/kimi-k2").
*
* For providers with hierarchical model IDs (e.g., OpenRouter), the model ID may include
* sub-providers (e.g., "moonshotai/kimi-k2"), resulting in a key like "openrouter/moonshotai/kimi-k2".
*/

//#endregion
//#region src/providers/github-copilot-auth.ts
const CLIENT_ID = "Iv1.b507a08c87ecfe98";
const DEVICE_CODE_URL = "https://github.com/login/device/code";
const ACCESS_TOKEN_URL = "https://github.com/login/oauth/access_token";
function parseJsonResponse(value) {
	if (!value || typeof value !== "object") throw new Error("Unexpected response from GitHub");
	return value;
}
async function requestDeviceCode(params) {
	const body = new URLSearchParams({
		client_id: CLIENT_ID,
		scope: params.scope
	});
	const res = await fetch(DEVICE_CODE_URL, {
		method: "POST",
		headers: {
			Accept: "application/json",
			"Content-Type": "application/x-www-form-urlencoded"
		},
		body,
		signal: AbortSignal.timeout(3e4)
	});
	if (!res.ok) throw new Error(`GitHub device code failed: HTTP ${res.status}`);
	const json = parseJsonResponse(await res.json());
	if (!json.device_code || !json.user_code || !json.verification_uri) throw new Error("GitHub device code response missing fields");
	return json;
}
async function pollForAccessToken(params) {
	const bodyBase = new URLSearchParams({
		client_id: CLIENT_ID,
		device_code: params.deviceCode,
		grant_type: "urn:ietf:params:oauth:grant-type:device_code"
	});
	while (Date.now() < params.expiresAt) {
		const res = await fetch(ACCESS_TOKEN_URL, {
			method: "POST",
			headers: {
				Accept: "application/json",
				"Content-Type": "application/x-www-form-urlencoded"
			},
			body: bodyBase,
			signal: AbortSignal.timeout(3e4)
		});
		if (!res.ok) throw new Error(`GitHub device token failed: HTTP ${res.status}`);
		const json = parseJsonResponse(await res.json());
		if ("access_token" in json && typeof json.access_token === "string") return json.access_token;
		const err = "error" in json ? json.error : "unknown";
		if (err === "authorization_pending") {
			await sleep(params.intervalMs);
			continue;
		}
		if (err === "slow_down") {
			await sleep(params.intervalMs + 2e3);
			continue;
		}
		if (err === "expired_token") throw new Error("GitHub device code expired; run login again");
		if (err === "access_denied") throw new Error("GitHub login cancelled");
		throw new Error(`GitHub device flow error: ${err}`);
	}
	throw new Error("GitHub device code expired; run login again");
}
async function githubCopilotLoginCommand(opts, runtime) {
	if (!process.stdin.isTTY) throw new Error("github-copilot login requires an interactive TTY.");
	intro(stylePromptTitle("GitHub Copilot login"));
	const profileId = opts.profileId?.trim() || "github-copilot:github";
	if (ensureAuthProfileStore(void 0, { allowKeychainPrompt: false }).profiles[profileId] && !opts.yes) note(`Auth profile already exists: ${profileId}\nRe-running will overwrite it.`, stylePromptTitle("Existing credentials"));
	const spin = spinner();
	spin.start("Requesting device code from GitHub...");
	const device = await requestDeviceCode({ scope: "read:user" });
	spin.stop("Device code ready");
	note([`Visit: ${device.verification_uri}`, `Code: ${device.user_code}`].join("\n"), stylePromptTitle("Authorize"));
	const expiresAt = Date.now() + device.expires_in * 1e3;
	const intervalMs = Math.max(1e3, device.interval * 1e3);
	const polling = spinner();
	polling.start("Waiting for GitHub authorization...");
	const accessToken = await pollForAccessToken({
		deviceCode: device.device_code,
		intervalMs,
		expiresAt
	});
	polling.stop("GitHub access token acquired");
	upsertAuthProfile({
		profileId,
		credential: {
			type: "token",
			provider: "github-copilot",
			token: accessToken
		}
	});
	await updateConfig((cfg) => applyAuthProfileConfig(cfg, {
		provider: "github-copilot",
		profileId,
		mode: "token"
	}));
	logConfigUpdated(runtime);
	runtime.log(`Auth profile: ${profileId} (github-copilot/token)`);
	outro("Done");
}

//#endregion
export { setOpenrouterApiKey as $, applyQianfanProviderConfig as A, applyXiaomiProviderConfig as B, applyMoonshotConfig as C, applyOpenrouterConfig as D, applyMoonshotProviderConfigCn as E, applyVercelAiGatewayConfig as F, ZAI_DEFAULT_MODEL_REF as G, OPENROUTER_DEFAULT_MODEL_REF as H, applyVercelAiGatewayProviderConfig as I, setGeminiApiKey as J, setAnthropicApiKey as K, applyXaiConfig as L, applySyntheticProviderConfig as M, applyVeniceConfig as N, applyOpenrouterProviderConfig as O, applyVeniceProviderConfig as P, setOpencodeZenApiKey as Q, applyXaiProviderConfig as R, applyKimiCodeProviderConfig as S, applyMoonshotProviderConfig as T, VERCEL_AI_GATEWAY_DEFAULT_MODEL_REF as U, applyZaiConfig as V, XIAOMI_DEFAULT_MODEL_REF as W, setMinimaxApiKey as X, setKimiCodingApiKey as Y, setMoonshotApiKey as Z, applyMinimaxProviderConfig as _, normalizeAlias as a, setXiaomiApiKey as at, applyCloudflareAiGatewayProviderConfig as b, updateConfig as c, KIMI_CODING_MODEL_REF as ct, resolvePluginProviders as d, XAI_DEFAULT_MODEL_REF as dt, setQianfanApiKey as et, applyOpencodeZenConfig as f, buildTokenProfileId as ft, applyMinimaxConfig as g, applyMinimaxApiProviderConfig as h, formatTokenK as i, setXaiApiKey as it, applySyntheticConfig as j, applyQianfanConfig as k, createVpsAwareOAuthHandlers as l, MOONSHOT_DEFAULT_MODEL_REF as lt, applyMinimaxApiConfig as m, ensureFlagCompatibility as n, setVeniceApiKey as nt, resolveKnownKoiId as o, setZaiApiKey as ot, applyOpencodeZenProviderConfig as p, validateAnthropicSetupToken as pt, setCloudflareAiGatewayConfig as q, formatMs as r, setVercelAiGatewayApiKey as rt, resolveModelTarget as s, writeOAuthCredentials as st, githubCopilotLoginCommand as t, setSyntheticApiKey as tt, isRemoteEnvironment as u, QIANFAN_DEFAULT_MODEL_REF as ut, applyAuthProfileConfig as v, applyMoonshotConfigCn as w, applyKimiCodeConfig as x, applyCloudflareAiGatewayConfig as y, applyXiaomiConfig as z };