import { c as normalizeOptionalString } from "./string-coerce-DW4mBlAt.js";
import { g as resolveSecretInputRef, s as coerceSecretRef } from "./types.secrets-Ck44SCc-.js";
import { r as normalizeProviderId } from "./provider-id-BIcU_2-A.js";
import { n as resolveProviderIdForAuth } from "./provider-auth-aliases-DtNdgkM5.js";
import { c as isNonSecretApiKeyMarker, d as resolveEnvSecretRefHeaderValueMarker, f as resolveNonEnvSecretRefApiKeyMarker, g as resolveProviderEnvAuthLookupMaps, p as resolveNonEnvSecretRefHeaderValueMarker, s as isKnownEnvApiKeyMarker } from "./model-auth-markers-eE-59iVv.js";
import { j as resolveProviderSyntheticAuthWithPlugin } from "./provider-runtime-DUtCRoOE.js";
import { t as normalizeOptionalSecretInput } from "./normalize-secret-input-Df_qhWv_.js";
import { t as resolveEnvApiKey } from "./model-auth-env--dn97-tg.js";
import { s as resolveAwsSdkEnvVarName } from "./model-auth-runtime-shared-BVzqP6NP.js";
//#region src/agents/models-config.providers.secret-helpers.ts
/**
* Resolves configured provider secrets from env, profiles, and SecretRefs.
*/
const ENV_VAR_NAME_RE = /^[A-Z_][A-Z0-9_]*$/;
/** Normalizes `${ENV_VAR}` config syntax to the raw environment variable name. */
function normalizeApiKeyConfig(value) {
	const trimmed = value.trim();
	return /^\$\{([A-Z0-9_]+)\}$/.exec(trimmed)?.[1] ?? trimmed;
}
/** Returns a concrete key for discovery, omitting placeholder markers and blanks. */
function toDiscoveryApiKey(value) {
	const trimmed = normalizeOptionalString(value);
	if (!trimmed || isNonSecretApiKeyMarker(trimmed)) return;
	return trimmed;
}
/** Resolves which environment variable supplies a provider API key. */
function resolveEnvApiKeyVarName(provider, env = process.env, options = {}) {
	const resolved = resolveEnvApiKey(provider, env, options);
	if (!resolved) return;
	const match = /^(?:env: |shell env: )([A-Z0-9_]+)$/.exec(resolved.source);
	return match ? match[1] : void 0;
}
/** Resolves the AWS SDK API key env var used by Bedrock-style auth. */
function resolveAwsSdkApiKeyVarName(env = process.env) {
	return resolveAwsSdkEnvVarName(env);
}
function resolveEnvAuthEvidenceApiKeyMarker(provider, env) {
	const apiKey = resolveEnvApiKey(provider, env)?.apiKey?.trim();
	if (!apiKey || !isNonSecretApiKeyMarker(apiKey, { includeEnvVarName: false })) return;
	return apiKey;
}
/** Rewrites secret-backed provider headers to stable marker values. */
function normalizeHeaderValues(params) {
	const { headers } = params;
	if (!headers) return {
		headers,
		mutated: false
	};
	let mutated = false;
	const nextHeaders = {};
	for (const [headerName, headerValue] of Object.entries(headers)) {
		const resolvedRef = resolveSecretInputRef({
			value: headerValue,
			defaults: params.secretDefaults
		}).ref;
		if (!resolvedRef || !resolvedRef.id.trim()) {
			nextHeaders[headerName] = headerValue;
			continue;
		}
		mutated = true;
		nextHeaders[headerName] = resolvedRef.source === "env" ? resolveEnvSecretRefHeaderValueMarker(resolvedRef.id) : resolveNonEnvSecretRefHeaderValueMarker(resolvedRef.source);
	}
	if (!mutated) return {
		headers,
		mutated: false
	};
	return {
		headers: nextHeaders,
		mutated: true
	};
}
/** Resolves an auth profile credential into provider apiKey/discovery values. */
function resolveApiKeyFromCredential(cred, env = process.env) {
	if (!cred) return;
	if (cred.type === "api_key") {
		const keyRef = coerceSecretRef(cred.keyRef);
		if (keyRef && keyRef.id.trim()) {
			if (keyRef.source === "env") {
				const envVar = keyRef.id.trim();
				return {
					apiKey: envVar,
					source: "env-ref",
					discoveryApiKey: toDiscoveryApiKey(env[envVar])
				};
			}
			return {
				apiKey: resolveNonEnvSecretRefApiKeyMarker(keyRef.source),
				source: "non-env-ref"
			};
		}
		if (cred.key?.trim()) return {
			apiKey: cred.key,
			source: "plaintext",
			discoveryApiKey: toDiscoveryApiKey(cred.key)
		};
		return;
	}
	if (cred.type === "token") {
		const tokenRef = coerceSecretRef(cred.tokenRef);
		if (tokenRef && tokenRef.id.trim()) {
			if (tokenRef.source === "env") {
				const envVar = tokenRef.id.trim();
				return {
					apiKey: envVar,
					source: "env-ref",
					discoveryApiKey: toDiscoveryApiKey(env[envVar])
				};
			}
			return {
				apiKey: resolveNonEnvSecretRefApiKeyMarker(tokenRef.source),
				source: "non-env-ref"
			};
		}
		if (cred.token?.trim()) return {
			apiKey: cred.token,
			source: "plaintext",
			discoveryApiKey: toDiscoveryApiKey(cred.token)
		};
	}
}
/** Lists auth profile ids whose provider aliases match the requested provider. */
function listAuthProfilesForProvider(store, provider) {
	const providerKey = resolveProviderIdForAuth(provider);
	return Object.entries(store.profiles).filter(([, cred]) => resolveProviderIdForAuth(cred.provider) === providerKey).map(([id]) => id);
}
/** Resolves the first usable API key from matching auth profiles. */
function resolveApiKeyFromProfiles(params) {
	const ids = listAuthProfilesForProvider(params.store, params.provider);
	for (const id of ids) {
		const resolved = resolveApiKeyFromCredential(params.store.profiles[id], params.env);
		if (resolved) return resolved;
	}
}
/** Normalizes configured provider apiKey values and records providers backed by secret refs. */
function normalizeConfiguredProviderApiKey(params) {
	const configuredApiKey = params.provider.apiKey;
	const configuredApiKeyRef = resolveSecretInputRef({
		value: configuredApiKey,
		defaults: params.secretDefaults
	}).ref;
	if (configuredApiKeyRef && configuredApiKeyRef.id.trim()) {
		const marker = configuredApiKeyRef.source === "env" ? configuredApiKeyRef.id.trim() : resolveNonEnvSecretRefApiKeyMarker(configuredApiKeyRef.source);
		params.secretRefManagedProviders?.add(params.providerKey);
		if (params.provider.apiKey === marker) return params.provider;
		return {
			...params.provider,
			apiKey: marker
		};
	}
	if (typeof configuredApiKey !== "string") return params.provider;
	const normalizedConfiguredApiKey = normalizeApiKeyConfig(configuredApiKey);
	if (isNonSecretApiKeyMarker(normalizedConfiguredApiKey)) params.secretRefManagedProviders?.add(params.providerKey);
	if (params.profileApiKey && params.profileApiKey.source !== "plaintext" && normalizedConfiguredApiKey === params.profileApiKey.apiKey) params.secretRefManagedProviders?.add(params.providerKey);
	if (normalizedConfiguredApiKey === configuredApiKey) return params.provider;
	return {
		...params.provider,
		apiKey: normalizedConfiguredApiKey
	};
}
/** Rewrites literal env-derived keys back to env variable names when provenance is clear. */
function normalizeResolvedEnvApiKey(params) {
	const currentApiKey = params.provider.apiKey;
	if (typeof currentApiKey !== "string" || !currentApiKey.trim() || ENV_VAR_NAME_RE.test(currentApiKey.trim())) return params.provider;
	const envVarName = resolveEnvApiKeyVarName(params.providerKey, params.env);
	if (!envVarName || params.env[envVarName] !== currentApiKey) return params.provider;
	params.secretRefManagedProviders?.add(params.providerKey);
	return {
		...params.provider,
		apiKey: envVarName
	};
}
/** Fills missing provider apiKey values from env, auth profiles, or AWS SDK auth. */
function resolveMissingProviderApiKey(params) {
	const hasModels = Array.isArray(params.provider.models) && params.provider.models.length > 0;
	const normalizedApiKey = normalizeOptionalSecretInput(params.provider.apiKey);
	const hasConfiguredApiKey = Boolean(normalizedApiKey || params.provider.apiKey);
	if (!hasModels || hasConfiguredApiKey) return params.provider;
	const authMode = params.provider.auth;
	if (params.providerApiKeyResolver && (!authMode || authMode === "aws-sdk")) {
		const resolvedApiKey = params.providerApiKeyResolver(params.env);
		if (resolvedApiKey) return {
			...params.provider,
			apiKey: resolvedApiKey
		};
	}
	if (authMode === "aws-sdk") {
		const awsEnvVar = resolveAwsSdkApiKeyVarName(params.env);
		if (!awsEnvVar) return params.provider;
		return {
			...params.provider,
			apiKey: awsEnvVar
		};
	}
	const fromEnv = resolveEnvApiKeyVarName(params.providerKey, params.env);
	const fromAuthEvidence = fromEnv ? void 0 : resolveEnvAuthEvidenceApiKeyMarker(params.providerKey, params.env);
	const apiKey = fromEnv ?? fromAuthEvidence ?? params.profileApiKey?.apiKey;
	if (!apiKey?.trim()) return params.provider;
	if (fromAuthEvidence || params.profileApiKey && params.profileApiKey.source !== "plaintext") params.secretRefManagedProviders?.add(params.providerKey);
	return {
		...params.provider,
		apiKey
	};
}
//#endregion
//#region src/agents/models-config.providers.secrets.ts
/**
* Provider auth resolution entry points used during model config generation.
* The resolvers return env/profile/config marker values so discovery can prove
* auth availability without writing secret material into generated config.
*/
function resolveAuthProfileStoreInput(input) {
	return typeof input === "function" ? input() : input;
}
function createProviderAuthLookupCaches(env, config) {
	let caches;
	return () => {
		if (!caches) {
			const lookupMaps = resolveProviderEnvAuthLookupMaps({
				config,
				env
			});
			caches = {
				aliasMap: lookupMaps.aliasMap,
				candidateMap: lookupMaps.envCandidateMap,
				authEvidenceMap: lookupMaps.authEvidenceMap
			};
		}
		return caches;
	};
}
function resolveProviderIdForAuthFromCaches(provider, caches) {
	const normalized = normalizeProviderId(provider);
	if (!normalized) return normalized;
	return caches.aliasMap[normalized] ?? normalized;
}
/** Create a resolver that returns redacted API-key markers for provider discovery. */
function createProviderApiKeyResolver(env, authStoreInput, config) {
	const getLookupCaches = createProviderAuthLookupCaches(env, config);
	return (provider) => {
		const lookupCaches = getLookupCaches();
		const authProvider = resolveProviderIdForAuthFromCaches(provider, lookupCaches);
		const envVar = resolveEnvApiKeyVarName(authProvider, env, {
			aliasMap: lookupCaches.aliasMap,
			candidateMap: lookupCaches.candidateMap,
			authEvidenceMap: lookupCaches.authEvidenceMap
		});
		if (envVar) return {
			apiKey: envVar,
			discoveryApiKey: toDiscoveryApiKey(env[envVar])
		};
		const fromConfig = resolveConfigBackedProviderAuth({
			provider: authProvider,
			config,
			env,
			authProvider
		});
		if (fromConfig?.apiKey) return {
			apiKey: fromConfig.apiKey,
			discoveryApiKey: fromConfig.discoveryApiKey
		};
		const fromProfiles = resolveApiKeyFromProfiles({
			provider: authProvider,
			store: resolveAuthProfileStoreInput(authStoreInput),
			env
		});
		return fromProfiles?.apiKey ? {
			apiKey: fromProfiles.apiKey,
			discoveryApiKey: fromProfiles.discoveryApiKey
		} : {
			apiKey: void 0,
			discoveryApiKey: void 0
		};
	};
}
/** Create a resolver that reports provider auth mode and provenance. */
function createProviderAuthResolver(env, authStoreInput, config) {
	const getLookupCaches = createProviderAuthLookupCaches(env, config);
	return (provider, options) => {
		const lookupCaches = getLookupCaches();
		const authProvider = resolveProviderIdForAuthFromCaches(provider, lookupCaches);
		const authStore = resolveAuthProfileStoreInput(authStoreInput);
		const ids = listAuthProfilesForProvider(authStore, authProvider);
		let oauthCandidate;
		for (const id of ids) {
			const cred = authStore.profiles[id];
			if (!cred) continue;
			if (cred.type === "oauth") {
				oauthCandidate ??= {
					apiKey: options?.oauthMarker,
					discoveryApiKey: toDiscoveryApiKey(cred.access),
					mode: "oauth",
					source: "profile",
					profileId: id
				};
				continue;
			}
			const resolved = resolveApiKeyFromCredential(cred, env);
			if (!resolved) continue;
			return {
				apiKey: resolved.apiKey,
				discoveryApiKey: resolved.discoveryApiKey,
				mode: cred.type,
				source: "profile",
				profileId: id
			};
		}
		if (oauthCandidate) return oauthCandidate;
		const envVar = resolveEnvApiKeyVarName(authProvider, env, {
			aliasMap: lookupCaches.aliasMap,
			candidateMap: lookupCaches.candidateMap,
			authEvidenceMap: lookupCaches.authEvidenceMap
		});
		if (envVar) return {
			apiKey: envVar,
			discoveryApiKey: toDiscoveryApiKey(env[envVar]),
			mode: "api_key",
			source: "env"
		};
		const fromConfig = resolveConfigBackedProviderAuth({
			provider: authProvider,
			config,
			env,
			authProvider
		});
		if (fromConfig) return {
			apiKey: fromConfig.apiKey,
			discoveryApiKey: fromConfig.discoveryApiKey,
			mode: fromConfig.mode,
			source: "none"
		};
		return {
			apiKey: void 0,
			discoveryApiKey: void 0,
			mode: "none",
			source: "none"
		};
	};
}
function resolveConfigBackedProviderAuth(params) {
	const authProvider = params.authProvider ?? resolveProviderIdForAuth(params.provider, { config: params.config });
	const apiKey = resolveProviderSyntheticAuthWithPlugin({
		provider: authProvider,
		config: params.config,
		context: {
			config: params.config,
			provider: authProvider,
			providerConfig: params.config?.models?.providers?.[authProvider]
		}
	})?.apiKey?.trim();
	if (apiKey) return isNonSecretApiKeyMarker(apiKey) ? {
		apiKey,
		discoveryApiKey: toDiscoveryApiKey(apiKey),
		mode: "api_key",
		source: "config"
	} : {
		apiKey: resolveNonEnvSecretRefApiKeyMarker("file"),
		discoveryApiKey: toDiscoveryApiKey(apiKey),
		mode: "api_key",
		source: "config"
	};
	const configuredProviderApiKey = (params.config?.models?.providers?.[authProvider])?.apiKey;
	const configuredApiKeyRef = resolveSecretInputRef({
		value: configuredProviderApiKey,
		defaults: params.config?.secrets?.defaults
	}).ref;
	if (configuredApiKeyRef) {
		if (configuredApiKeyRef.source === "env") {
			const envVar = configuredApiKeyRef.id.trim();
			const envValue = params.env?.[envVar]?.trim();
			return envValue ? {
				apiKey: envVar,
				discoveryApiKey: toDiscoveryApiKey(envValue),
				mode: "api_key",
				source: "config"
			} : void 0;
		}
		return {
			apiKey: resolveNonEnvSecretRefApiKeyMarker(configuredApiKeyRef.source),
			discoveryApiKey: void 0,
			mode: "api_key",
			source: "config"
		};
	}
	if (typeof configuredProviderApiKey !== "string") return;
	const configuredApiKey = normalizeApiKeyConfig(configuredProviderApiKey);
	if (!configuredApiKey) return;
	if (isKnownEnvApiKeyMarker(configuredApiKey)) {
		const envValue = params.env?.[configuredApiKey]?.trim();
		if (envValue) return {
			apiKey: configuredApiKey,
			discoveryApiKey: toDiscoveryApiKey(envValue),
			mode: "api_key",
			source: "config"
		};
		return;
	}
	return isNonSecretApiKeyMarker(configuredApiKey) ? {
		apiKey: configuredApiKey,
		discoveryApiKey: toDiscoveryApiKey(configuredApiKey),
		mode: "api_key",
		source: "config"
	} : {
		apiKey: configuredApiKey,
		discoveryApiKey: toDiscoveryApiKey(configuredApiKey),
		mode: "api_key",
		source: "config"
	};
}
//#endregion
export { normalizeHeaderValues as a, resolveMissingProviderApiKey as c, normalizeConfiguredProviderApiKey as i, createProviderAuthResolver as n, normalizeResolvedEnvApiKey as o, normalizeApiKeyConfig as r, resolveApiKeyFromProfiles as s, createProviderApiKeyResolver as t };
