aKode fase 3: provider locali, chiavi per provider, modelli dal server, SearXNG

- Provider: rimossi openai, Bedrock e GCP integrati e ogni fallback a OpenAI;
  restano ollama, lmstudio e i provider personalizzati. Senza provider, exec e
  TUI mostrano come configurarlo.
- Chiave per provider: api_key = "keyring", provider_api_key_store =
  auto|keyring|file (fallback su file 0600 / ACL Windows); `codex login
  --provider <id> --with-api-key`, `logout --provider`; login status e doctor
  mostrano dove sta la chiave senza rivelarla.
- Modelli letti da GET {base_url}/models; contesto da config, poi dal server
  (/props, meta.n_ctx), poi 32768; apply_patch come tool function; niente tool
  ospitati; niente piu' avviso "metadata not found".
- Unione dei soli messaggi system/developer iniziali in un unico system;
  quelli successivi restano al loro posto come user (cache del server
  preservata: turno N prefisso esatto del turno N+1).
- Modelli ausiliari (memorie, guardian-v2) = modello di sessione se il
  preferito gpt-* non e' nel catalogo.
- Ricerca web: crate web-tools, backend SearXNG con web_search e web_fetch
  (protezione SSRF); senza backend nessuno strumento web.
- Skill: rimossa openai-docs; skill-installer punta a git.difonzo.net.
- apply_patch accetta gli header @@ -a,b +c,d @@ dei diff unificati.
- Rimossi resti: request_plugin_install, AppsInstructions, --cyber-access-program,
  URL updater/realtime predefiniti.
- Fix: importazione sessioni con provider vuoto.
- Istruzioni di sistema invariate. Test: cancellati solo quelli del codice
  rimosso, test di sicurezza adattati; restano solo fallimenti d'ambiente.
- Prova reale su imeAI + SearXNG: risposta, modifica file, web_search,
  cache riusata, connessioni solo verso .25 e .57.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-11 02:11:45 +01:00
parent 9e33707b8e
commit e39aae0085
545 changed files with 9742 additions and 24503 deletions

View File

@@ -15,6 +15,7 @@ workspace = true
[dependencies]
codex-client = { workspace = true }
codex-http-client = { workspace = true }
codex-keyring-store = { workspace = true }
codex-protocol = { workspace = true }
codex-utils-redacted-string = { workspace = true }
http = { workspace = true }
@@ -22,6 +23,7 @@ schemars = { workspace = true }
serde = { workspace = true, features = ["derive"] }
[dev-dependencies]
keyring = { workspace = true }
codex-utils-absolute-path = { workspace = true }
maplit = { workspace = true }
pretty_assertions = { workspace = true }

View File

@@ -16,6 +16,9 @@ pub struct ModelProviderCapabilities {
pub cyber_access_programs: Option<bool>,
/// Whether hosted web search may access the live web.
pub external_web_access: Option<bool>,
/// Whether the server executes the hosted `web_search` tool itself (off by default;
/// local servers usually do not). aKode's own `[web_search]` backend is separate.
pub hosted_web_search: Option<bool>,
/// Remote context-compaction protocol; omission preserves provider defaults.
pub remote_compaction: Option<RemoteCompactionSupport>,
}

View File

@@ -156,9 +156,6 @@ impl GatewayOAuthConfig {
}
pub(crate) fn validate(&self, provider: &ModelProviderInfo) -> Result<(), String> {
if provider.aws.is_some() || provider.is_amazon_bedrock() {
return Err("provider gateway_oauth cannot be combined with AWS authentication".into());
}
let base_url = provider
.base_url
.as_deref()
@@ -197,10 +194,8 @@ impl GatewayOAuthConfig {
);
}
let gateway_header = if self.delivery().is_authorization_bearer() {
if provider.is_gcp() {
return Err("Google Cloud uses the Authorization header for its own token. Remove gateway_oauth to use the built-in Google Cloud provider".into());
}
if provider.requires_openai_auth
|| provider.api_key.is_some()
|| provider.env_key.is_some()
|| provider.experimental_bearer_token.is_some()
|| provider.has_command_auth()

View File

@@ -0,0 +1,243 @@
//! Per-provider API keys stored outside config.toml (`api_key = "keyring"`).
//!
//! The process-wide [`ProviderApiKeyStore`] decides where keys live. By default it is the
//! system keyring (service [`PROVIDER_API_KEY_KEYRING_SERVICE`], account
//! `model-provider:<id>`; Keychain on macOS, Credential Manager on Windows, Secret Service
//! or keyutils on Linux). `codex-login` installs a store that follows
//! `provider_api_key_store = "auto" | "keyring" | "file"` and can fall back to a private
//! file in CODEX_HOME. Loaded keys are cached for the life of the process. Keys are never
//! logged or included in errors.
use std::collections::HashMap;
use std::fmt;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::OnceLock;
use std::sync::PoisonError;
use std::sync::RwLock;
use codex_keyring_store::DefaultKeyringStore;
use codex_keyring_store::KeyringStore;
use codex_protocol::error::CodexErr;
use codex_protocol::error::Result as CodexResult;
use crate::PROVIDER_API_KEY_KEYRING_SERVICE;
use crate::provider_api_key_keyring_account;
/// Where a provider key was found or stored. Never contains the key.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ProviderApiKeyLocation {
/// System keyring entry (service, account).
Keyring { service: String, account: String },
/// Private file (path shown to the user).
File { path: String },
/// Process memory only.
Memory,
}
impl fmt::Display for ProviderApiKeyLocation {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Keyring { service, account } => {
write!(
f,
"system keyring (service `{service}`, account `{account}`)"
)
}
Self::File { path } => write!(f, "file {path}"),
Self::Memory => f.write_str("memory (this process only)"),
}
}
}
/// Backend that stores provider API keys by provider id.
///
/// Implementations must never include key material in errors, `Debug` output or logs.
pub trait ProviderApiKeyStore: fmt::Debug + Send + Sync {
/// Loads the key for `provider_id`; `Ok(None)` when none is stored.
fn load(&self, provider_id: &str) -> Result<Option<String>, String>;
/// Stores `api_key` for `provider_id` and reports where it went.
fn save(&self, provider_id: &str, api_key: &str) -> Result<ProviderApiKeyLocation, String>;
/// Deletes the key for `provider_id`; returns whether one existed.
fn delete(&self, provider_id: &str) -> Result<bool, String>;
/// Where the key for `provider_id` currently is, if stored.
fn locate(&self, provider_id: &str) -> Result<Option<ProviderApiKeyLocation>, String>;
}
/// Keyring-only store backed by a [`KeyringStore`].
#[derive(Debug, Clone)]
pub struct KeyringProviderApiKeyStore {
keyring: Arc<dyn KeyringStore>,
}
impl KeyringProviderApiKeyStore {
pub fn new(keyring: Arc<dyn KeyringStore>) -> Self {
Self { keyring }
}
fn location(provider_id: &str) -> ProviderApiKeyLocation {
ProviderApiKeyLocation::Keyring {
service: PROVIDER_API_KEY_KEYRING_SERVICE.to_string(),
account: provider_api_key_keyring_account(provider_id),
}
}
}
impl Default for KeyringProviderApiKeyStore {
fn default() -> Self {
Self::new(Arc::new(DefaultKeyringStore))
}
}
impl ProviderApiKeyStore for KeyringProviderApiKeyStore {
fn load(&self, provider_id: &str) -> Result<Option<String>, String> {
self.keyring
.load(
PROVIDER_API_KEY_KEYRING_SERVICE,
&provider_api_key_keyring_account(provider_id),
)
.map(|key| key.filter(|key| !key.trim().is_empty()))
// The keyring error describes the backend failure, never the secret.
.map_err(|error| format!("system keyring unavailable: {}", error.message()))
}
fn save(&self, provider_id: &str, api_key: &str) -> Result<ProviderApiKeyLocation, String> {
self.keyring
.save(
PROVIDER_API_KEY_KEYRING_SERVICE,
&provider_api_key_keyring_account(provider_id),
api_key,
)
.map_err(|error| format!("system keyring unavailable: {}", error.message()))?;
Ok(Self::location(provider_id))
}
fn delete(&self, provider_id: &str) -> Result<bool, String> {
self.keyring
.delete(
PROVIDER_API_KEY_KEYRING_SERVICE,
&provider_api_key_keyring_account(provider_id),
)
.map_err(|error| format!("system keyring unavailable: {}", error.message()))
}
fn locate(&self, provider_id: &str) -> Result<Option<ProviderApiKeyLocation>, String> {
Ok(self.load(provider_id)?.map(|_| Self::location(provider_id)))
}
}
fn store_slot() -> &'static RwLock<Arc<dyn ProviderApiKeyStore>> {
static STORE: OnceLock<RwLock<Arc<dyn ProviderApiKeyStore>>> = OnceLock::new();
STORE.get_or_init(|| RwLock::new(Arc::new(KeyringProviderApiKeyStore::default())))
}
fn cache() -> &'static Mutex<HashMap<String, String>> {
static CACHE: OnceLock<Mutex<HashMap<String, String>>> = OnceLock::new();
CACHE.get_or_init(|| Mutex::new(HashMap::new()))
}
fn clear_cache() {
cache()
.lock()
.unwrap_or_else(PoisonError::into_inner)
.clear();
}
/// The process-wide provider key store.
pub fn provider_api_key_store() -> Arc<dyn ProviderApiKeyStore> {
Arc::clone(&store_slot().read().unwrap_or_else(PoisonError::into_inner))
}
/// Installs the process-wide provider key store (done by config loading).
pub fn set_provider_api_key_store(store: Arc<dyn ProviderApiKeyStore>) {
*store_slot().write().unwrap_or_else(PoisonError::into_inner) = store;
clear_cache();
}
/// Replaces the keyring backend with a keyring-only store. Intended for tests.
#[doc(hidden)]
pub fn set_provider_keyring_store_for_testing(keyring: Arc<dyn KeyringStore>) {
set_provider_api_key_store(Arc::new(KeyringProviderApiKeyStore::new(keyring)));
}
fn provider_id_from_account(account: &str) -> &str {
account.strip_prefix("model-provider:").unwrap_or(account)
}
/// Loads the key for a keyring account, failing when no non-empty key is stored.
pub(crate) fn load(account: &str) -> CodexResult<String> {
if let Some(key) = cache()
.lock()
.unwrap_or_else(PoisonError::into_inner)
.get(account)
{
return Ok(key.clone());
}
let key = load_with(provider_api_key_store().as_ref(), account)?;
cache()
.lock()
.unwrap_or_else(PoisonError::into_inner)
.insert(account.to_string(), key.clone());
Ok(key)
}
pub(crate) fn load_with(store: &dyn ProviderApiKeyStore, account: &str) -> CodexResult<String> {
let provider_id = provider_id_from_account(account);
match store.load(provider_id) {
Ok(Some(key)) if !key.trim().is_empty() => Ok(key),
Ok(_) => Err(CodexErr::UnsupportedOperation(format!(
"No API key is stored for model provider `{provider_id}`. \
Store one with: codex login --provider {provider_id} --with-api-key"
))),
Err(error) => Err(CodexErr::UnsupportedOperation(format!(
"Failed to read the API key for model provider `{provider_id}`: {error}"
))),
}
}
/// Stores `api_key` for `provider_id` in the process-wide store.
pub fn save_provider_api_key(
provider_id: &str,
api_key: &str,
) -> Result<ProviderApiKeyLocation, String> {
if api_key.trim().is_empty() {
return Err("API key must not be empty".to_string());
}
let location = provider_api_key_store()
.save(provider_id, api_key)
.map_err(|error| {
format!("Failed to store the API key for model provider `{provider_id}`: {error}")
})?;
cache()
.lock()
.unwrap_or_else(PoisonError::into_inner)
.insert(
provider_api_key_keyring_account(provider_id),
api_key.to_string(),
);
Ok(location)
}
/// Removes the stored key for `provider_id`. Returns whether a key was present.
pub fn delete_provider_api_key(provider_id: &str) -> Result<bool, String> {
cache()
.lock()
.unwrap_or_else(PoisonError::into_inner)
.remove(&provider_api_key_keyring_account(provider_id));
provider_api_key_store()
.delete(provider_id)
.map_err(|error| {
format!("Failed to delete the API key for model provider `{provider_id}`: {error}")
})
}
/// Where the key for `provider_id` is stored, without reading it into any output.
pub fn locate_provider_api_key(
provider_id: &str,
) -> Result<Option<ProviderApiKeyLocation>, String> {
provider_api_key_store().locate(provider_id)
}
#[cfg(test)]
#[path = "keyring_api_key_tests.rs"]
mod tests;

View File

@@ -0,0 +1,113 @@
use std::sync::Arc;
use codex_keyring_store::tests::MockKeyringStore;
use pretty_assertions::assert_eq;
use super::*;
use crate::ModelProviderInfo;
use crate::ProviderApiKeySource;
const SECRET: &str = "sk-test-secret-value-1234567890";
fn keyring_store(mock: &MockKeyringStore) -> KeyringProviderApiKeyStore {
KeyringProviderApiKeyStore::new(Arc::new(mock.clone()))
}
#[test]
fn keyring_store_saves_under_provider_account() {
let mock = MockKeyringStore::default();
let store = keyring_store(&mock);
let location = store.save("imeai", SECRET).expect("save");
assert_eq!(
location,
ProviderApiKeyLocation::Keyring {
service: "aKode".to_string(),
account: "model-provider:imeai".to_string(),
}
);
assert_eq!(
mock.saved_value("model-provider:imeai").as_deref(),
Some(SECRET)
);
assert_eq!(
load_with(&store, "model-provider:imeai").expect("load"),
SECRET
);
assert_eq!(store.locate("imeai").expect("locate"), Some(location));
assert!(!location_string_contains_secret(&store));
}
fn location_string_contains_secret(store: &KeyringProviderApiKeyStore) -> bool {
store
.locate("imeai")
.ok()
.flatten()
.is_some_and(|location| location.to_string().contains(SECRET))
}
#[test]
fn missing_key_error_explains_how_to_store_it() {
let store = keyring_store(&MockKeyringStore::default());
let error = load_with(&store, "model-provider:imeai")
.expect_err("missing key must fail")
.to_string();
assert!(
error.contains("codex login --provider imeai --with-api-key"),
"{error}"
);
}
#[test]
fn keyring_errors_and_debug_output_never_contain_the_key() {
let mock = MockKeyringStore::default();
let store = keyring_store(&mock);
store.save("imeai", SECRET).expect("save");
mock.set_error(
"model-provider:imeai",
keyring::Error::PlatformFailure("locked".into()),
);
let error = load_with(&store, "model-provider:imeai")
.expect_err("keyring failure must surface")
.to_string();
assert!(!error.contains(SECRET), "{error}");
assert!(!format!("{store:?}").contains(SECRET));
let provider = ModelProviderInfo {
name: "imeAI".to_string(),
base_url: Some("http://127.0.0.1:8080/v1".to_string()),
api_key: Some(ProviderApiKeySource::Keyring),
keyring_account: Some("model-provider:imeai".to_string()),
..ModelProviderInfo::default()
};
let debug = format!("{provider:?}");
assert!(!debug.contains(SECRET), "{debug}");
}
#[test]
fn provider_api_key_uses_process_store() {
let mock = MockKeyringStore::default();
set_provider_keyring_store_for_testing(Arc::new(mock));
assert_eq!(
save_provider_api_key("process-store", " ").unwrap_err(),
"API key must not be empty"
);
save_provider_api_key("process-store", SECRET).expect("save");
let provider = ModelProviderInfo {
name: "process-store".to_string(),
base_url: Some("http://127.0.0.1:8080/v1".to_string()),
api_key: Some(ProviderApiKeySource::Keyring),
keyring_account: Some(crate::provider_api_key_keyring_account("process-store")),
..ModelProviderInfo::default()
};
assert_eq!(
provider.api_key().expect("api key").as_deref(),
Some(SECRET)
);
assert!(
locate_provider_api_key("process-store")
.expect("locate")
.is_some()
);
assert_eq!(delete_provider_api_key("process-store"), Ok(true));
assert!(provider.api_key().is_err());
}

View File

@@ -8,8 +8,6 @@
//! API provider construction applies the process-wide managed residency policy also
//! used by default HTTP headers.
use codex_client::OPENAI_ORGANIZATION_HEADER;
use codex_client::OPENAI_PROJECT_HEADER;
use codex_client::Provider as ApiProvider;
use codex_client::RetryConfig as ApiRetryConfig;
use codex_protocol::config_types::ModelProviderAuthInfo;
@@ -28,19 +26,28 @@ use std::fmt;
use std::num::NonZeroU64;
use std::path::Component;
use std::path::Path;
use std::path::PathBuf;
use std::sync::PoisonError;
use std::sync::RwLock;
use std::time::Duration;
mod capabilities;
mod gateway_oauth;
mod keyring_api_key;
mod oauth_session;
pub use capabilities::ModelProviderCapabilities;
pub use capabilities::RemoteCompactionSupport;
pub use gateway_oauth::GatewayOAuthConfig;
pub use gateway_oauth::GatewayOAuthDelivery;
pub use gateway_oauth::GatewayOAuthSettings;
pub use keyring_api_key::KeyringProviderApiKeyStore;
pub use keyring_api_key::ProviderApiKeyLocation;
pub use keyring_api_key::ProviderApiKeyStore;
pub use keyring_api_key::delete_provider_api_key;
pub use keyring_api_key::locate_provider_api_key;
pub use keyring_api_key::provider_api_key_store;
pub use keyring_api_key::save_provider_api_key;
pub use keyring_api_key::set_provider_api_key_store;
pub use keyring_api_key::set_provider_keyring_store_for_testing;
pub use oauth_session::OAuthCredentialsStore;
pub use oauth_session::OAuthSessionConfig;
@@ -73,38 +80,32 @@ const DEFAULT_STREAM_IDLE_TIMEOUT_MS: u64 = 300_000;
const DEFAULT_STREAM_MAX_RETRIES: u64 = 5;
const DEFAULT_REQUEST_MAX_RETRIES: u64 = 4;
const DEFAULT_CREDENTIAL_EXPORT_TIMEOUT_MS: u64 = 30_000;
const DEFAULT_AWS_AUTH_REFRESH_TIMEOUT_MS: u64 = 300_000;
pub const DEFAULT_WEBSOCKET_CONNECT_TIMEOUT_MS: u64 = 15_000;
/// Hard cap for user-configured `stream_max_retries`.
const MAX_STREAM_MAX_RETRIES: u64 = 100;
/// Hard cap for user-configured `request_max_retries`.
const MAX_REQUEST_MAX_RETRIES: u64 = 100;
pub const OPENAI_PROVIDER_NAME: &str = "OpenAI";
pub const OPENAI_PROVIDER_ID: &str = "openai";
pub const CHATGPT_CODEX_BASE_URL: &str = "https://chatgpt.com/backend-api/codex";
pub const AMAZON_BEDROCK_PROVIDER_NAME: &str = "Amazon Bedrock";
pub const AMAZON_BEDROCK_PROVIDER_ID: &str = "amazon-bedrock";
pub const AMAZON_BEDROCK_RUNTIME_PROVIDER_NAME: &str = "Amazon Bedrock Runtime";
pub const AMAZON_BEDROCK_RUNTIME_PROVIDER_ID: &str = "amazon-bedrock-runtime";
pub const GCP_PROVIDER_NAME: &str = "Google Cloud Vertex AI";
pub const GCP_PROVIDER_ID: &str = "gcp";
pub const AMAZON_BEDROCK_GPT_5_5_MODEL_ID: &str = "openai.gpt-5.5";
pub const AMAZON_BEDROCK_GPT_5_6_SOL_MODEL_ID: &str = "openai.gpt-5.6-sol";
pub const AMAZON_BEDROCK_GPT_6_1_SOL_MODEL_ID: &str = "openai.gpt-6.1-sol";
pub const AMAZON_BEDROCK_GPT_6_1_TERRA_MODEL_ID: &str = "openai.gpt-6.1-terra";
pub const AMAZON_BEDROCK_GPT_6_SOL_MODEL_ID: &str = "openai.gpt-6-sol";
pub const AMAZON_BEDROCK_GPT_6_LUNA_MODEL_ID: &str = "openai.gpt-6-luna";
pub const AMAZON_BEDROCK_GPT_6_ASTRA_MODEL_ID: &str = "openai.gpt-6-astra";
pub const AMAZON_BEDROCK_GPT_5_6_TERRA_MODEL_ID: &str = "openai.gpt-5.6-terra";
pub const AMAZON_BEDROCK_GPT_5_6_LUNA_MODEL_ID: &str = "openai.gpt-5.6-luna";
pub const AMAZON_BEDROCK_RUNTIME_GLOBAL_GPT_5_6_TERRA_MODEL_ID: &str =
"global.openai.gpt-5.6-terra";
pub const AMAZON_BEDROCK_RUNTIME_GLOBAL_GPT_5_6_LUNA_MODEL_ID: &str = "global.openai.gpt-5.6-luna";
pub const AMAZON_BEDROCK_DEFAULT_BASE_URL: &str =
"https://bedrock-mantle.us-east-1.api.aws/openai/v1";
const AMAZON_BEDROCK_MANTLE_CLIENT_AGENT_HEADER: &str = "x-amzn-mantle-client-agent";
const AMAZON_BEDROCK_MANTLE_CLIENT_AGENT_VALUE: &str = "codex";
/// Keyring service under which per-provider API keys are stored.
pub const PROVIDER_API_KEY_KEYRING_SERVICE: &str = "aKode";
/// Error shown when no model provider is configured.
pub const NO_MODEL_PROVIDER_CONFIGURED_ERROR: &str = concat!(
"No model provider is configured.\n",
"aKode does not ship a default provider. Add one to config.toml ",
"(in CODEX_HOME, default ~/.codex), for example:\n",
"\n",
" model_provider = \"local\"\n",
" model = \"<model id served by your server>\"\n",
"\n",
" [model_providers.local]\n",
" name = \"My server\"\n",
" base_url = \"http://127.0.0.1:8080/v1\" # must implement POST {base_url}/responses\n",
" api_key = \"keyring\" # store it with: codex login --provider local --with-api-key\n",
" # or instead: env_key = \"MY_SERVER_API_KEY\"\n",
"\n",
"Built-in local providers: model_provider = \"ollama\" (http://localhost:11434/v1) ",
"or model_provider = \"lmstudio\" (http://localhost:1234/v1).",
);
const CHAT_WIRE_API_REMOVED_ERROR: &str = "`wire_api = \"chat\"` is no longer supported.\nHow to fix: set `wire_api = \"responses\"` in your provider config.\nMore info: https://github.com/openai/codex/discussions/7782";
pub const LEGACY_OLLAMA_CHAT_PROVIDER_ID: &str = "ollama-chat";
pub const OLLAMA_CHAT_PROVIDER_REMOVED_ERROR: &str = "`ollama-chat` is no longer supported.\nHow to fix: replace `ollama-chat` with `ollama` in `model_provider`, `oss_provider`, or `--local-provider`.\nMore info: https://github.com/openai/codex/discussions/7782";
@@ -150,18 +151,11 @@ pub struct ModelProviderInfo {
pub name: String,
/// Base URL for the provider's OpenAI-compatible API.
pub base_url: Option<String>,
/// Optional full URL for a Codex-native model catalog. When unset, OpenAI discovery
/// uses the Codex backend unless `base_url` overrides the inference endpoint.
/// The endpoint must serve the Codex catalog format, not the public `/v1/models` API.
/// Optional full URL for a Codex-native model catalog (Codex catalog format, not the
/// public `/v1/models` API). When unset, models are listed from `GET {base_url}/models`.
///
/// For built-in OpenAI, set this under `[model_providers.openai]`; other non-default
/// provider overrides are rejected. The URL must use HTTPS and an allowed ChatGPT
/// host. Other hosts require a custom provider. Inference still uses `openai_base_url`.
///
/// Catalog requests use the provider's credentials, including an API key or ChatGPT
/// access token. Only configure an endpoint you trust with those credentials.
/// Setting this URL does not grant catalog access or guarantee that the endpoint
/// accepts a regional API key. Existing discovery gates and entitlement checks apply.
/// Catalog requests use the provider's credentials. Only configure an endpoint you trust
/// with those credentials.
pub model_catalog_url: Option<RedactedString>,
/// Environment variable that stores the user's API key for this provider.
pub env_key: Option<String>,
@@ -177,17 +171,10 @@ pub struct ModelProviderInfo {
pub auth: Option<ModelProviderAuthInfo>,
/// Gateway access token from OAuth or a credential export command.
pub gateway_oauth: Option<GatewayOAuthConfig>,
/// AWS SigV4 auth configuration for this provider.
pub aws: Option<ModelProviderAwsAuthInfo>,
/// Google Cloud project ID for the built-in GCP provider. Takes precedence
/// over `GOOGLE_CLOUD_PROJECT` when deriving the Vertex AI endpoint.
pub project_id: Option<String>,
/// Google Cloud location for the built-in GCP provider. Takes precedence
/// over `GOOGLE_CLOUD_LOCATION`; defaults to `global` when neither is set.
pub location: Option<String>,
/// Absolute path to a Google ADC credential file. For GCP, overrides
/// GOOGLE_APPLICATION_CREDENTIALS in the auth command's environment only.
pub credential_file: Option<PathBuf>,
/// Where to read this provider's API key from. `"keyring"` reads the key stored with
/// `codex login --provider <id> --with-api-key`: in the system keyring, or in a private
/// file in CODEX_HOME when `provider_api_key_store` selects (or falls back to) file storage.
pub api_key: Option<ProviderApiKeySource>,
/// Which wire protocol this provider expects.
#[serde(default)]
pub wire_api: WireApi,
@@ -214,13 +201,17 @@ pub struct ModelProviderInfo {
/// Maximum time (in milliseconds) to wait for a websocket connection attempt before treating
/// it as failed.
pub websocket_connect_timeout_ms: Option<u64>,
/// Does this provider require an OpenAI API key or ChatGPT login token? If true,
/// the user is presented with a login screen on first run, and credentials are
/// stored using the backend selected by `cli_auth_credentials_store`.
/// If false (the default), the login screen is skipped, and the API key
/// (if needed) comes from the environment variable specified by `env_key`.
#[serde(default)]
/// Use the API key stored with `codex login --with-api-key` (in `auth.json` or the
/// credentials store selected by `cli_auth_credentials_store`) for this provider.
/// `use_stored_api_key` is accepted as a clearer alias. When false (the default),
/// the key comes from `api_key`, `env_key`, or `auth`, if any.
#[serde(default, alias = "use_stored_api_key")]
pub requires_openai_auth: bool,
/// Merge the base instructions and the leading system/developer messages into one
/// leading system block; later system/developer messages stay in place as user
/// messages. Many local chat templates reject multiple or non-leading system messages.
/// Defaults to true.
pub merge_system_messages: Option<bool>,
/// Whether this provider supports the Responses API WebSocket transport.
#[serde(default)]
pub supports_websockets: bool,
@@ -232,20 +223,11 @@ pub struct ModelProviderInfo {
#[serde(skip)]
#[schemars(skip)]
pub include_internal_metadata: bool,
}
/// AWS SigV4 auth configuration for a model provider.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct ModelProviderAwsAuthInfo {
/// AWS profile name to use. When unset, the AWS SDK default chain decides.
pub profile: Option<String>,
/// AWS region to use for provider-specific endpoints.
pub region: Option<String>,
/// Optional command whose exported credentials replace the AWS SDK credential chain.
pub credential_export: Option<AwsCredentialExportConfig>,
/// Optional command used to reauthenticate after a refreshable AWS auth failure.
pub auth_refresh: Option<AwsAuthRefreshConfig>,
/// Runtime-only keyring account for `api_key = "keyring"`; set from the provider id
/// when configured providers are merged. Never serialized.
#[serde(skip)]
#[schemars(skip)]
pub keyring_account: Option<String>,
}
/// Command used to export credentials for a model provider.
@@ -262,8 +244,6 @@ pub struct CredentialExportConfig {
pub timeout_ms: NonZeroU64,
}
pub type AwsCredentialExportConfig = CredentialExportConfig;
impl CredentialExportConfig {
pub fn validate(&self, field: &str) -> Result<(), String> {
if self.command.trim().is_empty() {
@@ -293,79 +273,42 @@ fn default_credential_export_timeout_ms() -> NonZeroU64 {
}
}
/// Command used to refresh AWS credentials for a model provider.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct AwsAuthRefreshConfig {
/// Executable to invoke directly, without a shell.
pub command: String,
/// Arguments passed to the refresh command.
#[serde(default)]
pub args: Vec<RedactedString>,
/// Maximum time to wait for the refresh command to complete.
#[serde(default = "default_aws_auth_refresh_timeout_ms")]
pub timeout_ms: NonZeroU64,
/// Source of a provider API key configured through `api_key`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum ProviderApiKeySource {
/// Read the key from the system keyring (service `aKode`, account `model-provider:<id>`).
Keyring,
}
impl AwsAuthRefreshConfig {
pub fn timeout(&self) -> Duration {
Duration::from_millis(self.timeout_ms.get())
impl<'de> Deserialize<'de> for ProviderApiKeySource {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let value = String::deserialize(deserializer)?;
match value.as_str() {
"keyring" => Ok(Self::Keyring),
// Never echo the value: it may be a literal API key pasted by mistake.
_ => Err(serde::de::Error::custom(
"provider api_key must be \"keyring\"; literal API keys are not accepted in \
config.toml. Store the key with `codex login --provider <id> --with-api-key`, or use env_key",
)),
}
}
}
fn default_aws_auth_refresh_timeout_ms() -> NonZeroU64 {
match NonZeroU64::new(DEFAULT_AWS_AUTH_REFRESH_TIMEOUT_MS) {
Some(timeout_ms) => timeout_ms,
None => panic!("AWS auth refresh timeout must be non-zero"),
}
/// Keyring account that stores the API key for a provider id.
pub fn provider_api_key_keyring_account(provider_id: &str) -> String {
format!("model-provider:{provider_id}")
}
impl ModelProviderInfo {
/// Checks that a configured Bedrock entry only customizes supported fields.
/// Call this on the override before merging it with the built-in provider.
pub fn validate_bedrock_override(&self) -> Result<(), String> {
let unsupported_fields = Self {
base_url: None,
auth: None,
aws: None,
http_headers: None,
..self.clone()
};
if unsupported_fields != Self::default() {
return Err("only supports changing \
`base_url`, `auth`, `http_headers`, `aws.profile`, `aws.region`, `aws.credential_export`, \
and `aws.auth_refresh`; \
other non-default provider fields are not supported"
.to_string());
}
Ok(())
}
/// Checks the credential-file path for a GCP provider or built-in GCP override.
pub fn validate_gcp_credential_file(&self) -> Result<(), String> {
if let Some(credential_file) = &self.credential_file
&& !credential_file.is_absolute()
{
return Err("provider credential_file must be an absolute path".to_string());
}
Ok(())
}
pub fn validate(&self) -> std::result::Result<(), String> {
if self.is_gcp() {
self.validate_gcp_credential_file()?;
}
if let Some(gateway) = &self.gateway_oauth {
gateway.validate(self)?;
}
if let Some(aws) = self.aws.as_ref() {
if self.supports_websockets {
// TODO(celia-oai): Support AWS SigV4 signing for WebSocket
// upgrade requests before allowing AWS-authenticated providers
// to enable Responses-over-WebSocket.
return Err("provider aws cannot be combined with supports_websockets".to_string());
}
if self.api_key.is_some() {
let mut conflicts = Vec::new();
if self.env_key.is_some() {
conflicts.push("env_key");
@@ -379,32 +322,12 @@ other non-default provider fields are not supported"
if self.requires_openai_auth {
conflicts.push("requires_openai_auth");
}
if !conflicts.is_empty() {
return Err(format!(
"provider aws cannot be combined with {}",
"provider api_key cannot be combined with {}",
conflicts.join(", ")
));
}
if let Some(credential_export) = aws.credential_export.as_ref() {
if aws.profile.is_some() {
return Err(
"provider aws.credential_export cannot be combined with aws.profile"
.to_string(),
);
}
credential_export.validate("aws.credential_export")?;
}
if let Some(auth_refresh) = aws.auth_refresh.as_ref() {
if auth_refresh.command.trim().is_empty() {
return Err("provider aws.auth_refresh.command must not be empty".to_string());
}
if auth_refresh.command != "aws" {
return Err("provider aws.auth_refresh.command must be `aws`".to_string());
}
}
}
let Some(auth) = self.auth.as_ref() else {
@@ -468,11 +391,18 @@ other non-default provider fields are not supported"
/// Builds an API provider with managed residency taking precedence over configured headers.
pub fn to_api_provider(&self) -> CodexResult<ApiProvider> {
let default_base_url = "https://api.openai.com/v1";
// There is no default endpoint: a provider without base_url is never contacted.
let base_url = self
.base_url
.clone()
.unwrap_or_else(|| default_base_url.to_string());
.filter(|base_url| !base_url.trim().is_empty())
.ok_or_else(|| {
CodexErr::UnsupportedOperation(if self.is_unconfigured() {
NO_MODEL_PROVIDER_CONFIGURED_ERROR.to_string()
} else {
format!("model provider `{}` has no base_url", self.name)
})
})?;
let mut headers = self.build_header_map()?;
if let Some(requirement) = read_managed_residency_requirement() {
@@ -504,10 +434,21 @@ other non-default provider fields are not supported"
})
}
/// If `env_key` is Some, returns the API key for this provider if present
/// (and non-empty) in the environment. If `env_key` is required but
/// cannot be found, returns an error.
/// Returns the API key configured for this provider, if any.
///
/// `env_key` reads the named environment variable; `api_key = "keyring"` reads the key
/// stored in the system keyring for this provider id. A configured source that yields no
/// key is an error. The key itself is never included in errors or logs.
pub fn api_key(&self) -> CodexResult<Option<String>> {
if let Some(ProviderApiKeySource::Keyring) = self.api_key {
let account = self.keyring_account.as_deref().ok_or_else(|| {
CodexErr::UnsupportedOperation(format!(
"model provider `{}` uses api_key = \"keyring\" but its id is unknown",
self.name
))
})?;
return keyring_api_key::load(account).map(Some);
}
match &self.env_key {
Some(env_key) => {
let api_key = std::env::var(env_key)
@@ -525,6 +466,11 @@ other non-default provider fields are not supported"
}
}
/// Whether system/developer messages are merged into one leading system block.
pub fn merge_system_messages(&self) -> bool {
self.merge_system_messages.unwrap_or(true)
}
/// Effective maximum number of request retries for this provider.
pub fn request_max_retries(&self) -> u64 {
self.request_max_retries
@@ -553,153 +499,27 @@ other non-default provider fields are not supported"
.unwrap_or(Duration::from_millis(DEFAULT_WEBSOCKET_CONNECT_TIMEOUT_MS))
}
pub fn create_openai_provider(base_url: Option<String>) -> ModelProviderInfo {
/// Placeholder used when no `model_provider` is configured. It has no endpoint, so any
/// attempt to use it fails with [`NO_MODEL_PROVIDER_CONFIGURED_ERROR`].
pub fn unconfigured() -> ModelProviderInfo {
ModelProviderInfo::default()
}
/// Whether this is the placeholder returned by [`ModelProviderInfo::unconfigured`].
pub fn is_unconfigured(&self) -> bool {
self.name.is_empty() && self.base_url.is_none()
}
/// A generic Responses-compatible provider at `base_url`, using the stored API key.
pub fn create_responses_provider(name: &str, base_url: Option<String>) -> ModelProviderInfo {
ModelProviderInfo {
name: OPENAI_PROVIDER_NAME.into(),
name: name.to_string(),
base_url,
model_catalog_url: None,
env_key: None,
env_key_instructions: None,
experimental_bearer_token: None,
auth: None,
gateway_oauth: None,
aws: None,
wire_api: WireApi::Responses,
query_params: None,
http_headers: Some(
[("version".to_string(), env!("CARGO_PKG_VERSION").into())]
.into_iter()
.collect(),
),
env_http_headers: Some(
[
(
OPENAI_ORGANIZATION_HEADER.to_string(),
"OPENAI_ORGANIZATION".to_string(),
),
(
OPENAI_PROJECT_HEADER.to_string(),
"OPENAI_PROJECT".to_string(),
),
]
.into_iter()
.collect(),
),
// Use global defaults for retry/timeout unless overridden in config.toml.
request_max_retries: None,
stream_max_retries: None,
stream_idle_timeout_ms: None,
websocket_connect_timeout_ms: None,
requires_openai_auth: true,
supports_websockets: true,
supports_standalone_web_search: true,
capabilities: None,
project_id: None,
location: None,
credential_file: None,
include_internal_metadata: true,
..ModelProviderInfo::default()
}
}
pub fn create_amazon_bedrock_provider(
aws: Option<ModelProviderAwsAuthInfo>,
) -> ModelProviderInfo {
ModelProviderInfo {
name: AMAZON_BEDROCK_PROVIDER_NAME.into(),
// The runtime provider derives the regional Mantle endpoint when
// this is unset. A configured value is therefore unambiguously an
// endpoint override.
base_url: None,
model_catalog_url: None,
env_key: None,
env_key_instructions: None,
experimental_bearer_token: None,
auth: None,
gateway_oauth: None,
aws: Some(aws.unwrap_or(ModelProviderAwsAuthInfo {
profile: None,
region: None,
credential_export: None,
auth_refresh: None,
})),
wire_api: WireApi::Responses,
query_params: None,
http_headers: Some(HashMap::from([(
AMAZON_BEDROCK_MANTLE_CLIENT_AGENT_HEADER.to_string(),
AMAZON_BEDROCK_MANTLE_CLIENT_AGENT_VALUE.into(),
)])),
env_http_headers: None,
request_max_retries: None,
stream_max_retries: None,
stream_idle_timeout_ms: None,
websocket_connect_timeout_ms: None,
requires_openai_auth: false,
supports_websockets: false,
supports_standalone_web_search: false,
capabilities: None,
project_id: None,
location: None,
credential_file: None,
include_internal_metadata: false,
}
}
pub fn create_amazon_bedrock_runtime_provider(
aws: Option<ModelProviderAwsAuthInfo>,
) -> ModelProviderInfo {
let mut provider = Self::create_amazon_bedrock_provider(aws);
provider.name = AMAZON_BEDROCK_RUNTIME_PROVIDER_NAME.into();
provider
}
pub fn create_gcp_provider() -> ModelProviderInfo {
ModelProviderInfo {
name: GCP_PROVIDER_NAME.into(),
base_url: None,
model_catalog_url: None,
env_key: None,
env_key_instructions: None,
experimental_bearer_token: None,
// Config loading supplies default command auth after resolving its working directory.
auth: None,
gateway_oauth: None,
aws: None,
capabilities: None,
wire_api: WireApi::Responses,
query_params: None,
http_headers: None,
env_http_headers: None,
request_max_retries: None,
stream_max_retries: None,
stream_idle_timeout_ms: None,
websocket_connect_timeout_ms: None,
requires_openai_auth: false,
supports_websockets: false,
supports_standalone_web_search: false,
project_id: None,
location: None,
credential_file: None,
include_internal_metadata: false,
}
}
pub fn is_openai(&self) -> bool {
self.name == OPENAI_PROVIDER_NAME
}
pub fn is_amazon_bedrock(&self) -> bool {
self.name == AMAZON_BEDROCK_PROVIDER_NAME
|| self.name == AMAZON_BEDROCK_RUNTIME_PROVIDER_NAME
}
pub fn is_amazon_bedrock_runtime(&self) -> bool {
self.name == AMAZON_BEDROCK_RUNTIME_PROVIDER_NAME
}
pub fn is_gcp(&self) -> bool {
self.name == GCP_PROVIDER_NAME
}
pub fn has_command_auth(&self) -> bool {
self.auth.is_some()
}
@@ -711,27 +531,10 @@ pub const DEFAULT_OLLAMA_PORT: u16 = 11434;
pub const LMSTUDIO_OSS_PROVIDER_ID: &str = "lmstudio";
pub const OLLAMA_OSS_PROVIDER_ID: &str = "ollama";
/// Built-in default provider list.
pub fn built_in_model_providers(
openai_base_url: Option<String>,
) -> HashMap<String, ModelProviderInfo> {
use ModelProviderInfo as P;
let openai_provider = P::create_openai_provider(openai_base_url);
let amazon_bedrock_provider = P::create_amazon_bedrock_provider(/*aws*/ None);
let amazon_bedrock_runtime_provider =
P::create_amazon_bedrock_runtime_provider(/*aws*/ None);
let gcp_provider = P::create_gcp_provider();
// Bundle OpenAI, supported cloud-hosted OpenAI backends, and local OSS providers.
// Other compatible providers can be added through `model_providers` in config.toml.
/// Built-in provider list: only the local OSS servers. Everything else is configured
/// under `model_providers` in config.toml.
pub fn built_in_model_providers() -> HashMap<String, ModelProviderInfo> {
[
(OPENAI_PROVIDER_ID, openai_provider),
(AMAZON_BEDROCK_PROVIDER_ID, amazon_bedrock_provider),
(GCP_PROVIDER_ID, gcp_provider),
(
AMAZON_BEDROCK_RUNTIME_PROVIDER_ID,
amazon_bedrock_runtime_provider,
),
(
OLLAMA_OSS_PROVIDER_ID,
create_oss_provider(DEFAULT_OLLAMA_PORT, WireApi::Responses),
@@ -748,99 +551,23 @@ pub fn built_in_model_providers(
/// Merge configured providers into the built-in provider catalog.
///
/// Configured providers extend the built-in set. Built-in providers are not
/// generally overridable. OpenAI allows a catalog URL override, while the
/// cloud-hosted OpenAI providers allow a limited
/// set of endpoint, authentication, header, and cloud-specific overrides.
/// Configured providers extend the built-in set; built-in providers are not overridable.
/// Each configured provider learns its id as its keyring account.
pub fn merge_configured_model_providers(
mut model_providers: HashMap<String, ModelProviderInfo>,
configured_model_providers: HashMap<String, ModelProviderInfo>,
) -> Result<HashMap<String, ModelProviderInfo>, String> {
for (key, mut provider) in configured_model_providers {
if key == "openai" {
// Keep the built-in identity, inference routing, and authentication.
// Only catalog routing is configurable through this provider entry.
// aKode never routes the built-in OpenAI provider's catalog to a ChatGPT host;
// catalogs from any other host need a custom model_provider.
if provider.model_catalog_url.is_some() {
return Err("model_providers.openai.model_catalog_url is not supported. If you need a model catalog, configure a custom model_provider".to_string());
}
} else if matches!(
key.as_str(),
AMAZON_BEDROCK_PROVIDER_ID | AMAZON_BEDROCK_RUNTIME_PROVIDER_ID
) {
provider
.validate_bedrock_override()
.map_err(|message| format!("model_providers.{key} {message}"))?;
let base_url_override = provider.base_url.take();
let auth_override = provider.auth.take();
let aws_override = provider.aws.take();
let http_headers_override = provider.http_headers.take();
if let Some(built_in_provider) = model_providers.get_mut(&key) {
built_in_provider.base_url = base_url_override;
built_in_provider.auth = auth_override;
if let Some(aws_override) = aws_override {
built_in_provider.aws = Some(aws_override);
}
if let Some(http_headers_override) = http_headers_override {
built_in_provider
.http_headers
.get_or_insert_default()
.extend(http_headers_override);
}
}
} else if key == GCP_PROVIDER_ID {
merge_gcp_provider_overrides(model_providers.get_mut(&key), provider)?;
} else {
model_providers.entry(key).or_insert(provider);
provider.keyring_account = Some(provider_api_key_keyring_account(&key));
if provider.name.trim().is_empty() {
provider.name = key.clone();
}
model_providers.entry(key).or_insert(provider);
}
Ok(model_providers)
}
/// Validates GCP overrides and applies them when the built-in provider is present.
pub fn merge_gcp_provider_overrides(
built_in: Option<&mut ModelProviderInfo>,
mut overrides: ModelProviderInfo,
) -> Result<(), String> {
overrides
.validate_gcp_credential_file()
.and_then(|()| overrides.validate())
.map_err(|message| format!("model_providers.{GCP_PROVIDER_ID} {message}"))?;
let base_url = overrides.base_url.take();
let auth = overrides.auth.take();
let credential_file = overrides.credential_file.take();
let http_headers = overrides.http_headers.take();
let project_id = overrides.project_id.take();
let location = overrides.location.take();
if overrides != ModelProviderInfo::default() {
return Err(format!(
"model_providers.{GCP_PROVIDER_ID} only supports changing \
`base_url`, `auth`, `http_headers`, `project_id`, `location`, and `credential_file`; other non-default provider fields are not supported"
));
}
if let Some(provider) = built_in {
provider.project_id = project_id;
provider.location = location;
provider.credential_file = credential_file;
if let Some(base_url) = base_url {
provider.base_url = Some(base_url);
}
if let Some(auth) = auth {
provider.auth = Some(auth);
}
if let Some(http_headers) = http_headers {
provider
.http_headers
.get_or_insert_default()
.extend(http_headers);
}
}
Ok(())
}
pub fn create_oss_provider(default_provider_port: u16, wire_api: WireApi) -> ModelProviderInfo {
// These CODEX_OSS_ environment variables are experimental: we may
// switch to reading values from config.toml instead.
@@ -870,7 +597,7 @@ pub fn create_oss_provider_with_base_url(base_url: &str, wire_api: WireApi) -> M
experimental_bearer_token: None,
auth: None,
gateway_oauth: None,
aws: None,
api_key: None,
wire_api,
query_params: None,
http_headers: None,
@@ -883,10 +610,9 @@ pub fn create_oss_provider_with_base_url(base_url: &str, wire_api: WireApi) -> M
supports_websockets: false,
supports_standalone_web_search: false,
capabilities: None,
project_id: None,
location: None,
credential_file: None,
merge_system_messages: None,
include_internal_metadata: false,
keyring_account: None,
}
}

View File

@@ -28,7 +28,10 @@ fn test_api_provider_applies_current_managed_residency() {
"X-OpenAI-Internal-Codex-Residency".to_string() => "eu".into(),
"x-provider-header".to_string() => "preserved".into(),
}),
..ModelProviderInfo::create_openai_provider(/*base_url*/ None)
..ModelProviderInfo::create_responses_provider(
"test",
Some("https://example.test/v1".to_string()),
)
};
let original_info = info.clone();
let previous_requirement = read_managed_residency_requirement();
@@ -84,7 +87,7 @@ base_url = "http://localhost:11434/v1"
experimental_bearer_token: None,
auth: None,
gateway_oauth: None,
aws: None,
api_key: None,
wire_api: WireApi::Responses,
query_params: None,
http_headers: None,
@@ -97,9 +100,8 @@ base_url = "http://localhost:11434/v1"
supports_websockets: false,
supports_standalone_web_search: false,
capabilities: None,
project_id: None,
location: None,
credential_file: None,
merge_system_messages: None,
keyring_account: None,
include_internal_metadata: false,
};
@@ -124,7 +126,7 @@ query_params = { api-version = "2025-04-01-preview" }
experimental_bearer_token: None,
auth: None,
gateway_oauth: None,
aws: None,
api_key: None,
wire_api: WireApi::Responses,
query_params: Some(maplit::hashmap! {
"api-version".to_string() => "2025-04-01-preview".into(),
@@ -139,9 +141,8 @@ query_params = { api-version = "2025-04-01-preview" }
supports_websockets: false,
supports_standalone_web_search: false,
capabilities: None,
project_id: None,
location: None,
credential_file: None,
merge_system_messages: None,
keyring_account: None,
include_internal_metadata: false,
};
@@ -168,7 +169,7 @@ supports_standalone_web_search = true
experimental_bearer_token: None,
auth: None,
gateway_oauth: None,
aws: None,
api_key: None,
wire_api: WireApi::Responses,
query_params: None,
http_headers: Some(maplit::hashmap! {
@@ -185,9 +186,8 @@ supports_standalone_web_search = true
supports_websockets: false,
supports_standalone_web_search: true,
capabilities: None,
project_id: None,
location: None,
credential_file: None,
merge_system_messages: None,
keyring_account: None,
include_internal_metadata: false,
};
@@ -249,204 +249,6 @@ args = ["--format=text"]
);
}
#[test]
fn test_deserialize_provider_aws_config() {
let provider_toml = r#"
name = "Amazon Bedrock"
base_url = "https://bedrock.example.com/v1"
[aws]
region = "us-west-2"
[aws.credential_export]
command = "aws-vault"
args = ["--profile", "codex-bedrock"]
[aws.auth_refresh]
command = "aws"
args = ["login", "--profile", "codex-bedrock"]
"#;
let provider: ModelProviderInfo = toml::from_str(provider_toml).unwrap();
assert_eq!(
provider.aws,
Some(ModelProviderAwsAuthInfo {
profile: None,
region: Some("us-west-2".to_string()),
credential_export: Some(AwsCredentialExportConfig {
command: "aws-vault".to_string(),
args: vec!["--profile".into(), "codex-bedrock".into()],
timeout_ms: NonZeroU64::new(30_000).expect("timeout should be non-zero"),
}),
auth_refresh: Some(AwsAuthRefreshConfig {
command: "aws".to_string(),
args: vec!["login".into(), "--profile".into(), "codex-bedrock".into()],
timeout_ms: NonZeroU64::new(300_000).expect("timeout should be non-zero"),
}),
})
);
}
#[test]
fn test_create_amazon_bedrock_provider() {
assert_eq!(
ModelProviderInfo::create_amazon_bedrock_provider(/*aws*/ None),
ModelProviderInfo {
name: "Amazon Bedrock".to_string(),
base_url: None,
model_catalog_url: None,
env_key: None,
env_key_instructions: None,
experimental_bearer_token: None,
auth: None,
gateway_oauth: None,
aws: Some(ModelProviderAwsAuthInfo {
profile: None,
region: None,
credential_export: None,
auth_refresh: None,
}),
wire_api: WireApi::Responses,
query_params: None,
http_headers: Some(maplit::hashmap! {
AMAZON_BEDROCK_MANTLE_CLIENT_AGENT_HEADER.to_string() =>
AMAZON_BEDROCK_MANTLE_CLIENT_AGENT_VALUE.into(),
}),
env_http_headers: None,
request_max_retries: None,
stream_max_retries: None,
stream_idle_timeout_ms: None,
websocket_connect_timeout_ms: None,
requires_openai_auth: false,
supports_websockets: false,
supports_standalone_web_search: false,
capabilities: None,
project_id: None,
location: None,
credential_file: None,
include_internal_metadata: false,
}
);
}
#[test]
fn test_create_amazon_bedrock_runtime_provider() {
let mut expected = ModelProviderInfo::create_amazon_bedrock_provider(/*aws*/ None);
expected.name = "Amazon Bedrock Runtime".to_string();
assert_eq!(
ModelProviderInfo::create_amazon_bedrock_runtime_provider(/*aws*/ None),
expected
);
}
#[test]
fn test_create_amazon_bedrock_runtime_provider_with_aws_configuration() {
let provider =
ModelProviderInfo::create_amazon_bedrock_runtime_provider(Some(ModelProviderAwsAuthInfo {
profile: Some("runtime-profile".to_string()),
region: Some("us-west-2".to_string()),
credential_export: None,
auth_refresh: None,
}));
assert_eq!(
(
provider.name.as_str(),
provider.aws,
provider.http_headers,
provider.supports_standalone_web_search,
),
(
"Amazon Bedrock Runtime",
Some(ModelProviderAwsAuthInfo {
profile: Some("runtime-profile".to_string()),
region: Some("us-west-2".to_string()),
credential_export: None,
auth_refresh: None,
}),
Some(maplit::hashmap! {
AMAZON_BEDROCK_MANTLE_CLIENT_AGENT_HEADER.to_string() =>
AMAZON_BEDROCK_MANTLE_CLIENT_AGENT_VALUE.into(),
}),
false,
)
);
}
fn provider_auth_for_test() -> ModelProviderAuthInfo {
ModelProviderAuthInfo {
command: "token-fetcher".to_string(),
args: vec!["fetch".into()],
timeout_ms: NonZeroU64::new(5_000).expect("timeout should be non-zero"),
refresh_interval_ms: 300_000,
cwd: std::env::current_dir()
.expect("current directory should be available")
.try_into()
.expect("current directory should be absolute"),
}
}
#[test]
fn test_amazon_bedrock_providers_add_mantle_client_agent_header() {
for provider in [
ModelProviderInfo::create_amazon_bedrock_provider(/*aws*/ None),
ModelProviderInfo::create_amazon_bedrock_runtime_provider(/*aws*/ None),
] {
let api_provider = provider
.to_api_provider()
.expect("Amazon Bedrock provider should build API provider");
assert_eq!(
api_provider
.headers
.get(AMAZON_BEDROCK_MANTLE_CLIENT_AGENT_HEADER)
.and_then(|value| value.to_str().ok()),
Some(AMAZON_BEDROCK_MANTLE_CLIENT_AGENT_VALUE),
"provider: {}",
provider.name
);
}
}
#[test]
fn test_built_in_model_providers_include_amazon_bedrock_endpoints() {
let providers = built_in_model_providers(/*openai_base_url*/ None);
assert_eq!(
[
AMAZON_BEDROCK_PROVIDER_ID,
AMAZON_BEDROCK_RUNTIME_PROVIDER_ID
]
.into_iter()
.map(|provider_id| {
providers
.get(provider_id)
.map(ModelProviderInfo::is_amazon_bedrock)
})
.collect::<Vec<_>>(),
vec![Some(true), Some(true)]
);
}
#[test]
fn test_built_in_model_providers_include_amazon_bedrock_runtime() {
let providers = built_in_model_providers(/*openai_base_url*/ None);
let runtime = providers
.get(AMAZON_BEDROCK_RUNTIME_PROVIDER_ID)
.expect("Amazon Bedrock Runtime provider should be built in");
assert!(runtime.is_amazon_bedrock());
assert!(runtime.is_amazon_bedrock_runtime());
assert!(
!providers
.get(AMAZON_BEDROCK_PROVIDER_ID)
.expect("Amazon Bedrock provider should be built in")
.is_amazon_bedrock_runtime()
);
}
#[test]
fn test_merge_configured_model_providers_adds_custom_provider() {
let custom_provider = ModelProviderInfo {
@@ -457,433 +259,21 @@ fn test_merge_configured_model_providers_adds_custom_provider() {
let configured_model_providers =
std::collections::HashMap::from([("custom".to_string(), custom_provider.clone())]);
let mut expected = built_in_model_providers(/*openai_base_url*/ None);
expected.insert("custom".to_string(), custom_provider);
let mut expected = built_in_model_providers();
expected.insert(
"custom".to_string(),
ModelProviderInfo {
keyring_account: Some("model-provider:custom".to_string()),
..custom_provider
},
);
assert_eq!(
merge_configured_model_providers(
built_in_model_providers(/*openai_base_url*/ None),
configured_model_providers,
),
merge_configured_model_providers(built_in_model_providers(), configured_model_providers,),
Ok(expected)
);
}
#[test]
fn test_merge_configured_model_providers_applies_amazon_bedrock_aws_override() {
let credential_export = AwsCredentialExportConfig {
command: "aws-vault".to_string(),
args: vec!["export".into(), "codex-bedrock".into()],
timeout_ms: NonZeroU64::new(30_000).expect("timeout should be non-zero"),
};
let auth_refresh = AwsAuthRefreshConfig {
command: "aws".to_string(),
args: vec!["login".into(), "--profile".into(), "codex-bedrock".into()],
timeout_ms: NonZeroU64::new(10_000).expect("timeout should be non-zero"),
};
let configured_model_providers = std::collections::HashMap::from([(
AMAZON_BEDROCK_PROVIDER_ID.to_string(),
ModelProviderInfo {
aws: Some(ModelProviderAwsAuthInfo {
profile: None,
region: Some("us-west-2".to_string()),
credential_export: Some(credential_export.clone()),
auth_refresh: Some(auth_refresh.clone()),
}),
..ModelProviderInfo::default()
},
)]);
let mut expected = built_in_model_providers(/*openai_base_url*/ None);
expected
.get_mut(AMAZON_BEDROCK_PROVIDER_ID)
.expect("Amazon Bedrock provider should be built in")
.aws = Some(ModelProviderAwsAuthInfo {
profile: None,
region: Some("us-west-2".to_string()),
credential_export: Some(credential_export),
auth_refresh: Some(auth_refresh),
});
assert_eq!(
merge_configured_model_providers(
built_in_model_providers(/*openai_base_url*/ None),
configured_model_providers,
),
Ok(expected)
);
}
#[test]
fn test_merge_configured_model_providers_applies_runtime_overrides_independently() {
let runtime_aws = ModelProviderAwsAuthInfo {
profile: Some("runtime-profile".to_string()),
region: Some("eu-west-1".to_string()),
credential_export: None,
auth_refresh: None,
};
let configured_model_providers = std::collections::HashMap::from([(
AMAZON_BEDROCK_RUNTIME_PROVIDER_ID.to_string(),
ModelProviderInfo {
base_url: Some("https://runtime.example.com/openai/v1".to_string()),
aws: Some(runtime_aws.clone()),
..ModelProviderInfo::default()
},
)]);
let mut expected = built_in_model_providers(/*openai_base_url*/ None);
let expected_runtime = expected
.get_mut(AMAZON_BEDROCK_RUNTIME_PROVIDER_ID)
.expect("Amazon Bedrock Runtime provider should be built in");
expected_runtime.base_url = Some("https://runtime.example.com/openai/v1".to_string());
expected_runtime.aws = Some(runtime_aws);
assert_eq!(
merge_configured_model_providers(
built_in_model_providers(/*openai_base_url*/ None),
configured_model_providers,
),
Ok(expected)
);
}
#[test]
fn test_merge_configured_model_providers_applies_amazon_bedrock_transport_overrides() {
let auth = provider_auth_for_test();
let configured_model_providers = std::collections::HashMap::from([(
AMAZON_BEDROCK_PROVIDER_ID.to_string(),
ModelProviderInfo {
base_url: Some("https://proxy.example.com/v1".to_string()),
auth: Some(auth.clone()),
aws: Some(ModelProviderAwsAuthInfo {
profile: Some("codex-bedrock".to_string()),
region: Some("us-west-2".to_string()),
credential_export: None,
auth_refresh: None,
}),
http_headers: Some(maplit::hashmap! {
"x-example-header".to_string() => "value".into(),
}),
..ModelProviderInfo::default()
},
)]);
let mut expected = built_in_model_providers(/*openai_base_url*/ None);
let expected_provider = expected
.get_mut(AMAZON_BEDROCK_PROVIDER_ID)
.expect("Amazon Bedrock provider should be built in");
expected_provider.base_url = Some("https://proxy.example.com/v1".to_string());
expected_provider.auth = Some(auth);
expected_provider.aws = Some(ModelProviderAwsAuthInfo {
profile: Some("codex-bedrock".to_string()),
region: Some("us-west-2".to_string()),
credential_export: None,
auth_refresh: None,
});
expected_provider
.http_headers
.get_or_insert_default()
.insert("x-example-header".to_string(), "value".into());
assert_eq!(
merge_configured_model_providers(
built_in_model_providers(/*openai_base_url*/ None),
configured_model_providers,
),
Ok(expected)
);
}
#[test]
fn test_merge_configured_model_providers_applies_gcp_transport_overrides() {
let auth = provider_auth_for_test();
let credential_file = std::env::current_dir().unwrap().join("adc.json");
let configured_model_providers = std::collections::HashMap::from([(
GCP_PROVIDER_ID.to_string(),
ModelProviderInfo {
base_url: Some("https://vertex.example.com/v1".to_string()),
project_id: Some("configured-project".to_string()),
location: Some("us-east4".to_string()),
auth: Some(auth.clone()),
credential_file: Some(credential_file.clone()),
http_headers: Some(maplit::hashmap! {
"x-example-header".to_string() => "value".into(),
}),
..ModelProviderInfo::default()
},
)]);
let mut expected = built_in_model_providers(/*openai_base_url*/ None);
let provider = expected
.get_mut(GCP_PROVIDER_ID)
.expect("GCP provider should be built in");
provider.base_url = Some("https://vertex.example.com/v1".to_string());
provider.project_id = Some("configured-project".to_string());
provider.location = Some("us-east4".to_string());
provider.auth = Some(auth);
provider.credential_file = Some(credential_file);
provider.http_headers = Some(maplit::hashmap! {
"x-example-header".to_string() => "value".into(),
});
assert_eq!(
merge_configured_model_providers(
built_in_model_providers(/*openai_base_url*/ None),
configured_model_providers,
),
Ok(expected)
);
}
#[test]
fn test_merge_configured_model_providers_applies_gcp_endpoint_override() {
let configured_model_providers = std::collections::HashMap::from([(
GCP_PROVIDER_ID.to_string(),
ModelProviderInfo {
base_url: Some("https://vertex.example.com/v1".to_string()),
..ModelProviderInfo::default()
},
)]);
let mut expected = built_in_model_providers(/*openai_base_url*/ None);
expected
.get_mut(GCP_PROVIDER_ID)
.expect("GCP provider should be built in")
.base_url = Some("https://vertex.example.com/v1".to_string());
assert_eq!(
merge_configured_model_providers(
built_in_model_providers(/*openai_base_url*/ None),
configured_model_providers,
),
Ok(expected)
);
}
#[test]
fn test_merge_configured_gcp_rejects_relative_credential_file() {
for credential_file in ["", "adc.json", "../adc.json"] {
let provider = ModelProviderInfo {
credential_file: Some(credential_file.into()),
..ModelProviderInfo::create_gcp_provider()
};
assert_eq!(
provider.validate(),
Err("provider credential_file must be an absolute path".to_string()),
);
let overrides = HashMap::from([(
GCP_PROVIDER_ID.to_string(),
ModelProviderInfo {
credential_file: Some(credential_file.into()),
..Default::default()
},
)]);
assert_eq!(
merge_configured_model_providers(
built_in_model_providers(/*openai_base_url*/ None),
overrides,
),
Err(
"model_providers.gcp provider credential_file must be an absolute path".to_string()
),
);
}
}
#[test]
fn test_merge_configured_model_providers_rejects_amazon_bedrock_non_default_fields() {
let configured_model_providers = std::collections::HashMap::from([(
AMAZON_BEDROCK_PROVIDER_ID.to_string(),
ModelProviderInfo {
name: "Custom Bedrock".to_string(),
aws: Some(ModelProviderAwsAuthInfo {
profile: Some("codex-bedrock".to_string()),
region: None,
credential_export: None,
auth_refresh: None,
}),
..ModelProviderInfo::default()
},
)]);
assert_eq!(
merge_configured_model_providers(
built_in_model_providers(/*openai_base_url*/ None),
configured_model_providers,
),
Err(
"model_providers.amazon-bedrock only supports changing `base_url`, `auth`, `http_headers`, `aws.profile`, `aws.region`, `aws.credential_export`, and `aws.auth_refresh`; other non-default provider fields are not supported"
.to_string()
)
);
}
#[test]
fn test_merge_configured_model_providers_allows_amazon_bedrock_default_fields() {
let configured_model_providers = std::collections::HashMap::from([(
AMAZON_BEDROCK_PROVIDER_ID.to_string(),
ModelProviderInfo {
aws: Some(ModelProviderAwsAuthInfo {
profile: None,
region: None,
credential_export: None,
auth_refresh: None,
}),
wire_api: WireApi::Responses,
..ModelProviderInfo::default()
},
)]);
assert_eq!(
merge_configured_model_providers(
built_in_model_providers(/*openai_base_url*/ None),
configured_model_providers,
),
Ok(built_in_model_providers(/*openai_base_url*/ None))
);
}
#[test]
fn test_validate_provider_aws_rejects_conflicting_auth() {
let provider = ModelProviderInfo {
aws: Some(ModelProviderAwsAuthInfo {
profile: None,
region: None,
credential_export: None,
auth_refresh: None,
}),
env_key: Some("AWS_BEARER_TOKEN_BEDROCK".to_string()),
supports_websockets: false,
..ModelProviderInfo::create_openai_provider(/*base_url*/ None)
};
assert_eq!(
provider.validate(),
Err("provider aws cannot be combined with env_key, requires_openai_auth".to_string())
);
}
#[test]
fn test_validate_provider_aws_rejects_websockets() {
let provider = ModelProviderInfo {
aws: Some(ModelProviderAwsAuthInfo {
profile: None,
region: None,
credential_export: None,
auth_refresh: None,
}),
requires_openai_auth: false,
supports_websockets: true,
..ModelProviderInfo::create_openai_provider(/*base_url*/ None)
};
assert_eq!(
provider.validate(),
Err("provider aws cannot be combined with supports_websockets".to_string())
);
}
#[test]
fn test_validate_provider_aws_auth_refresh_command() {
for (command, expected) in [
(
" ",
Err("provider aws.auth_refresh.command must not be empty".to_string()),
),
(
"other-command",
Err("provider aws.auth_refresh.command must be `aws`".to_string()),
),
("aws", Ok(())),
] {
let provider =
ModelProviderInfo::create_amazon_bedrock_provider(Some(ModelProviderAwsAuthInfo {
profile: None,
region: None,
credential_export: None,
auth_refresh: Some(AwsAuthRefreshConfig {
command: command.to_string(),
args: Vec::new(),
timeout_ms: NonZeroU64::new(300_000).expect("timeout should be non-zero"),
}),
}));
assert_eq!(provider.validate(), expected);
}
}
#[test]
fn test_validate_provider_aws_credential_export_command() {
let absolute_command = std::env::current_exe()
.expect("current executable should have a path")
.to_string_lossy()
.into_owned();
for (command, expected) in [
(
String::new(),
Err("provider aws.credential_export.command must not be empty".to_string()),
),
(
" ".to_string(),
Err("provider aws.credential_export.command must not be empty".to_string()),
),
("aws-vault".to_string(), Ok(())),
(absolute_command, Ok(())),
(
"./scripts/export-credentials".to_string(),
Err(
"provider aws.credential_export.command must be an absolute path or a bare executable name"
.to_string(),
),
),
(
"scripts/export-credentials".to_string(),
Err(
"provider aws.credential_export.command must be an absolute path or a bare executable name"
.to_string(),
),
),
(
"scripts/.".to_string(),
Err(
"provider aws.credential_export.command must be an absolute path or a bare executable name"
.to_string(),
),
),
] {
let mut provider =
ModelProviderInfo::create_amazon_bedrock_provider(Some(ModelProviderAwsAuthInfo {
profile: None,
region: Some("us-west-2".to_string()),
credential_export: Some(AwsCredentialExportConfig {
command,
args: vec!["--secret-argument".into()],
timeout_ms: NonZeroU64::new(30_000).expect("timeout should be non-zero"),
}),
auth_refresh: Some(AwsAuthRefreshConfig {
command: "aws".to_string(),
args: Vec::new(),
timeout_ms: NonZeroU64::new(300_000).expect("timeout should be non-zero"),
}),
}));
assert_eq!(provider.validate(), expected);
if expected.is_ok() {
provider.aws.as_mut().expect("AWS config").profile = Some("codex-bedrock".to_string());
assert_eq!(
provider.validate(),
Err("provider aws.credential_export cannot be combined with aws.profile".to_string()),
);
}
let export = provider
.aws
.as_ref()
.and_then(|aws| aws.credential_export.as_ref())
.expect("credential export should be configured");
assert!(!format!("{export:?}").contains("--secret-argument"));
}
}
#[test]
fn test_deserialize_provider_auth_config_allows_zero_refresh_interval() {
let base_dir = tempdir().unwrap();
@@ -933,93 +323,6 @@ model_catalog_url = "https://gateway.example/codex/catalog?token=catalog-secret"
);
}
#[test]
fn builtin_openai_catalog_override_preserves_inference_and_identity() {
for inference_url in [None, Some("https://us.api.openai.com/v1")] {
// A catalog override on the built-in provider is rejected; see the tests below.
for catalog_url in [None::<&str>] {
let configured: ModelProviderInfo = toml::from_str(&format!(
"name = \"Ignored name\"\nbase_url = \"https://ignored.example/v1\"\nrequires_openai_auth = false\n{}",
catalog_url.map(|url| format!("model_catalog_url = {url:?}")).unwrap_or_default()
)).unwrap();
let builtins = built_in_model_providers(inference_url.map(str::to_owned));
let mut expected = builtins.clone();
expected.get_mut("openai").unwrap().model_catalog_url = catalog_url.map(Into::into);
assert_eq!(
merge_configured_model_providers(
builtins,
HashMap::from([("openai".to_string(), configured)]),
)
.unwrap(),
expected,
);
}
}
}
#[test]
fn builtin_openai_catalog_rejects_untrusted_destinations() {
for url in [
"http://chatgpt.com/backend-api/codex/models",
"https://chatgpt.com.evil.example/models",
"https://evilchatgpt.com/models",
"https://api.openai.com/v1/models",
"https://example.com/models?secret=do-not-log",
"https://user:secret@chatgpt.com/models",
"/models",
"not a URL",
] {
let provider = ModelProviderInfo {
model_catalog_url: Some(url.into()),
..Default::default()
};
assert_eq!(
merge_configured_model_providers(
built_in_model_providers(/*openai_base_url*/ None),
HashMap::from([("openai".to_string(), provider.clone())]),
)
.unwrap_err(),
"model_providers.openai.model_catalog_url is not supported. If you need a model catalog, configure a custom model_provider",
);
let mut expected = built_in_model_providers(/*openai_base_url*/ None);
expected.insert("custom".into(), provider.clone());
assert_eq!(
merge_configured_model_providers(
built_in_model_providers(/*openai_base_url*/ None),
HashMap::from([("custom".into(), provider)]),
)
.unwrap(),
expected,
);
}
}
#[test]
fn builtin_openai_catalog_rejects_chatgpt_hosts() {
// aKode never fetches the built-in provider's catalog from ChatGPT.
for host in [
"chatgpt.com",
"gov.chatgpt.com",
"chat.openai.com",
"chatgpt-staging.com",
"api.chatgpt-staging.com",
"CHATGPT.COM",
] {
let provider = ModelProviderInfo {
model_catalog_url: Some(format!("https://{host}/backend-api/codex/models").into()),
..Default::default()
};
assert_eq!(
merge_configured_model_providers(
built_in_model_providers(/*openai_base_url*/ None),
HashMap::from([("openai".into(), provider)]),
)
.unwrap_err(),
"model_providers.openai.model_catalog_url is not supported. If you need a model catalog, configure a custom model_provider",
);
}
}
#[test]
fn legacy_cyber_access_programs_capability_is_accepted_and_ignored() {
for configured in [None, Some(false), Some(true)] {
@@ -1035,3 +338,135 @@ fn legacy_cyber_access_programs_capability_is_accepted_and_ignored() {
assert_eq!(round_trip, provider);
}
}
#[test]
fn built_in_providers_are_only_local_servers() {
let providers = built_in_model_providers();
let mut ids = providers.keys().cloned().collect::<Vec<_>>();
ids.sort();
assert_eq!(ids, vec!["lmstudio".to_string(), "ollama".to_string()]);
for (id, provider) in providers {
let base_url = provider
.base_url
.expect("built-in providers have a base_url");
assert!(
base_url.starts_with("http://localhost:")
|| std::env::var("CODEX_OSS_BASE_URL").is_ok(),
"{id}: {base_url}"
);
assert!(!provider.requires_openai_auth, "{id}");
}
}
#[test]
fn no_provider_targets_openai_without_explicit_configuration() {
// There is no built-in OpenAI provider: `openai` is an ordinary custom id, and an
// unconfigured provider has no endpoint at all instead of falling back to OpenAI.
let providers =
merge_configured_model_providers(built_in_model_providers(), HashMap::new()).unwrap();
assert!(!providers.contains_key("openai"));
for provider in providers.values() {
let base_url = provider.base_url.as_deref().unwrap_or_default();
assert!(!base_url.contains("openai.com"), "{base_url}");
assert!(!base_url.contains("chatgpt.com"), "{base_url}");
}
let unconfigured = ModelProviderInfo::unconfigured();
assert!(unconfigured.is_unconfigured());
let error = unconfigured.to_api_provider().unwrap_err().to_string();
assert!(error.contains("No model provider is configured"), "{error}");
assert!(!error.contains("api.openai.com"), "{error}");
}
#[test]
fn configured_provider_learns_keyring_account_and_default_name() {
let configured: ModelProviderInfo = toml::from_str(
r#"
base_url = "http://192.0.2.10:8080/v1"
api_key = "keyring"
"#,
)
.unwrap();
assert_eq!(configured.api_key, Some(ProviderApiKeySource::Keyring));
let providers = merge_configured_model_providers(
built_in_model_providers(),
HashMap::from([("imeai".to_string(), configured)]),
)
.unwrap();
let provider = &providers["imeai"];
assert_eq!(provider.name, "imeai");
assert_eq!(
provider.keyring_account.as_deref(),
Some("model-provider:imeai")
);
// The runtime-only keyring account is never serialized.
assert!(
!toml::to_string(provider)
.unwrap()
.contains("model-provider:")
);
}
#[test]
fn literal_api_key_is_rejected_without_echoing_it() {
// The TOML parser quotes the offending source line in its own errors; the
// deserializer message itself must never repeat the value.
let error = toml::from_str::<ModelProviderInfo>(
r#"
base_url = "http://192.0.2.10:8080/v1"
api_key = "sk-literal-secret-do-not-log"
"#,
)
.unwrap_err();
assert!(error.message().contains("must be \"keyring\""), "{error}");
assert!(
!error.message().contains("sk-literal-secret-do-not-log"),
"{error}"
);
let error = ProviderApiKeySource::deserialize(serde::de::value::StrDeserializer::<
serde::de::value::Error,
>::new("sk-literal-secret-do-not-log"))
.unwrap_err()
.to_string();
assert!(!error.contains("sk-literal-secret-do-not-log"), "{error}");
}
#[test]
fn keyring_api_key_conflicts_with_other_credential_sources() {
for extra in [
"env_key = \"KEY\"",
"experimental_bearer_token = \"token\"",
"requires_openai_auth = true",
] {
let provider: ModelProviderInfo = toml::from_str(&format!(
"base_url = \"http://192.0.2.10/v1\"\napi_key = \"keyring\"\n{extra}\n"
))
.unwrap();
let error = provider.validate().unwrap_err();
assert!(error.contains("api_key cannot be combined"), "{error}");
}
}
#[test]
fn use_stored_api_key_is_an_alias_for_requires_openai_auth() {
let provider: ModelProviderInfo =
toml::from_str("base_url = \"http://192.0.2.10/v1\"\nuse_stored_api_key = true\n").unwrap();
assert!(provider.requires_openai_auth);
let legacy: ModelProviderInfo =
toml::from_str("base_url = \"http://192.0.2.10/v1\"\nrequires_openai_auth = true\n")
.unwrap();
assert_eq!(provider, legacy);
}
#[test]
fn merge_system_messages_defaults_on() {
let provider: ModelProviderInfo =
toml::from_str("base_url = \"http://192.0.2.10/v1\"").unwrap();
assert!(provider.merge_system_messages());
let disabled: ModelProviderInfo =
toml::from_str("base_url = \"http://192.0.2.10/v1\"\nmerge_system_messages = false")
.unwrap();
assert!(!disabled.merge_system_messages());
for provider in built_in_model_providers().values() {
assert!(provider.merge_system_messages());
}
}