Pannello endpoint /endpoint e primo avvio guidato (ripristino da 0.9.2, senza provider predefiniti)

Riportato dalla 0.9.2 solo cio' che serve alla configurazione dei provider:
- /endpoint nella TUI: elenco provider, aggiunta/modifica/rimozione, scelta del
  modello da /v1/models, impostazioni per modello (contesto, temperatura, top_p,
  max output, ragionamento, nome mostrato), nomi abbreviati dei modelli.
- primo avvio guidato quando non c'e' alcun provider: endpoint, chiave, dove
  salvarla (portachiavi o file protetto), elenco modelli dal server, prova della
  connessione, salvataggio in config.toml.
- chiavi per provider nel portachiavi (`api_key = "keyring"`,
  `akode login --provider <id> --with-api-key`, `akode logout --provider <id>`).

Nessun URL, modello o provider predefinito nel codice; nessun provider cloud tra
le scelte (solo endpoint personalizzato e i provider locali Ollama/LM Studio
gia' presenti in upstream). Lasciati fuori: passo tema e passo ricerca web
(SearXNG) del primo avvio, barra di stato, unione messaggi di sistema, header @@,
modello ausiliario, tool function di apply_patch.

Test: test CLI debug_models riportato al comportamento upstream (catalogo
incluso); snapshot doctor aggiornati al nome e alla versione aKode.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-17 17:41:20 +01:00
parent 565079cb94
commit 2c78ef50e1
106 changed files with 7068 additions and 84 deletions

View File

@@ -15,6 +15,7 @@ workspace = true
[dependencies]
akode-client = { workspace = true }
akode-http-client = { workspace = true }
akode-keyring-store = { workspace = true }
akode-protocol = { workspace = true }
akode-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 }
akode-utils-absolute-path = { workspace = true }
maplit = { workspace = true }
pretty_assertions = { workspace = true }

View File

@@ -195,6 +195,7 @@ impl GatewayOAuthConfig {
}
let gateway_header = if self.delivery().is_authorization_bearer() {
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). `akode-login` installs a store that follows
//! `provider_api_key_store = "auto" | "keyring" | "file"` and can fall back to a private
//! file in AKODE_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 akode_keyring_store::DefaultKeyringStore;
use akode_keyring_store::KeyringStore;
use akode_protocol::error::CodexErr;
use akode_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 akode_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

@@ -21,6 +21,8 @@ use http::header::HeaderValue;
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Serialize;
use akode_protocol::openai_models::ReasoningEffort;
use std::collections::BTreeMap;
use std::collections::HashMap;
use std::fmt;
use std::num::NonZeroU64;
@@ -32,12 +34,22 @@ 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;
@@ -80,6 +92,8 @@ const MAX_STREAM_MAX_RETRIES: u64 = 100;
/// Hard cap for user-configured `request_max_retries`.
const MAX_REQUEST_MAX_RETRIES: u64 = 100;
/// 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",
@@ -92,7 +106,8 @@ pub const NO_MODEL_PROVIDER_CONFIGURED_ERROR: &str = concat!(
" [model_providers.local]\n",
" name = \"My server\"\n",
" base_url = \"http://127.0.0.1:8080/v1\" # must implement POST {base_url}/responses\n",
" env_key = \"MY_SERVER_API_KEY\" # environment variable that holds the API key\n",
" api_key = \"keyring\" # store it with: akode 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).",
@@ -162,6 +177,10 @@ pub struct ModelProviderInfo {
pub auth: Option<ModelProviderAuthInfo>,
/// Gateway access token from OAuth or a credential export command.
pub gateway_oauth: Option<GatewayOAuthConfig>,
/// Where to read this provider's API key from. `"keyring"` reads the key stored with
/// `akode login --provider <id> --with-api-key`: in the system keyring, or in a private
/// file in AKODE_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,
@@ -192,8 +211,9 @@ pub struct ModelProviderInfo {
pub websocket_connect_timeout_ms: Option<u64>,
/// Use the API key stored with `akode login --with-api-key` (in `auth.json` or the
/// credentials store selected by `cli_auth_credentials_store`) for this provider.
/// When false (the default), the key comes from `env_key` or `auth`, if any.
#[serde(default)]
/// `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,
/// Whether this provider supports the Responses API WebSocket transport.
#[serde(default)]
@@ -201,11 +221,45 @@ pub struct ModelProviderInfo {
/// Whether this provider supports the standalone web-search endpoint.
#[serde(default)]
pub supports_standalone_web_search: bool,
/// Per-model settings keyed by model id (`[model_providers.<id>.models."<model id>"]`).
/// A value set here wins over the matching global setting (e.g. `model_context_window`).
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub models: BTreeMap<String, ProviderModelSettings>,
/// Runtime-only opt-in for internal metadata, independent of the destination check.
/// This cannot be loaded from or written to serialized provider configuration.
#[serde(skip)]
#[schemars(skip)]
pub include_internal_metadata: bool,
/// 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>,
}
/// Settings for one model of a provider. Every value is optional; unset values fall back to
/// the global settings, then to what the server reports, then to the defaults.
#[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct ProviderModelSettings {
/// Context window in tokens (wins over `model_context_window`).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub context_window: Option<i64>,
/// Sampling temperature sent with each request.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub temperature: Option<f64>,
/// Nucleus sampling (`top_p`) sent with each request.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub top_p: Option<f64>,
/// Maximum output tokens per response (`max_output_tokens`).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max_output_tokens: Option<u64>,
/// Reasoning effort (wins over `model_reasoning_effort`).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reasoning_effort: Option<ReasoningEffort>,
/// Name shown in the interface instead of the model id (the API always gets the id).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub display_name: Option<String>,
}
/// Command used to export credentials for a model provider.
@@ -251,11 +305,67 @@ fn default_credential_export_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<'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 `akode login --provider <id> --with-api-key`, or use env_key",
)),
}
}
}
/// 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 {
/// Settings configured for `model`, if any.
pub fn model_settings(&self, model: &str) -> Option<&ProviderModelSettings> {
self.models.get(model)
}
pub fn validate(&self) -> std::result::Result<(), String> {
if let Some(gateway) = &self.gateway_oauth {
gateway.validate(self)?;
}
if self.api_key.is_some() {
let mut conflicts = Vec::new();
if self.env_key.is_some() {
conflicts.push("env_key");
}
if self.experimental_bearer_token.is_some() {
conflicts.push("experimental_bearer_token");
}
if self.auth.is_some() {
conflicts.push("auth");
}
if self.requires_openai_auth {
conflicts.push("requires_openai_auth");
}
if !conflicts.is_empty() {
return Err(format!(
"provider api_key cannot be combined with {}",
conflicts.join(", ")
));
}
}
let Some(auth) = self.auth.as_ref() else {
return Ok(());
@@ -361,10 +471,21 @@ impl ModelProviderInfo {
})
}
/// 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)
@@ -475,11 +596,13 @@ pub fn built_in_model_providers() -> HashMap<String, ModelProviderInfo> {
/// Merge configured providers into the built-in provider catalog.
///
/// 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 {
provider.keyring_account = Some(provider_api_key_keyring_account(&key));
if provider.name.trim().is_empty() {
provider.name = key.clone();
}
@@ -518,6 +641,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,
api_key: None,
wire_api,
query_params: None,
http_headers: None,
@@ -531,6 +655,8 @@ pub fn create_oss_provider_with_base_url(base_url: &str, wire_api: WireApi) -> M
supports_standalone_web_search: false,
capabilities: None,
include_internal_metadata: false,
keyring_account: None,
models: Default::default(),
}
}

View File

@@ -87,6 +87,7 @@ base_url = "http://localhost:11434/v1"
experimental_bearer_token: None,
auth: None,
gateway_oauth: None,
api_key: None,
wire_api: WireApi::Responses,
query_params: None,
http_headers: None,
@@ -99,7 +100,9 @@ base_url = "http://localhost:11434/v1"
supports_websockets: false,
supports_standalone_web_search: false,
capabilities: None,
keyring_account: None,
include_internal_metadata: false,
models: Default::default(),
};
let provider: ModelProviderInfo = toml::from_str(azure_provider_toml).unwrap();
@@ -123,6 +126,7 @@ query_params = { api-version = "2025-04-01-preview" }
experimental_bearer_token: None,
auth: None,
gateway_oauth: None,
api_key: None,
wire_api: WireApi::Responses,
query_params: Some(maplit::hashmap! {
"api-version".to_string() => "2025-04-01-preview".into(),
@@ -137,7 +141,9 @@ query_params = { api-version = "2025-04-01-preview" }
supports_websockets: false,
supports_standalone_web_search: false,
capabilities: None,
keyring_account: None,
include_internal_metadata: false,
models: Default::default(),
};
let provider: ModelProviderInfo = toml::from_str(azure_provider_toml).unwrap();
@@ -163,6 +169,7 @@ supports_standalone_web_search = true
experimental_bearer_token: None,
auth: None,
gateway_oauth: None,
api_key: None,
wire_api: WireApi::Responses,
query_params: None,
http_headers: Some(maplit::hashmap! {
@@ -179,7 +186,9 @@ supports_standalone_web_search = true
supports_websockets: false,
supports_standalone_web_search: true,
capabilities: None,
keyring_account: None,
include_internal_metadata: false,
models: Default::default(),
};
let provider: ModelProviderInfo = toml::from_str(azure_provider_toml).unwrap();
@@ -254,6 +263,7 @@ fn test_merge_configured_model_providers_adds_custom_provider() {
expected.insert(
"custom".to_string(),
ModelProviderInfo {
keyring_account: Some("model-provider:custom".to_string()),
..custom_provider
},
);
@@ -367,6 +377,118 @@ fn no_provider_targets_openai_without_explicit_configuration() {
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 deserializes_per_model_settings() {
let provider: ModelProviderInfo = toml::from_str(
r#"
name = "MACOS"
base_url = "http://127.0.0.1:8080/v1"
[models."/models/Flint.gguf"]
context_window = 65536
temperature = 0.7
top_p = 0.95
max_output_tokens = 8192
reasoning_effort = "medium"
display_name = "Flint"
"#,
)
.expect("provider");
let settings = provider
.model_settings("/models/Flint.gguf")
.expect("settings");
assert_eq!(settings.context_window, Some(65536));
assert_eq!(settings.temperature, Some(0.7));
assert_eq!(settings.top_p, Some(0.95));
assert_eq!(settings.max_output_tokens, Some(8192));
assert_eq!(
settings.reasoning_effort,
Some(akode_protocol::openai_models::ReasoningEffort::Medium)
);
assert_eq!(settings.display_name.as_deref(), Some("Flint"));
assert!(provider.model_settings("other").is_none());
}
#[test]
fn local_providers_get_a_generous_idle_timeout() {
let provider = |base_url: &str| -> ModelProviderInfo {