import { __esmMin, __exportAll } from "../../_virtual/_rolldown/runtime.js";
import { PROVIDER_ENV_MAP, getApiKeyFromEnv, init_env_keys } from "./env-keys.js";
import { CredentialResolver, hasCredentials, init_credentials, resolveApiKey } from "../auth/credentials.js";
import { hasProviderAuthOnDiskSync, init_sync_provider_auth } from "../auth/sync-provider-auth.js";
import { ModelRegistry, getModelRegistry, init_model_registry, prewarmModelRegistry, resetModelRegistry } from "./model-registry.js";
import { getProviderRegistry, init_plugin_registry } from "./plugin-registry.js";
import { getModel, getModels, getProviders } from "@earendil-works/pi-ai";
//#region src/providers/index.ts
/**
* Model provider module - integrates built-in models with custom models from models.json
*/
var providers_exports = /* @__PURE__ */ __exportAll({
	EXTENSION_PROVIDER_BASE_URL: () => EXTENSION_PROVIDER_BASE_URL,
	ModelRegistry: () => ModelRegistry,
	PROVIDER_ENV_MAP: () => PROVIDER_ENV_MAP,
	PROVIDER_META: () => PROVIDER_META,
	getAllModels: () => getAllModels,
	getAllProviders: () => getAllProviders,
	getApiKey: () => getApiKey,
	getApiKeyFromEnv: () => getApiKeyFromEnv,
	getApiKeySync: () => getApiKeySync,
	getAvailableModels: () => getAvailableModels,
	getConfiguredProviders: () => getConfiguredProviders,
	getDefaultModel: () => getDefaultModel,
	getDefaultModelSync: () => getDefaultModelSync,
	getModelRegistry: () => getModelRegistry,
	getModelsByProvider: () => getModelsByProvider,
	getProviderActiveKeySource: () => getProviderActiveKeySource,
	getProviderDisplayName: () => getProviderDisplayName,
	getSortedProviders: () => getSortedProviders,
	isProviderConfigured: () => isProviderConfigured,
	isProviderConfiguredSync: () => isProviderConfiguredSync,
	pluginModelToModel: () => pluginModelToModel,
	prewarmModelRegistry: () => prewarmModelRegistry,
	providerSupportsApiKey: () => providerSupportsApiKey,
	providerSupportsOAuth: () => providerSupportsOAuth,
	resetModelRegistry: () => resetModelRegistry,
	resolveModel: () => resolveModel
});
/** Map a plugin registry model to the pi-ai {@link Model} shape. */
function pluginModelToModel(providerId, definition) {
	return {
		provider: providerId,
		id: definition.id,
		name: definition.name,
		api: "openai-completions",
		baseUrl: EXTENSION_PROVIDER_BASE_URL,
		reasoning: false,
		input: definition.supportsImages ? ["text", "image"] : ["text"],
		contextWindow: definition.contextWindow ?? 128e3,
		maxTokens: definition.maxOutputTokens ?? 4096,
		cost: {
			input: definition.pricing?.input ?? 0,
			output: definition.pricing?.output ?? 0,
			cacheRead: 0,
			cacheWrite: 0
		}
	};
}
/**
* Get API key synchronously: checks registry (models.json) first, then environment variables.
* Use this for Agent's getApiKey callback which must be synchronous.
*/
function getApiKeySync(provider) {
	if (getProviderRegistry().has(provider)) return "extension-managed";
	const registryKey = getModelRegistry().getApiKey(provider);
	if (registryKey) return registryKey;
	return getApiKeyFromEnv(provider);
}
/**
* Resolve model reference. Supports:
* - "provider/modelId" format
* - "modelId" auto-detection via pi-ai or custom models
* @throws if model not found
*/
function resolveModel(ref) {
	const customModel = getModelRegistry().resolve(ref);
	if (customModel) return customModel;
	if (ref.includes("/")) {
		const [provider, modelId] = ref.split("/");
		const piAiModel = getModel(provider, modelId);
		if (piAiModel) return piAiModel;
		const plugin = getProviderRegistry().get(provider);
		if (plugin) {
			const pluginModel = plugin.models.find((m) => m.id === modelId);
			if (pluginModel) return pluginModelToModel(provider, pluginModel);
		}
		throw new Error(`Model not found: ${ref}`);
	}
	for (const provider of getProviders()) try {
		const found = getModels(provider).find((m) => m.id === ref);
		if (found) return found;
	} catch {
		continue;
	}
	const pluginRegistry = getProviderRegistry();
	for (const plugin of pluginRegistry.listAll()) {
		const found = plugin.models.find((m) => m.id === ref);
		if (found) return pluginModelToModel(plugin.id, found);
	}
	throw new Error(`Model not found: ${ref}. Use format: provider/model-id`);
}
function getModelsByProvider(provider) {
	const fromRegistry = getModelRegistry().getAll().filter((m) => m.provider === provider);
	const plugin = getProviderRegistry().get(provider);
	if (!plugin) return fromRegistry;
	const pluginModels = plugin.models.map((m) => pluginModelToModel(provider, m));
	return [...fromRegistry, ...pluginModels];
}
function getAllProviders() {
	const registry = getModelRegistry();
	const providers = /* @__PURE__ */ new Set();
	for (const p of getProviders()) providers.add(p);
	for (const m of registry.getAll()) providers.add(m.provider);
	for (const plugin of getProviderRegistry().listAll()) providers.add(plugin.id);
	return Array.from(providers);
}
async function getApiKey(provider) {
	if (getProviderRegistry().has(provider)) return "extension-managed";
	const credentialKey = await resolveApiKey(provider);
	if (credentialKey) return credentialKey;
	const registryKey = getModelRegistry().getApiKey(provider);
	if (registryKey) return registryKey;
	return getApiKeyFromEnv(provider);
}
/**
* Synchronous version for use in non-async contexts
* Only checks environment variables and registry, not credential system
*/
function isProviderConfiguredSync(provider) {
	if (getProviderRegistry().has(provider)) return true;
	if (getModelRegistry().getApiKey(provider)) return true;
	if (getApiKeyFromEnv(provider)) return true;
	return hasProviderAuthOnDiskSync(provider);
}
async function isProviderConfigured(provider) {
	if (getProviderRegistry().has(provider)) return true;
	if (getModelRegistry().getApiKey(provider)) return true;
	return await hasCredentials(provider);
}
async function getProviderActiveKeySource(provider) {
	if (getProviderRegistry().has(provider)) return "extension";
	const fromCredentials = await new CredentialResolver().resolveApiKeySource(provider);
	if (fromCredentials === "agent") return "agent";
	if (fromCredentials === "global") return "gateway";
	if (fromCredentials === "oauth") return "oauth";
	if (fromCredentials === "env") return "env";
	if (getModelRegistry().getApiKey(provider)) return "models_json";
	return "none";
}
async function getConfiguredProviders() {
	const allProviders = getAllProviders();
	const configured = [];
	for (const p of allProviders) if (await isProviderConfigured(p)) configured.push(p);
	return configured;
}
function getAllModels() {
	const registryModels = getModelRegistry().getAll();
	const pluginProviders = getProviderRegistry().listAll();
	if (pluginProviders.length === 0) return registryModels;
	const existingIds = new Set(registryModels.map((m) => `${m.provider}/${m.id}`));
	const merged = [...registryModels];
	for (const plugin of pluginProviders) for (const model of plugin.models) {
		const compositeId = `${plugin.id}/${model.id}`;
		if (!existingIds.has(compositeId)) {
			merged.push(pluginModelToModel(plugin.id, model));
			existingIds.add(compositeId);
		}
	}
	return merged;
}
async function getAvailableModels() {
	const allModels = getAllModels();
	const pluginRegistry = getProviderRegistry();
	const available = [];
	for (const model of allModels) if (pluginRegistry.has(model.provider)) available.push(model);
	else if (await isProviderConfigured(model.provider)) available.push(model);
	return available;
}
function getSortedProviders() {
	const all = getAllProviders();
	const catOrder = {
		common: 0,
		specialty: 1,
		enterprise: 2,
		oauth: 3,
		extension: 4
	};
	const pluginRegistry = getProviderRegistry();
	return [...all].sort((a, b) => {
		const catA = pluginRegistry.has(a) ? "extension" : PROVIDER_META[a]?.category ?? "specialty";
		const catB = pluginRegistry.has(b) ? "extension" : PROVIDER_META[b]?.category ?? "specialty";
		if (catOrder[catA] !== catOrder[catB]) return catOrder[catA] - catOrder[catB];
		return a.localeCompare(b);
	});
}
function getProviderDisplayName(provider) {
	const plugin = getProviderRegistry().get(provider);
	if (plugin) return plugin.name;
	return PROVIDER_META[provider]?.name || provider;
}
function providerSupportsOAuth(provider) {
	return PROVIDER_META[provider]?.supportsOAuth ?? false;
}
function providerSupportsApiKey(provider) {
	return PROVIDER_META[provider]?.supportsApiKey ?? true;
}
/**
* Get a default model reference.
* Priority:
* 1. Explicitly configured model in agents.defaults.model (if set and available)
* 2. Default fallback: deepseek/deepseek-v4-flash
*/
async function getDefaultModel(config) {
	const defaultModel = config?.agents?.defaults?.model;
	if (defaultModel) {
		const modelRef = typeof defaultModel === "string" ? defaultModel : defaultModel.primary;
		if (modelRef) {
			const configured = (await getAvailableModels()).find((m) => `${m.provider}/${m.id}` === modelRef || m.id === modelRef);
			if (configured) return `${configured.provider}/${configured.id}`;
			return modelRef;
		}
	}
	return DEFAULT_FALLBACK_MODEL;
}
/**
* Synchronous default model resolution for constructors and sync code paths.
* Uses catalog/registry only (no async credential checks).
*
* When no model is explicitly configured, returns the preferred default
* (`deepseek/deepseek-v4-flash`) rather than picking an arbitrary first
* model from the full catalog.
*/
function getDefaultModelSync(config) {
	const defaultModel = config?.agents?.defaults?.model;
	if (defaultModel) {
		const modelRef = typeof defaultModel === "string" ? defaultModel : defaultModel.primary;
		if (modelRef) return modelRef;
	}
	return DEFAULT_FALLBACK_MODEL;
}
var EXTENSION_PROVIDER_BASE_URL, PROVIDER_META, DEFAULT_FALLBACK_MODEL;
var init_providers = __esmMin((() => {
	init_model_registry();
	init_credentials();
	init_sync_provider_auth();
	init_env_keys();
	init_plugin_registry();
	EXTENSION_PROVIDER_BASE_URL = "extension://provider-plugin";
	PROVIDER_META = {
		"openai": {
			name: "OpenAI (GPT-4, o1, o3)",
			category: "common",
			supportsApiKey: true
		},
		"anthropic": {
			name: "Anthropic Claude",
			category: "common",
			supportsApiKey: true,
			supportsOAuth: true
		},
		"deepseek": {
			name: "DeepSeek",
			category: "common",
			supportsApiKey: true
		},
		"google": {
			name: "Google Gemini",
			category: "common",
			supportsApiKey: true
		},
		"groq": {
			name: "Groq (Fast Inference)",
			category: "common",
			supportsApiKey: true
		},
		"minimax": {
			name: "MiniMax",
			category: "common",
			supportsApiKey: true,
			supportsOAuth: true
		},
		"minimax-cn": {
			name: "MiniMax CN",
			category: "common",
			supportsApiKey: true,
			supportsOAuth: true
		},
		"kimi-coding": {
			name: "Kimi For Coding",
			category: "common",
			supportsApiKey: true,
			supportsOAuth: true
		},
		"xai": {
			name: "xAI (Grok)",
			category: "specialty",
			supportsApiKey: true
		},
		"mistral": {
			name: "Mistral AI",
			category: "specialty",
			supportsApiKey: true
		},
		"cerebras": {
			name: "Cerebras",
			category: "specialty",
			supportsApiKey: true
		},
		"openrouter": {
			name: "OpenRouter (Multi-provider)",
			category: "specialty",
			supportsApiKey: true
		},
		"huggingface": {
			name: "Hugging Face",
			category: "specialty",
			supportsApiKey: true
		},
		moonshotai: {
			name: "Moonshot AI (Kimi · International)",
			category: "common",
			supportsApiKey: true
		},
		"moonshotai-cn": {
			name: "Moonshot AI (Kimi · China)",
			category: "common",
			supportsApiKey: true
		},
		fireworks: {
			name: "Fireworks AI",
			category: "specialty",
			supportsApiKey: true
		},
		together: {
			name: "Together AI",
			category: "specialty",
			supportsApiKey: true
		},
		"cloudflare-workers-ai": {
			name: "Cloudflare Workers AI",
			category: "enterprise",
			supportsApiKey: true
		},
		"cloudflare-ai-gateway": {
			name: "Cloudflare AI Gateway",
			category: "enterprise",
			supportsApiKey: true
		},
		xiaomi: {
			name: "Xiaomi Mimo",
			category: "specialty",
			supportsApiKey: true
		},
		"xiaomi-token-plan-cn": {
			name: "Xiaomi Token Plan (CN)",
			category: "specialty",
			supportsApiKey: true
		},
		"xiaomi-token-plan-ams": {
			name: "Xiaomi Token Plan (AMS)",
			category: "specialty",
			supportsApiKey: true
		},
		"xiaomi-token-plan-sgp": {
			name: "Xiaomi Token Plan (SGP)",
			category: "specialty",
			supportsApiKey: true
		},
		"opencode": {
			name: "OpenCode",
			category: "specialty",
			supportsApiKey: true
		},
		"opencode-go": {
			name: "OpenCode Go",
			category: "specialty",
			supportsApiKey: true
		},
		/** DashScope (Alibaba) — image, speech, STT; not an LLM KnownProvider. */
		"dashscope": {
			name: "DashScope (Alibaba)",
			category: "specialty",
			supportsApiKey: true
		},
		/** International GLM (api.z.ai). Auth: API key (ZAI_API_KEY); no published OAuth for this HTTP API. */
		"zai": {
			name: "Zhipu GLM (International · z.ai)",
			category: "common",
			supportsApiKey: true
		},
		"amazon-bedrock": {
			name: "Amazon Bedrock",
			category: "enterprise",
			supportsApiKey: true
		},
		"azure-openai-responses": {
			name: "Azure OpenAI",
			category: "enterprise",
			supportsApiKey: true
		},
		"google-vertex": {
			name: "Google Vertex AI",
			category: "enterprise",
			supportsApiKey: true
		},
		"vercel-ai-gateway": {
			name: "Vercel AI Gateway",
			category: "enterprise",
			supportsApiKey: true
		},
		"github-copilot": {
			name: "GitHub Copilot (OAuth)",
			category: "oauth",
			supportsOAuth: true
		},
		"openai-codex": {
			name: "OpenAI Codex (OAuth)",
			category: "oauth",
			supportsOAuth: true,
			supportsApiKey: false
		},
		"google-gemini-cli": {
			name: "Google Gemini CLI (OAuth)",
			category: "oauth",
			supportsOAuth: true
		},
		"google-antigravity": {
			name: "Google Antigravity (OAuth)",
			category: "oauth",
			supportsOAuth: true
		}
	};
	DEFAULT_FALLBACK_MODEL = "deepseek/deepseek-v4-flash";
}));
//#endregion
init_providers();
export { EXTENSION_PROVIDER_BASE_URL, ModelRegistry, PROVIDER_ENV_MAP, PROVIDER_META, getAllModels, getAllProviders, getApiKey, getApiKeyFromEnv, getApiKeySync, getAvailableModels, getConfiguredProviders, getDefaultModel, getDefaultModelSync, getModelRegistry, getModelsByProvider, getProviderActiveKeySource, getProviderDisplayName, getSortedProviders, init_providers, isProviderConfigured, isProviderConfiguredSync, pluginModelToModel, prewarmModelRegistry, providerSupportsApiKey, providerSupportsOAuth, providers_exports, resetModelRegistry, resolveModel };

//# sourceMappingURL=index.js.map