import { Ea as normalizeProviderId, Ia as resolveAuthProfileDisplayLabel, Pi as resolveProfileUnusableUntilForDisplay, ba as resolveAuthStorePathForDisplay, ca as listProfilesForProvider, ci as getCustomProviderApiKey, di as resolveEnvApiKey } from "./env-Dlz8aQHP.js";
import { H as theme, V as isRich$1, w as shortenHomePath } from "./agent-paths-DUHGyU1s.js";
import { a as deriveModelMetadata, hr as maskApiKey, mt as formatRemainingShort } from "./model-catalog-B2mRe6cZ.js";

//#region src/agents/provider-extension-catalog-manifest.ts
const FASED_PROVIDER_EXTENSION_CATALOG_MANIFEST = [
	{
		upstreamProviderId: "anthropic",
		upstreamCatalogPaths: ["extensions/anthropic/provider-discovery.ts"],
		status: "mapped",
		fasedProviderIds: ["anthropic"],
		docsPath: "docs/providers/anthropic.md",
		authSurface: "api-key",
		authChoiceIds: ["apiKey", "token"]
	},
	{
		upstreamProviderId: "byteplus",
		upstreamCatalogPaths: ["extensions/byteplus/provider-catalog.ts", "extensions/byteplus/provider-discovery.ts"],
		status: "mapped",
		fasedProviderIds: [
			"byteplus",
			"byteplus-coding",
			"byteplus-plan"
		],
		docsPath: "docs/providers/volcengine.md",
		authSurface: "api-key",
		authChoiceIds: ["byteplus-api-key"]
	},
	{
		upstreamProviderId: "chutes",
		upstreamCatalogPaths: ["extensions/chutes/provider-catalog.ts"],
		status: "mapped",
		fasedProviderIds: ["chutes"],
		docsPath: "docs/providers/chutes.md",
		authSurface: "oauth",
		authChoiceIds: ["chutes"]
	},
	{
		upstreamProviderId: "codex",
		upstreamCatalogPaths: ["extensions/codex/provider-catalog.ts", "extensions/codex/provider-discovery.ts"],
		status: "mapped",
		fasedProviderIds: ["openai-codex"],
		fasedProviderAliases: ["codex"],
		docsPath: "docs/providers/openai.md",
		authSurface: "oauth",
		authChoiceIds: ["openai-codex"]
	},
	{
		upstreamProviderId: "huggingface",
		upstreamCatalogPaths: ["extensions/huggingface/provider-catalog.ts"],
		status: "mapped",
		fasedProviderIds: ["huggingface"],
		docsPath: "docs/providers/huggingface.md",
		authSurface: "api-key",
		authChoiceIds: ["huggingface-api-key"]
	},
	{
		upstreamProviderId: "kimi-coding",
		upstreamCatalogPaths: ["extensions/kimi-coding/provider-catalog.ts"],
		status: "mapped",
		fasedProviderIds: ["kimi"],
		fasedProviderAliases: ["kimi-coding", "kimi-code"],
		docsPath: "docs/providers/moonshot.md",
		authSurface: "api-key",
		authChoiceIds: ["kimi-code-api-key"]
	},
	{
		upstreamProviderId: "litellm",
		upstreamCatalogPaths: ["extensions/litellm/provider-catalog.ts"],
		status: "mapped",
		fasedProviderIds: ["litellm"],
		docsPath: "docs/providers/litellm.md",
		authSurface: "api-key",
		authChoiceIds: ["litellm-api-key"]
	},
	{
		upstreamProviderId: "minimax",
		upstreamCatalogPaths: ["extensions/minimax/provider-catalog.ts"],
		status: "mapped",
		fasedProviderIds: [
			"minimax",
			"minimax-cn",
			"minimax-portal"
		],
		docsPath: "docs/providers/minimax.md",
		authSurface: "api-key",
		authChoiceIds: [
			"minimax-portal",
			"minimax-api",
			"minimax-api-key-cn",
			"minimax-api-lightning"
		]
	},
	{
		upstreamProviderId: "mistral",
		upstreamCatalogPaths: ["extensions/mistral/provider-catalog.ts"],
		status: "mapped",
		fasedProviderIds: ["mistral"],
		docsPath: "docs/providers/mistral.md",
		authSurface: "api-key",
		authChoiceIds: ["mistral-api-key"]
	},
	{
		upstreamProviderId: "moonshot",
		upstreamCatalogPaths: ["extensions/moonshot/provider-catalog.ts", "extensions/moonshot/provider-discovery.ts"],
		status: "mapped",
		fasedProviderIds: ["moonshot"],
		docsPath: "docs/providers/moonshot.md",
		authSurface: "api-key",
		authChoiceIds: ["moonshot-api-key", "moonshot-api-key-cn"]
	},
	{
		upstreamProviderId: "openrouter",
		upstreamCatalogPaths: ["extensions/openrouter/provider-catalog.ts"],
		status: "mapped",
		fasedProviderIds: ["openrouter"],
		docsPath: "docs/providers/openrouter.md",
		authSurface: "api-key",
		authChoiceIds: ["openrouter-api-key"]
	},
	{
		upstreamProviderId: "qianfan",
		upstreamCatalogPaths: ["extensions/qianfan/provider-catalog.ts"],
		status: "mapped",
		fasedProviderIds: ["qianfan"],
		docsPath: "docs/providers/qianfan.md",
		authSurface: "api-key",
		authChoiceIds: ["qianfan-api-key"]
	},
	{
		upstreamProviderId: "qwen",
		upstreamCatalogPaths: ["extensions/qwen/provider-catalog.ts"],
		status: "mapped",
		fasedProviderIds: ["qwen"],
		docsPath: "docs/providers/qwen.md",
		authSurface: "api-key",
		authChoiceIds: ["qwen-coding-plan-api-key", "qwen-api-key"]
	},
	{
		upstreamProviderId: "synthetic",
		upstreamCatalogPaths: ["extensions/synthetic/provider-catalog.ts"],
		status: "mapped",
		fasedProviderIds: ["synthetic"],
		docsPath: "docs/providers/synthetic.md",
		authSurface: "api-key",
		authChoiceIds: ["synthetic-api-key"]
	},
	{
		upstreamProviderId: "together",
		upstreamCatalogPaths: ["extensions/together/provider-catalog.ts"],
		status: "mapped",
		fasedProviderIds: ["together"],
		docsPath: "docs/providers/together.md",
		authSurface: "api-key",
		authChoiceIds: ["together-api-key"]
	},
	{
		upstreamProviderId: "venice",
		upstreamCatalogPaths: ["extensions/venice/provider-catalog.ts"],
		status: "mapped",
		fasedProviderIds: ["venice"],
		docsPath: "docs/providers/venice.md",
		authSurface: "api-key",
		authChoiceIds: ["venice-api-key"]
	},
	{
		upstreamProviderId: "vercel-ai-gateway",
		upstreamCatalogPaths: ["extensions/vercel-ai-gateway/provider-catalog.ts"],
		status: "mapped",
		fasedProviderIds: ["vercel-ai-gateway"],
		docsPath: "docs/providers/vercel-ai-gateway.md",
		authSurface: "api-key",
		authChoiceIds: ["ai-gateway-api-key"]
	},
	{
		upstreamProviderId: "volcengine",
		upstreamCatalogPaths: ["extensions/volcengine/provider-catalog.ts", "extensions/volcengine/provider-discovery.ts"],
		status: "mapped",
		fasedProviderIds: [
			"volcengine",
			"volcengine-coding",
			"volcengine-plan"
		],
		docsPath: "docs/providers/volcengine.md",
		authSurface: "api-key",
		authChoiceIds: ["volcengine-api-key"]
	},
	{
		upstreamProviderId: "xai",
		upstreamCatalogPaths: ["extensions/xai/provider-catalog.ts", "extensions/xai/provider-discovery.ts"],
		status: "mapped",
		fasedProviderIds: ["xai"],
		docsPath: "docs/providers/xai.md",
		authSurface: "api-key",
		authChoiceIds: [
			"xai-oauth",
			"xai-device-code",
			"xai-api-key"
		]
	},
	{
		upstreamProviderId: "xiaomi",
		upstreamCatalogPaths: ["extensions/xiaomi/provider-catalog.ts"],
		status: "mapped",
		fasedProviderIds: ["xiaomi"],
		docsPath: "docs/providers/xiaomi.md",
		authSurface: "api-key",
		authChoiceIds: ["xiaomi-api-key"]
	}
];
function listProviderExtensionCatalogManifestEntries() {
	return FASED_PROVIDER_EXTENSION_CATALOG_MANIFEST;
}

//#endregion
//#region src/agents/model-catalog-status.ts
const SOURCE_CONFIDENCE_RANK = {
	configured: 600,
	runtime: 500,
	manifest: 400,
	"provider-index": 300,
	"current-preview": 200,
	catalog: 100
};
function createCapabilityCounts() {
	return {
		textModels: 0,
		visionModels: 0,
		reasoningModels: 0,
		toolsModels: 0,
		jsonModels: 0,
		audioModels: 0,
		videoModels: 0,
		speechModels: 0
	};
}
function capabilityKey(feature) {
	return `${feature}Models`;
}
function resolveProviderConfig(params) {
	return params.cfg.models?.providers?.[params.provider];
}
function deriveStatusMetadata(params) {
	return params.model.metadata ?? deriveModelMetadata({
		model: params.model,
		cfg: params.cfg,
		providerConfig: resolveProviderConfig({
			cfg: params.cfg,
			provider: params.provider
		})
	});
}
function higherConfidence(left, right) {
	return (SOURCE_CONFIDENCE_RANK[left] ?? 0) >= (SOURCE_CONFIDENCE_RANK[right] ?? 0) ? left : right;
}
function buildModelCatalogStatus(params) {
	const configuredProviders = new Set(Object.keys(params.cfg.models?.providers ?? {}).map((provider) => normalizeProviderId(provider)));
	const sourceCounts = {};
	const providers = /* @__PURE__ */ new Map();
	let reasoningModels = 0;
	let visionModels = 0;
	const capabilityCounts = createCapabilityCounts();
	for (const model of params.catalog) {
		const provider = normalizeProviderId(model.provider);
		if (!provider) continue;
		const source = model.catalogSource ?? "catalog";
		sourceCounts[source] = (sourceCounts[source] ?? 0) + 1;
		let entry = providers.get(provider);
		if (!entry) {
			entry = {
				provider,
				totalModels: 0,
				configured: configuredProviders.has(provider),
				reasoningModels: 0,
				visionModels: 0,
				sources: /* @__PURE__ */ new Set(),
				sourceConfidence: source,
				capabilityCounts: createCapabilityCounts(),
				authModes: /* @__PURE__ */ new Set(),
				privateNetwork: {
					models: 0,
					allowed: 0,
					blocked: 0
				}
			};
			providers.set(provider, entry);
		}
		entry.totalModels += 1;
		entry.sources.add(source);
		entry.sourceConfidence = higherConfidence(entry.sourceConfidence, source);
		const metadata = deriveStatusMetadata({
			cfg: params.cfg,
			model,
			provider
		});
		entry.authModes.add(metadata.authMode);
		for (const feature of metadata.features) {
			entry.capabilityCounts[capabilityKey(feature)] += 1;
			capabilityCounts[capabilityKey(feature)] += 1;
		}
		if (metadata.privateNetwork) {
			entry.privateNetwork.models += 1;
			if (metadata.privateNetworkAllowed) entry.privateNetwork.allowed += 1;
			else entry.privateNetwork.blocked += 1;
		}
		if (typeof metadata.contextWindow === "number") entry.maxContextWindow = Math.max(entry.maxContextWindow ?? 0, metadata.contextWindow);
		if (typeof metadata.maxTokens === "number") entry.maxOutputTokens = Math.max(entry.maxOutputTokens ?? 0, metadata.maxTokens);
		if (model.reasoning === true) {
			reasoningModels += 1;
			entry.reasoningModels += 1;
		}
		if (model.input?.includes("image")) {
			visionModels += 1;
			entry.visionModels += 1;
		}
	}
	const providerRows = Array.from(providers.values()).map((provider) => ({
		provider: provider.provider,
		totalModels: provider.totalModels,
		configured: provider.configured,
		reasoningModels: provider.reasoningModels,
		visionModels: provider.visionModels,
		sources: Array.from(provider.sources).toSorted((left, right) => left.localeCompare(right)),
		sourceConfidence: provider.sourceConfidence,
		capabilityCounts: provider.capabilityCounts,
		authModes: Array.from(provider.authModes).toSorted((left, right) => left.localeCompare(right)),
		privateNetwork: provider.privateNetwork,
		probeStatus: params.providerHealth?.[provider.provider] ? params.providerHealth[provider.provider].reachable === "ok" && params.providerHealth[provider.provider].auth !== "fail" ? "ok" : params.providerHealth[provider.provider].reachable === "fail" || params.providerHealth[provider.provider].auth === "fail" ? "fail" : "unknown" : "not-run",
		...params.providerHealth?.[provider.provider] ? { health: {
			reachable: params.providerHealth[provider.provider].reachable,
			auth: params.providerHealth[provider.provider].auth,
			modelsDiscovered: params.providerHealth[provider.provider].modelsDiscovered,
			privateNetworkApproved: params.providerHealth[provider.provider].privateNetworkApproved,
			...typeof params.providerHealth[provider.provider].checkedAtMs === "number" ? { checkedAtMs: params.providerHealth[provider.provider].checkedAtMs } : {},
			...params.providerHealth[provider.provider].detail ? { detail: params.providerHealth[provider.provider].detail } : {}
		} } : {},
		...provider.maxContextWindow ? { maxContextWindow: provider.maxContextWindow } : {},
		...provider.maxOutputTokens ? { maxOutputTokens: provider.maxOutputTokens } : {}
	})).toSorted((left, right) => left.provider.localeCompare(right.provider));
	const manifestEntries = listProviderExtensionCatalogManifestEntries();
	const mappedManifestProviderIds = [...new Set(manifestEntries.flatMap((entry) => entry.status === "mapped" ? entry.fasedProviderIds.map(normalizeProviderId) : []))].filter(Boolean).toSorted((left, right) => left.localeCompare(right));
	const catalogProviderIds = new Set(providerRows.map((provider) => provider.provider));
	const deferredProviderIds = manifestEntries.filter((entry) => entry.status === "deferred").map((entry) => normalizeProviderId(entry.upstreamProviderId)).filter(Boolean).toSorted((left, right) => left.localeCompare(right));
	const providerExtensionEntries = (params.providerExtensionCatalog?.entries ?? []).map((entry) => ({
		id: entry.id,
		source: entry.source,
		trusted: entry.trusted,
		providerIds: entry.providerIds,
		loadedProviderIds: entry.loadedProviderIds,
		modelCount: entry.modelCount,
		status: entry.status,
		...entry.error ? { error: entry.error } : {}
	}));
	const providerExtensionWarnings = providerExtensionEntries.filter((entry) => entry.status === "error" || entry.status === "skipped-untrusted");
	return {
		checkedAtMs: params.checkedAtMs ?? Date.now(),
		cache: {
			modelCatalog: "shared-loader",
			providerExtensionCatalog: params.providerExtensionCatalog ? "fresh-status-load" : "not-loaded"
		},
		totalProviders: providerRows.length,
		totalModels: params.catalog.length,
		configuredProviders: providerRows.filter((provider) => provider.configured).length,
		availableProviders: providerRows.filter((provider) => !provider.configured).length,
		reasoningModels,
		visionModels,
		capabilityCounts,
		sourceCounts,
		providers: providerRows,
		providerExtensionCatalog: {
			totalEntries: providerExtensionEntries.length,
			loadedEntries: providerExtensionEntries.filter((entry) => entry.status === "loaded").length,
			skippedUntrustedEntries: providerExtensionEntries.filter((entry) => entry.status === "skipped-untrusted").length,
			emptyEntries: providerExtensionEntries.filter((entry) => entry.status === "empty").length,
			errorEntries: providerExtensionEntries.filter((entry) => entry.status === "error").length,
			modelCount: providerExtensionEntries.reduce((total, entry) => total + entry.modelCount, 0),
			loadedProviderIds: Object.keys(params.providerExtensionCatalog?.providers ?? {}).toSorted((left, right) => left.localeCompare(right)),
			warnings: providerExtensionWarnings,
			entries: providerExtensionEntries
		},
		providerExtensionManifest: {
			upstreamProviderCount: manifestEntries.length,
			mappedProviderCount: manifestEntries.filter((entry) => entry.status === "mapped").length,
			deferredProviderCount: manifestEntries.filter((entry) => entry.status === "deferred").length,
			mappedProviderIds: mappedManifestProviderIds,
			deferredProviderIds,
			missingMappedProviderIds: mappedManifestProviderIds.filter((providerId) => !catalogProviderIds.has(providerId))
		}
	};
}

//#endregion
//#region src/commands/models/list.format.ts
const isRich = (opts) => Boolean(isRich$1() && !opts?.json && !opts?.plain);
const pad = (value, size) => value.padEnd(size);
const formatTag = (tag, rich) => {
	if (!rich) return tag;
	if (tag === "default") return theme.success(tag);
	if (tag === "image") return theme.accentBright(tag);
	if (tag === "configured") return theme.accent(tag);
	if (tag === "missing") return theme.error(tag);
	if (tag.startsWith("fallback#")) return theme.warn(tag);
	if (tag.startsWith("img-fallback#")) return theme.warn(tag);
	if (tag.startsWith("alias:")) return theme.accentDim(tag);
	return theme.muted(tag);
};
const truncate = (value, max) => {
	if (value.length <= max) return value;
	if (max <= 3) return value.slice(0, max);
	return `${value.slice(0, max - 3)}...`;
};

//#endregion
//#region src/commands/models/list.auth-overview.ts
function formatProfileSecretLabel(params) {
	const value = typeof params.value === "string" ? params.value.trim() : "";
	if (value) return params.kind === "token" ? `token:${maskApiKey(value)}` : maskApiKey(value);
	if (params.ref) {
		const refLabel = `ref(${params.ref.source}:${params.ref.id})`;
		return params.kind === "token" ? `token:${refLabel}` : refLabel;
	}
	return params.kind === "token" ? "token:missing" : "missing";
}
function resolveProviderAuthOverview(params) {
	const { provider, cfg, store } = params;
	const now = Date.now();
	const profiles = listProfilesForProvider(store, provider);
	const withUnusableSuffix = (base, profileId) => {
		const unusableUntil = resolveProfileUnusableUntilForDisplay(store, profileId);
		if (!unusableUntil || now >= unusableUntil) return base;
		const stats = store.usageStats?.[profileId];
		return `${base} [${typeof stats?.disabledUntil === "number" && now < stats.disabledUntil ? `disabled${stats.disabledReason ? `:${stats.disabledReason}` : ""}` : "cooldown"} ${formatRemainingShort(unusableUntil - now)}]`;
	};
	const labels = profiles.map((profileId) => {
		const profile = store.profiles[profileId];
		if (!profile) return `${profileId}=missing`;
		if (profile.type === "api_key") return withUnusableSuffix(`${profileId}=${formatProfileSecretLabel({
			value: profile.key,
			ref: profile.keyRef,
			kind: "api-key"
		})}`, profileId);
		if (profile.type === "token") return withUnusableSuffix(`${profileId}=${formatProfileSecretLabel({
			value: profile.token,
			ref: profile.tokenRef,
			kind: "token"
		})}`, profileId);
		const display = resolveAuthProfileDisplayLabel({
			cfg,
			store,
			profileId
		});
		const suffix = display === profileId ? "" : display.startsWith(profileId) ? display.slice(profileId.length).trim() : `(${display})`;
		return withUnusableSuffix(`${profileId}=OAuth${suffix ? ` ${suffix}` : ""}`, profileId);
	});
	const oauthCount = profiles.filter((id) => store.profiles[id]?.type === "oauth").length;
	const tokenCount = profiles.filter((id) => store.profiles[id]?.type === "token").length;
	const apiKeyCount = profiles.filter((id) => store.profiles[id]?.type === "api_key").length;
	const envKey = resolveEnvApiKey(provider);
	const customKey = getCustomProviderApiKey(cfg, provider);
	return {
		provider,
		effective: (() => {
			if (profiles.length > 0) return {
				kind: "profiles",
				detail: shortenHomePath(resolveAuthStorePathForDisplay())
			};
			if (envKey) return {
				kind: "env",
				detail: envKey.source.includes("OAUTH_TOKEN") || envKey.source.toLowerCase().includes("oauth") ? "OAuth (env)" : maskApiKey(envKey.apiKey)
			};
			if (customKey) return {
				kind: "models.json",
				detail: maskApiKey(customKey)
			};
			return {
				kind: "missing",
				detail: "missing"
			};
		})(),
		profiles: {
			count: profiles.length,
			oauth: oauthCount,
			token: tokenCount,
			apiKey: apiKeyCount,
			labels
		},
		...envKey ? { env: {
			value: envKey.source.includes("OAUTH_TOKEN") || envKey.source.toLowerCase().includes("oauth") ? "OAuth (env)" : maskApiKey(envKey.apiKey),
			source: envKey.source
		} } : {},
		...customKey ? { modelsJson: {
			value: maskApiKey(customKey),
			source: `models.json: ${shortenHomePath(params.modelsPath)}`
		} } : {}
	};
}

//#endregion
export { truncate as a, pad as i, formatTag as n, buildModelCatalogStatus as o, isRich as r, resolveProviderAuthOverview as t };