optionalProviderApiKey function

String? optionalProviderApiKey(
  1. String provider,
  2. SecureKeyCache keys, {
  3. String? baseUrl,
  4. Iterable<String>? scopedKeyNames,
  5. Map<String, String>? env,
})

Resolves provider's API key headlessly. On the catalog spec's DEFAULT endpoint: a genuine environment value of the catalog env names, then endpoint-scoped secure-store entries (FA_KEY_<HOST> — what /provider writes — plus any saved custom entry's name-scoped key for this endpoint), then legacy env-name store entries from older versions. On ANY OTHER endpoint only the endpoint-scoped entries resolve — the catalog env names describe the default endpoint and must never hijack a custom one (issue #40: the user's OPENROUTER_API_KEY environment key silently serving api.z.ai), mirroring the shared resolveEndpointKey chain. env overrides Platform.environment (tests).

Implementation

String? optionalProviderApiKey(
  String provider,
  SecureKeyCache keys, {
  String? baseUrl,
  Iterable<String>? scopedKeyNames,
  Map<String, String>? env,
}) {
  final environment = env ?? Platform.environment;
  final names = apiKeyEnvNames(provider);
  final spec = catalogProvider(provider);
  final customEndpoint =
      spec != null && baseUrl != null && baseUrl != spec.defaultBaseUrl;
  if (!customEndpoint) {
    final envKey = _firstEnvValue(names, environment);
    if (envKey != null) return envKey;
  }
  if (baseUrl != null) {
    final stored = _firstStoredValue([
      CustomProviderRegistry.keyNameFor(baseUrl),
      ...?scopedKeyNames,
    ], keys);
    if (stored != null) return stored;
  }
  if (!customEndpoint) {
    final stored = _firstStoredValue(names, keys);
    if (stored != null) return stored;
  }
  return null;
}