getAnthropicApiKeyWithSource function
Get the Anthropic API key along with its source.
Implementation
ApiKeyWithSource getAnthropicApiKeyWithSource({
bool skipRetrievingKeyFromApiKeyHelper = false,
}) {
if (isBareMode()) {
final envKey = Platform.environment['ANTHROPIC_API_KEY'];
if (envKey != null) {
return ApiKeyWithSource(
key: envKey,
source: ApiKeySource.anthropicApiKey,
);
}
if (getConfiguredApiKeyHelper() != null) {
return ApiKeyWithSource(
key: skipRetrievingKeyFromApiKeyHelper
? null
: getApiKeyFromApiKeyHelperCached(),
source: ApiKeySource.apiKeyHelper,
);
}
return const ApiKeyWithSource(key: null, source: ApiKeySource.none);
}
final apiKeyEnv = isRunningOnHomespace()
? null
: Platform.environment['ANTHROPIC_API_KEY'];
// Always check direct env var for non-interactive (--print) mode.
if (apiKeyEnv != null &&
_isEnvTruthy(Platform.environment['MAGE_PREFER_3P_AUTH'])) {
return ApiKeyWithSource(
key: apiKeyEnv,
source: ApiKeySource.anthropicApiKey,
);
}
// CI / test mode.
if (_isEnvTruthy(Platform.environment['CI']) ||
Platform.environment['NODE_ENV'] == 'test') {
final apiKeyFromFd = getApiKeyFromFileDescriptor();
if (apiKeyFromFd != null) {
return ApiKeyWithSource(
key: apiKeyFromFd,
source: ApiKeySource.anthropicApiKey,
);
}
if (apiKeyEnv != null) {
return ApiKeyWithSource(
key: apiKeyEnv,
source: ApiKeySource.anthropicApiKey,
);
}
return const ApiKeyWithSource(key: null, source: ApiKeySource.none);
}
// Check ANTHROPIC_API_KEY against approved list.
if (apiKeyEnv != null) {
// Simplified: in the full implementation this checks config approval list.
return ApiKeyWithSource(
key: apiKeyEnv,
source: ApiKeySource.anthropicApiKey,
);
}
// Check file descriptor.
final apiKeyFromFd = getApiKeyFromFileDescriptor();
if (apiKeyFromFd != null) {
return ApiKeyWithSource(
key: apiKeyFromFd,
source: ApiKeySource.anthropicApiKey,
);
}
// Check apiKeyHelper.
final apiKeyHelperCommand = getConfiguredApiKeyHelper();
if (apiKeyHelperCommand != null) {
if (skipRetrievingKeyFromApiKeyHelper) {
return const ApiKeyWithSource(
key: null,
source: ApiKeySource.apiKeyHelper,
);
}
return ApiKeyWithSource(
key: getApiKeyFromApiKeyHelperCached(),
source: ApiKeySource.apiKeyHelper,
);
}
// Check config or platform keychain.
final fromConfig = getApiKeyFromConfigOrKeychain();
if (fromConfig != null) {
return fromConfig;
}
return const ApiKeyWithSource(key: null, source: ApiKeySource.none);
}