optionalProviderApiKey function

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

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).

pinnedKeyName (gh-1000 AC1) is the restored folder state's saved provider entry's own key slot: it resolves FIRST — the environment value, then the store slot — because it names the account the session actually ran on. A same-endpoint twin entry (or the host-scoped slot) must never win over the pin.

Implementation

String? optionalProviderApiKey(
  String provider,
  SecureKeyCache keys, {
  String? baseUrl,
  Iterable<String>? scopedKeyNames,
  Map<String, String>? env,
  String? pinnedKeyName,
}) {
  final environment = env ?? Platform.environment;
  final pinned = _pinnedKeyValue(pinnedKeyName, environment, keys);
  if (pinned != null) return pinned;
  final spec = _keySpec(provider);
  final customEndpoint =
      spec != null && baseUrl != null && baseUrl != spec.defaultBaseUrl;
  if (!customEndpoint) {
    final envKey = _firstEnvValue(apiKeyEnvNames(provider), environment);
    if (envKey != null) return envKey;
  }
  return _storedValueFor(
    baseUrl,
    customEndpoint,
    provider,
    keys,
    scopedKeyNames: scopedKeyNames,
  );
}