Rinomina: crate akode-*, cartelle akode-rs/ e akode-cli/, binario akode, ~/.akode, AKODE_* (A)
Riapplica la fase 5 di aKode (86e7c72e) sulla base ripulita:
- crate codex-* -> akode-*, codex-rs -> akode-rs, codex-cli -> akode-cli, binario e ausiliari akode;
- ~/.codex -> ~/.akode, CODEX_HOME -> AKODE_HOME, variabili CODEX_* -> AKODE_*, .codex/ -> .akode/ di progetto;
nessun fallback a ~/.codex o a CODEX_*;
- testi per l'utente "Codex" -> "aKode"; testi verso il modello e istruzioni di sistema invariati;
- snapshot insta rinominati (non ancora rigenerati).
I conflitti con la base ripulita sono stati risolti riapplicando la rinomina ai file senza le
funzioni di imeAI (script di mappa dei token per file).
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
6
akode-rs/model-provider-info/BUILD.bazel
Normal file
6
akode-rs/model-provider-info/BUILD.bazel
Normal file
@@ -0,0 +1,6 @@
|
||||
load("//:defs.bzl", "codex_rust_crate")
|
||||
|
||||
codex_rust_crate(
|
||||
name = "model-provider-info",
|
||||
crate_name = "akode_model_provider_info",
|
||||
)
|
||||
29
akode-rs/model-provider-info/Cargo.toml
Normal file
29
akode-rs/model-provider-info/Cargo.toml
Normal file
@@ -0,0 +1,29 @@
|
||||
[package]
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
name = "akode-model-provider-info"
|
||||
version.workspace = true
|
||||
|
||||
[lib]
|
||||
doctest = false
|
||||
name = "akode_model_provider_info"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
akode-client = { workspace = true }
|
||||
akode-http-client = { workspace = true }
|
||||
akode-protocol = { workspace = true }
|
||||
akode-utils-redacted-string = { workspace = true }
|
||||
http = { workspace = true }
|
||||
schemars = { workspace = true }
|
||||
serde = { workspace = true, features = ["derive"] }
|
||||
|
||||
[dev-dependencies]
|
||||
akode-utils-absolute-path = { workspace = true }
|
||||
maplit = { workspace = true }
|
||||
pretty_assertions = { workspace = true }
|
||||
tempfile = { workspace = true }
|
||||
toml = { workspace = true }
|
||||
31
akode-rs/model-provider-info/src/capabilities.rs
Normal file
31
akode-rs/model-provider-info/src/capabilities.rs
Normal file
@@ -0,0 +1,31 @@
|
||||
//! Serializable capability overrides for custom Responses-compatible providers.
|
||||
//!
|
||||
//! Unspecified capabilities inherit the provider's existing defaults. Model and
|
||||
//! turn settings may further restrict the capabilities declared here.
|
||||
|
||||
use schemars::JsonSchema;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
|
||||
/// Overrides for the optional API features supported by a custom provider.
|
||||
#[derive(Debug, Clone, Copy, Default, Deserialize, Serialize, PartialEq, Eq, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct ModelProviderCapabilities {
|
||||
/// Removed: explicit access-program selection was deleted. Accepted and ignored
|
||||
/// so existing provider configs keep loading.
|
||||
pub cyber_access_programs: Option<bool>,
|
||||
/// Whether hosted web search may access the live web.
|
||||
pub external_web_access: Option<bool>,
|
||||
/// Remote context-compaction protocol; omission preserves provider defaults.
|
||||
pub remote_compaction: Option<RemoteCompactionSupport>,
|
||||
}
|
||||
|
||||
/// Remote context-compaction protocols supported by a model provider.
|
||||
#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq, JsonSchema)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum RemoteCompactionSupport {
|
||||
/// Use local compaction instead of a provider compaction protocol.
|
||||
Unsupported,
|
||||
/// Send `compaction_trigger` items over the Responses endpoint.
|
||||
V2,
|
||||
}
|
||||
244
akode-rs/model-provider-info/src/gateway_oauth.rs
Normal file
244
akode-rs/model-provider-info/src/gateway_oauth.rs
Normal file
@@ -0,0 +1,244 @@
|
||||
//! Gateway credentials and their delivery alongside the provider's primary authentication.
|
||||
|
||||
use akode_client::CHATGPT_ACCOUNT_ID_HEADER;
|
||||
use std::fmt;
|
||||
|
||||
use akode_http_client::validate_endpoint_url;
|
||||
use http::header::HeaderName;
|
||||
use schemars::JsonSchema;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::CredentialExportConfig;
|
||||
use crate::ModelProviderInfo;
|
||||
use crate::OAuthCredentialsStore;
|
||||
|
||||
// Reserve authentication, routing/framing, and internal protocol headers.
|
||||
const RESERVED_GATEWAY_OAUTH_HEADERS: &[&str] = &[
|
||||
"authorization",
|
||||
"proxy-authorization",
|
||||
"cookie",
|
||||
"host",
|
||||
"content-length",
|
||||
"transfer-encoding",
|
||||
"connection",
|
||||
"upgrade",
|
||||
CHATGPT_ACCOUNT_ID_HEADER,
|
||||
];
|
||||
const RESERVED_GATEWAY_OAUTH_HEADER_PREFIXES: &[&str] =
|
||||
&["x-codex-", "x-openai-", "sec-websocket-"];
|
||||
|
||||
#[derive(Clone, Deserialize, Serialize, PartialEq, Eq, JsonSchema)]
|
||||
#[serde(
|
||||
untagged,
|
||||
deny_unknown_fields,
|
||||
expecting = "choose one gateway credential source: credential_export or OAuth settings (authorization_url, token_url, and client_id)"
|
||||
)]
|
||||
pub enum GatewayOAuthConfig {
|
||||
OAuth(GatewayOAuthSettings),
|
||||
Export {
|
||||
/// Command that prints a gateway access token.
|
||||
credential_export: CredentialExportConfig,
|
||||
#[serde(default)]
|
||||
delivery: GatewayOAuthDelivery,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Deserialize, Serialize, PartialEq, Eq, JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct GatewayOAuthSettings {
|
||||
pub authorization_url: String,
|
||||
/// Optional device endpoint used when the terminal cannot open a browser for gateway sign-in.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub device_authorization_url: Option<String>,
|
||||
pub token_url: String,
|
||||
pub client_id: String,
|
||||
pub resource: Option<String>,
|
||||
#[serde(default)]
|
||||
pub scopes: Vec<String>,
|
||||
pub redirect_port: Option<u16>,
|
||||
/// Where Codex stores this gateway's OAuth credentials. Defaults to the keyring-backed store.
|
||||
#[serde(default, skip_serializing_if = "is_keyring")]
|
||||
pub credentials_store: OAuthCredentialsStore,
|
||||
/// Omit to send the gateway token via the Authorization header
|
||||
#[serde(default)]
|
||||
pub delivery: GatewayOAuthDelivery,
|
||||
}
|
||||
|
||||
// Preserve the serialized provider and model cache identity for the default store.
|
||||
#[expect(
|
||||
clippy::trivially_copy_pass_by_ref,
|
||||
reason = "Serde passes a reference to skip_serializing_if predicates"
|
||||
)]
|
||||
fn is_keyring(store: &OAuthCredentialsStore) -> bool {
|
||||
*store == OAuthCredentialsStore::Keyring
|
||||
}
|
||||
|
||||
impl fmt::Debug for GatewayOAuthConfig {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("GatewayOAuthConfig")
|
||||
.field("delivery", self.delivery())
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, JsonSchema)]
|
||||
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
|
||||
pub enum GatewayOAuthDelivery {
|
||||
Header {
|
||||
name: String,
|
||||
#[serde(default = "bearer_scheme")]
|
||||
scheme: String,
|
||||
},
|
||||
Cookie {
|
||||
name: String,
|
||||
},
|
||||
}
|
||||
|
||||
impl Default for GatewayOAuthDelivery {
|
||||
fn default() -> Self {
|
||||
Self::Header {
|
||||
name: "Authorization".into(),
|
||||
scheme: bearer_scheme(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl GatewayOAuthDelivery {
|
||||
fn is_authorization_bearer(&self) -> bool {
|
||||
matches!(self, Self::Header { name, scheme } if name.eq_ignore_ascii_case("authorization") && scheme.eq_ignore_ascii_case("bearer"))
|
||||
}
|
||||
|
||||
fn secondary_header(&self) -> Result<HeaderName, &'static str> {
|
||||
match self {
|
||||
Self::Header { name, scheme } => {
|
||||
let header = HeaderName::from_bytes(name.as_bytes())
|
||||
.map_err(|_| "needs a valid HTTP header name, such as X-Gateway-Auth")?;
|
||||
if RESERVED_GATEWAY_OAUTH_HEADERS.contains(&header.as_str())
|
||||
|| RESERVED_GATEWAY_OAUTH_HEADER_PREFIXES
|
||||
.iter()
|
||||
.any(|prefix| header.as_str().starts_with(prefix))
|
||||
{
|
||||
return Err(
|
||||
"uses a reserved header. Choose a custom header or cookie accepted by your gateway",
|
||||
);
|
||||
}
|
||||
if !is_token(scheme) {
|
||||
return Err("needs an HTTP authentication scheme such as Bearer");
|
||||
}
|
||||
Ok(header)
|
||||
}
|
||||
Self::Cookie { name } if is_token(name) => Ok(http::header::COOKIE),
|
||||
Self::Cookie { .. } => Err("needs a valid cookie name, such as gateway_session"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn bearer_scheme() -> String {
|
||||
"Bearer".to_owned()
|
||||
}
|
||||
|
||||
impl GatewayOAuthConfig {
|
||||
pub fn delivery(&self) -> &GatewayOAuthDelivery {
|
||||
match self {
|
||||
Self::OAuth(settings) => &settings.delivery,
|
||||
Self::Export { delivery, .. } => delivery,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn uses_credential_export(&self) -> bool {
|
||||
matches!(self, Self::Export { .. })
|
||||
}
|
||||
|
||||
/// Send the gateway bearer only to the configured endpoint.
|
||||
pub fn requires_gateway_origin(&self) -> bool {
|
||||
self.delivery().is_authorization_bearer() || self.uses_credential_export()
|
||||
}
|
||||
|
||||
pub(crate) fn validate(&self, provider: &ModelProviderInfo) -> Result<(), String> {
|
||||
let base_url = provider
|
||||
.base_url
|
||||
.as_deref()
|
||||
.ok_or("gateway_oauth requires base_url")?;
|
||||
let gateway = validate_endpoint_url(base_url, "base_url")?;
|
||||
match self {
|
||||
Self::Export {
|
||||
credential_export, ..
|
||||
} => credential_export.validate("gateway_oauth.credential_export")?,
|
||||
Self::OAuth(settings) => {
|
||||
validate_endpoint_url(
|
||||
&settings.authorization_url,
|
||||
"gateway_oauth.authorization_url",
|
||||
)?;
|
||||
if let Some(url) = &settings.device_authorization_url {
|
||||
validate_endpoint_url(url, "gateway_oauth.device_authorization_url")?;
|
||||
}
|
||||
validate_endpoint_url(&settings.token_url, "gateway_oauth.token_url")?;
|
||||
if settings.client_id.trim().is_empty() || settings.redirect_port == Some(0) {
|
||||
return Err(
|
||||
"gateway_oauth requires a nonempty client_id and a nonzero redirect_port"
|
||||
.into(),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
if self.requires_gateway_origin()
|
||||
&& let Some(catalog) = provider.model_catalog_url.as_deref()
|
||||
&& validate_endpoint_url(catalog, "model_catalog_url")?.origin() != gateway.origin()
|
||||
{
|
||||
return Err(
|
||||
"Codex would send gateway credentials to a different model catalog. Set model_catalog_url \
|
||||
to a URL with the same scheme, host, and port as base_url, or remove model_catalog_url \
|
||||
to use the gateway's catalog."
|
||||
.into(),
|
||||
);
|
||||
}
|
||||
let gateway_header = if self.delivery().is_authorization_bearer() {
|
||||
if provider.requires_openai_auth
|
||||
|| provider.env_key.is_some()
|
||||
|| provider.experimental_bearer_token.is_some()
|
||||
|| provider.has_command_auth()
|
||||
{
|
||||
return Err(
|
||||
"Header conflict. Codex is configured to send both the model provider credential \
|
||||
and the gateway token in the Authorization header. Set gateway_oauth.delivery \
|
||||
to a different header or cookie that your gateway accepts for its token."
|
||||
.into(),
|
||||
);
|
||||
}
|
||||
http::header::AUTHORIZATION
|
||||
} else {
|
||||
self.delivery()
|
||||
.secondary_header()
|
||||
.map_err(|reason| format!("gateway_oauth.delivery {reason}"))?
|
||||
};
|
||||
if provider
|
||||
.http_headers
|
||||
.iter()
|
||||
.flat_map(|headers| headers.keys())
|
||||
.chain(
|
||||
provider
|
||||
.env_http_headers
|
||||
.iter()
|
||||
.flat_map(|headers| headers.keys()),
|
||||
)
|
||||
.any(|name| name.eq_ignore_ascii_case(gateway_header.as_str()))
|
||||
{
|
||||
return Err(format!(
|
||||
"The {gateway_header} header is set in both gateway_oauth.delivery and the provider's http_headers or env_http_headers. Remove the duplicate header from the provider or choose a different gateway delivery."
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn is_token(value: &str) -> bool {
|
||||
!value.is_empty()
|
||||
&& value
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&byte))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "gateway_oauth_tests.rs"]
|
||||
mod tests;
|
||||
156
akode-rs/model-provider-info/src/gateway_oauth_tests.rs
Normal file
156
akode-rs/model-provider-info/src/gateway_oauth_tests.rs
Normal file
@@ -0,0 +1,156 @@
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
fn provider(extra: &str) -> ModelProviderInfo {
|
||||
toml::from_str(&format!(
|
||||
r#"
|
||||
base_url = "https://gateway.example.test/v1"
|
||||
[gateway_oauth]
|
||||
authorization_url = "https://login.example.test/authorize"
|
||||
token_url = "https://login.example.test/token"
|
||||
client_id = "codex"
|
||||
{extra}
|
||||
"#
|
||||
))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_header_and_cookie_delivery() {
|
||||
let header = provider("delivery = { kind = 'header', name = 'x-gateway-auth' }");
|
||||
assert_eq!(header.validate(), Ok(()));
|
||||
assert_eq!(
|
||||
header.gateway_oauth.as_ref().unwrap().delivery(),
|
||||
&GatewayOAuthDelivery::Header {
|
||||
name: "x-gateway-auth".into(),
|
||||
scheme: "Bearer".into(),
|
||||
}
|
||||
);
|
||||
let cookie = provider("delivery = { kind = 'cookie', name = 'gateway_session' }");
|
||||
assert_eq!(cookie.validate(), Ok(()));
|
||||
assert_eq!(
|
||||
toml::from_str::<ModelProviderInfo>(&toml::to_string(&cookie).unwrap()).unwrap(),
|
||||
cookie
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_remote_device_authorization_url_requires_https() {
|
||||
for (url, valid) in [
|
||||
("https://login.example.test/devicecode", true),
|
||||
("http://login.example.test/devicecode", false),
|
||||
] {
|
||||
let config = provider(&format!(
|
||||
"device_authorization_url = '{url}'\ndelivery = {{ kind = 'header', name = 'x-gateway-auth' }}"
|
||||
));
|
||||
assert_eq!(config.validate().is_ok(), valid, "{url}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_unsafe_endpoints_and_delivery_collisions() {
|
||||
let valid = provider("delivery = { kind = 'header', name = 'x-gateway-auth' }");
|
||||
for url in [
|
||||
"http://remote.example.test",
|
||||
"https://user:secret@gateway.example.test",
|
||||
"https://gateway.example.test/#secret",
|
||||
"file:///token",
|
||||
] {
|
||||
let mut invalid = valid.clone();
|
||||
invalid.base_url = Some(url.into());
|
||||
assert!(invalid.validate().is_err());
|
||||
invalid = valid.clone();
|
||||
let Some(GatewayOAuthConfig::OAuth(settings)) = &mut invalid.gateway_oauth else {
|
||||
unreachable!()
|
||||
};
|
||||
settings.token_url = url.into();
|
||||
let error = invalid.validate().unwrap_err();
|
||||
assert!(!error.contains(url));
|
||||
}
|
||||
for name in [
|
||||
"HOST",
|
||||
"x-openai-actor-authorization",
|
||||
"content-length",
|
||||
"sec-websocket-key",
|
||||
"bad name",
|
||||
] {
|
||||
let invalid = provider(&format!(
|
||||
"delivery = {{ kind = 'header', name = '{name}' }}"
|
||||
));
|
||||
assert!(invalid.validate().is_err(), "{name}");
|
||||
}
|
||||
let mut collision = valid;
|
||||
collision.http_headers = Some(std::collections::HashMap::from([(
|
||||
"X-Gateway-Auth".into(),
|
||||
"static".into(),
|
||||
)]));
|
||||
assert!(collision.validate().is_err());
|
||||
let mut cookie = provider("delivery = { kind = 'cookie', name = 'gateway' }");
|
||||
cookie.env_http_headers = Some(std::collections::HashMap::from([(
|
||||
"COOKIE".into(),
|
||||
"COOKIE_ENV".into(),
|
||||
)]));
|
||||
assert!(cookie.validate().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn credential_export_rejects_oauth_settings() {
|
||||
for oauth in [
|
||||
"client_id = 'codex'",
|
||||
"scopes = []",
|
||||
"credentials_store = 'keyring'",
|
||||
"authorization_url = 'https://example.test/authorize'\ntoken_url = 'https://example.test/token'\nclient_id = 'codex'",
|
||||
] {
|
||||
let config =
|
||||
format!("[gateway_oauth]\ncredential_export = {{ command = 'export-token' }}\n{oauth}");
|
||||
let error = toml::from_str::<ModelProviderInfo>(&config).unwrap_err();
|
||||
assert!(
|
||||
error
|
||||
.to_string()
|
||||
.contains("choose one gateway credential source"),
|
||||
"{error}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gateway_bearer_requires_the_model_catalog_to_share_its_origin() {
|
||||
let other = "https://gateway.example.test:8443/catalog";
|
||||
let mut info = provider("");
|
||||
info.model_catalog_url = Some(other.into());
|
||||
assert!(
|
||||
info.validate()
|
||||
.unwrap_err()
|
||||
.contains("same scheme, host, and port as base_url")
|
||||
);
|
||||
|
||||
info.model_catalog_url = Some("https://gateway.example.test:443/custom/catalog".into());
|
||||
assert_eq!(info.validate(), Ok(()));
|
||||
|
||||
let mut legacy = provider("delivery = { kind = 'header', name = 'x-gateway-auth' }");
|
||||
legacy.model_catalog_url = Some(other.into());
|
||||
assert_eq!(legacy.validate(), Ok(()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn omitted_delivery_rejects_an_existing_provider_bearer() {
|
||||
let mut info = provider("");
|
||||
assert_eq!(info.validate(), Ok(()));
|
||||
info.requires_openai_auth = true;
|
||||
assert!(
|
||||
info.validate()
|
||||
.unwrap_err()
|
||||
.contains("gateway_oauth.delivery")
|
||||
);
|
||||
info.requires_openai_auth = false;
|
||||
info.env_key = Some("PROVIDER_API_KEY".into());
|
||||
assert!(
|
||||
info.validate()
|
||||
.unwrap_err()
|
||||
.contains("gateway_oauth.delivery")
|
||||
);
|
||||
|
||||
let mut explicit = provider("delivery = { kind = 'header', name = 'x-gateway-auth' }");
|
||||
explicit.env_key = info.env_key;
|
||||
assert_eq!(explicit.validate(), Ok(()));
|
||||
}
|
||||
521
akode-rs/model-provider-info/src/lib.rs
Normal file
521
akode-rs/model-provider-info/src/lib.rs
Normal file
@@ -0,0 +1,521 @@
|
||||
//! Registry of model providers supported by Codex.
|
||||
//!
|
||||
//! Providers can be defined in two places:
|
||||
//! 1. Built-in defaults compiled into the binary so Codex works out-of-the-box.
|
||||
//! 2. User-defined entries inside `~/.akode/config.toml` under the `model_providers`
|
||||
//! key. These override or extend the defaults at runtime.
|
||||
//!
|
||||
//! API provider construction applies the process-wide managed residency policy also
|
||||
//! used by default HTTP headers.
|
||||
|
||||
use akode_client::Provider as ApiProvider;
|
||||
use akode_client::RetryConfig as ApiRetryConfig;
|
||||
use akode_protocol::config_types::ModelProviderAuthInfo;
|
||||
use akode_protocol::error::CodexErr;
|
||||
use akode_protocol::error::EnvVarError;
|
||||
use akode_protocol::error::Result as CodexResult;
|
||||
use akode_utils_redacted_string::RedactedString;
|
||||
use http::HeaderMap;
|
||||
use http::header::HeaderName;
|
||||
use http::header::HeaderValue;
|
||||
use schemars::JsonSchema;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use std::collections::HashMap;
|
||||
use std::fmt;
|
||||
use std::num::NonZeroU64;
|
||||
use std::path::Component;
|
||||
use std::path::Path;
|
||||
use std::sync::PoisonError;
|
||||
use std::sync::RwLock;
|
||||
use std::time::Duration;
|
||||
|
||||
mod capabilities;
|
||||
mod gateway_oauth;
|
||||
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 oauth_session::OAuthCredentialsStore;
|
||||
pub use oauth_session::OAuthSessionConfig;
|
||||
|
||||
pub const RESIDENCY_HEADER_NAME: &str = "x-openai-internal-akode-residency";
|
||||
|
||||
#[derive(Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum ResidencyRequirement {
|
||||
Us,
|
||||
}
|
||||
|
||||
static REQUIREMENTS_RESIDENCY: RwLock<Option<ResidencyRequirement>> = RwLock::new(None);
|
||||
|
||||
/// Sets the process-wide residency requirement loaded from managed configuration.
|
||||
pub fn set_managed_residency_requirement(enforce_residency: Option<ResidencyRequirement>) {
|
||||
// Recover the stored policy if the lock is poisoned rather than silently disabling it.
|
||||
*REQUIREMENTS_RESIDENCY
|
||||
.write()
|
||||
.unwrap_or_else(PoisonError::into_inner) = enforce_residency;
|
||||
}
|
||||
|
||||
/// Returns the current process-wide managed residency requirement.
|
||||
pub fn read_managed_residency_requirement() -> Option<ResidencyRequirement> {
|
||||
*REQUIREMENTS_RESIDENCY
|
||||
.read()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
|
||||
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;
|
||||
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;
|
||||
|
||||
/// 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 ~/.akode), 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",
|
||||
" env_key = \"MY_SERVER_API_KEY\" # environment variable that holds the 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/akode/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/akode/discussions/7782";
|
||||
|
||||
/// Wire protocol that the provider speaks.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, JsonSchema)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum WireApi {
|
||||
/// The Responses API exposed by OpenAI at `/v1/responses`.
|
||||
#[default]
|
||||
Responses,
|
||||
}
|
||||
|
||||
impl fmt::Display for WireApi {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
let value = match self {
|
||||
Self::Responses => "responses",
|
||||
};
|
||||
f.write_str(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for WireApi {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: serde::Deserializer<'de>,
|
||||
{
|
||||
let value = String::deserialize(deserializer)?;
|
||||
match value.as_str() {
|
||||
"responses" => Ok(Self::Responses),
|
||||
"chat" => Err(serde::de::Error::custom(CHAT_WIRE_API_REMOVED_ERROR)),
|
||||
_ => Err(serde::de::Error::unknown_variant(&value, &["responses"])),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Serializable representation of a provider definition.
|
||||
#[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct ModelProviderInfo {
|
||||
/// Friendly display name.
|
||||
#[serde(default)]
|
||||
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 (Codex catalog format, not the
|
||||
/// public `/v1/models` API). When unset, models are listed from `GET {base_url}/models`.
|
||||
///
|
||||
/// 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>,
|
||||
|
||||
/// Optional instructions to help the user get a valid value for the
|
||||
/// variable and set it.
|
||||
pub env_key_instructions: Option<String>,
|
||||
/// Value to use with `Authorization: Bearer <token>` header. Use of this
|
||||
/// config is discouraged in favor of `env_key` for security reasons, but
|
||||
/// this may be necessary when using this programmatically.
|
||||
pub experimental_bearer_token: Option<RedactedString>,
|
||||
/// Command-backed bearer-token configuration for this provider.
|
||||
pub auth: Option<ModelProviderAuthInfo>,
|
||||
/// Gateway access token from OAuth or a credential export command.
|
||||
pub gateway_oauth: Option<GatewayOAuthConfig>,
|
||||
/// Which wire protocol this provider expects.
|
||||
#[serde(default)]
|
||||
pub wire_api: WireApi,
|
||||
/// Optional API capability overrides for a custom Responses-compatible provider.
|
||||
/// Unspecified capabilities retain their existing provider defaults.
|
||||
pub capabilities: Option<ModelProviderCapabilities>,
|
||||
/// Optional query parameters to append to the base URL.
|
||||
pub query_params: Option<HashMap<String, RedactedString>>,
|
||||
/// Additional HTTP headers to include in requests to this provider where
|
||||
/// the (key, value) pairs are the header name and value.
|
||||
pub http_headers: Option<HashMap<String, RedactedString>>,
|
||||
/// Optional HTTP headers to include in requests to this provider where the
|
||||
/// (key, value) pairs are the header name and _environment variable_ whose
|
||||
/// value should be used. If the environment variable is not set, or the
|
||||
/// value is empty, the header will not be included in the request.
|
||||
pub env_http_headers: Option<HashMap<String, String>>,
|
||||
/// Maximum number of times to retry a failed HTTP request to this provider.
|
||||
pub request_max_retries: Option<u64>,
|
||||
/// Number of times to retry reconnecting a dropped streaming response before failing.
|
||||
pub stream_max_retries: Option<u64>,
|
||||
/// Idle timeout (in milliseconds) to wait for activity on a streaming response before treating
|
||||
/// the connection as lost.
|
||||
pub stream_idle_timeout_ms: Option<u64>,
|
||||
/// Maximum time (in milliseconds) to wait for a websocket connection attempt before treating
|
||||
/// it as failed.
|
||||
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)]
|
||||
pub requires_openai_auth: bool,
|
||||
/// Whether this provider supports the Responses API WebSocket transport.
|
||||
#[serde(default)]
|
||||
pub supports_websockets: bool,
|
||||
/// Whether this provider supports the standalone web-search endpoint.
|
||||
#[serde(default)]
|
||||
pub supports_standalone_web_search: bool,
|
||||
/// 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,
|
||||
}
|
||||
|
||||
/// Command used to export credentials for a model provider.
|
||||
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct CredentialExportConfig {
|
||||
/// Executable to invoke directly, without a shell.
|
||||
pub command: String,
|
||||
/// Arguments passed to the credential export command.
|
||||
#[serde(default)]
|
||||
pub args: Vec<RedactedString>,
|
||||
/// Maximum time to wait for the credential export command to complete.
|
||||
#[serde(default = "default_credential_export_timeout_ms")]
|
||||
pub timeout_ms: NonZeroU64,
|
||||
}
|
||||
|
||||
impl CredentialExportConfig {
|
||||
pub fn validate(&self, field: &str) -> Result<(), String> {
|
||||
if self.command.trim().is_empty() {
|
||||
return Err(format!("provider {field}.command must not be empty"));
|
||||
}
|
||||
let path = Path::new(&self.command);
|
||||
let mut components = path.components();
|
||||
let bare = matches!((components.next(), components.next()),
|
||||
(Some(Component::Normal(name)), None) if name == path.as_os_str());
|
||||
if !path.is_absolute() && !bare {
|
||||
return Err(format!(
|
||||
"provider {field}.command must be an absolute path or a bare executable name"
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn timeout(&self) -> Duration {
|
||||
Duration::from_millis(self.timeout_ms.get())
|
||||
}
|
||||
}
|
||||
|
||||
fn default_credential_export_timeout_ms() -> NonZeroU64 {
|
||||
match NonZeroU64::new(DEFAULT_CREDENTIAL_EXPORT_TIMEOUT_MS) {
|
||||
Some(timeout_ms) => timeout_ms,
|
||||
None => panic!("credential export timeout must be non-zero"),
|
||||
}
|
||||
}
|
||||
|
||||
impl ModelProviderInfo {
|
||||
pub fn validate(&self) -> std::result::Result<(), String> {
|
||||
if let Some(gateway) = &self.gateway_oauth {
|
||||
gateway.validate(self)?;
|
||||
}
|
||||
|
||||
let Some(auth) = self.auth.as_ref() else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
if auth.command.trim().is_empty() {
|
||||
return Err("provider auth.command must not be empty".to_string());
|
||||
}
|
||||
|
||||
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.requires_openai_auth {
|
||||
conflicts.push("requires_openai_auth");
|
||||
}
|
||||
|
||||
if conflicts.is_empty() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(format!(
|
||||
"provider auth cannot be combined with {}",
|
||||
conflicts.join(", ")
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve configured request headers before choosing credentials or a runtime.
|
||||
pub fn build_header_map(&self) -> CodexResult<HeaderMap> {
|
||||
let capacity = self.http_headers.as_ref().map_or(0, HashMap::len)
|
||||
+ self.env_http_headers.as_ref().map_or(0, HashMap::len);
|
||||
let mut headers = HeaderMap::with_capacity(capacity);
|
||||
if let Some(extra) = &self.http_headers {
|
||||
for (k, v) in extra {
|
||||
if let (Ok(name), Ok(value)) =
|
||||
(HeaderName::try_from(k), HeaderValue::try_from(v.as_str()))
|
||||
{
|
||||
headers.insert(name, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(env_headers) = &self.env_http_headers {
|
||||
for (header, env_var) in env_headers {
|
||||
if let Ok(val) = std::env::var(env_var)
|
||||
&& !val.trim().is_empty()
|
||||
&& let (Ok(name), Ok(value)) =
|
||||
(HeaderName::try_from(header), HeaderValue::try_from(val))
|
||||
{
|
||||
headers.insert(name, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(headers)
|
||||
}
|
||||
|
||||
/// Builds an API provider with managed residency taking precedence over configured headers.
|
||||
pub fn to_api_provider(&self) -> CodexResult<ApiProvider> {
|
||||
// There is no default endpoint: a provider without base_url is never contacted.
|
||||
let base_url = self
|
||||
.base_url
|
||||
.clone()
|
||||
.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() {
|
||||
let value = match requirement {
|
||||
ResidencyRequirement::Us => HeaderValue::from_static("us"),
|
||||
};
|
||||
headers.insert(RESIDENCY_HEADER_NAME, value);
|
||||
}
|
||||
let retry = ApiRetryConfig {
|
||||
max_attempts: self.request_max_retries(),
|
||||
base_delay: Duration::from_millis(200),
|
||||
retry_429: false,
|
||||
retry_5xx: true,
|
||||
retry_transport: true,
|
||||
};
|
||||
|
||||
Ok(ApiProvider {
|
||||
name: self.name.clone(),
|
||||
base_url,
|
||||
query_params: self.query_params.clone().map(|params| {
|
||||
params
|
||||
.into_iter()
|
||||
.map(|(name, value)| (name, value.into_inner()))
|
||||
.collect()
|
||||
}),
|
||||
headers,
|
||||
retry,
|
||||
stream_idle_timeout: self.stream_idle_timeout(),
|
||||
})
|
||||
}
|
||||
|
||||
/// 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.
|
||||
pub fn api_key(&self) -> CodexResult<Option<String>> {
|
||||
match &self.env_key {
|
||||
Some(env_key) => {
|
||||
let api_key = std::env::var(env_key)
|
||||
.ok()
|
||||
.filter(|v| !v.trim().is_empty())
|
||||
.ok_or_else(|| {
|
||||
CodexErr::EnvVar(EnvVarError {
|
||||
var: env_key.clone(),
|
||||
instructions: self.env_key_instructions.clone(),
|
||||
})
|
||||
})?;
|
||||
Ok(Some(api_key))
|
||||
}
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
/// Effective maximum number of request retries for this provider.
|
||||
pub fn request_max_retries(&self) -> u64 {
|
||||
self.request_max_retries
|
||||
.unwrap_or(DEFAULT_REQUEST_MAX_RETRIES)
|
||||
.min(MAX_REQUEST_MAX_RETRIES)
|
||||
}
|
||||
|
||||
/// Effective maximum number of stream reconnection attempts for this provider.
|
||||
pub fn stream_max_retries(&self) -> u64 {
|
||||
self.stream_max_retries
|
||||
.unwrap_or(DEFAULT_STREAM_MAX_RETRIES)
|
||||
.min(MAX_STREAM_MAX_RETRIES)
|
||||
}
|
||||
|
||||
/// Effective idle timeout for streaming responses.
|
||||
pub fn stream_idle_timeout(&self) -> Duration {
|
||||
self.stream_idle_timeout_ms
|
||||
.map(Duration::from_millis)
|
||||
.unwrap_or(Duration::from_millis(DEFAULT_STREAM_IDLE_TIMEOUT_MS))
|
||||
}
|
||||
|
||||
/// Effective timeout for websocket connect attempts.
|
||||
pub fn websocket_connect_timeout(&self) -> Duration {
|
||||
self.websocket_connect_timeout_ms
|
||||
.map(Duration::from_millis)
|
||||
.unwrap_or(Duration::from_millis(DEFAULT_WEBSOCKET_CONNECT_TIMEOUT_MS))
|
||||
}
|
||||
|
||||
/// 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: name.to_string(),
|
||||
base_url,
|
||||
requires_openai_auth: true,
|
||||
..ModelProviderInfo::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn has_command_auth(&self) -> bool {
|
||||
self.auth.is_some()
|
||||
}
|
||||
}
|
||||
|
||||
pub const DEFAULT_LMSTUDIO_PORT: u16 = 1234;
|
||||
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 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> {
|
||||
[
|
||||
(
|
||||
OLLAMA_OSS_PROVIDER_ID,
|
||||
create_oss_provider(DEFAULT_OLLAMA_PORT, WireApi::Responses),
|
||||
),
|
||||
(
|
||||
LMSTUDIO_OSS_PROVIDER_ID,
|
||||
create_oss_provider(DEFAULT_LMSTUDIO_PORT, WireApi::Responses),
|
||||
),
|
||||
]
|
||||
.into_iter()
|
||||
.map(|(k, v)| (k.to_string(), v))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Merge configured providers into the built-in provider catalog.
|
||||
///
|
||||
/// Configured providers extend the built-in set; built-in providers are not overridable.
|
||||
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 provider.name.trim().is_empty() {
|
||||
provider.name = key.clone();
|
||||
}
|
||||
model_providers.entry(key).or_insert(provider);
|
||||
}
|
||||
|
||||
Ok(model_providers)
|
||||
}
|
||||
|
||||
pub fn create_oss_provider(default_provider_port: u16, wire_api: WireApi) -> ModelProviderInfo {
|
||||
// These AKODE_OSS_ environment variables are experimental: we may
|
||||
// switch to reading values from config.toml instead.
|
||||
let default_codex_oss_base_url = format!(
|
||||
"http://localhost:{codex_oss_port}/v1",
|
||||
codex_oss_port = std::env::var("AKODE_OSS_PORT")
|
||||
.ok()
|
||||
.filter(|value| !value.trim().is_empty())
|
||||
.and_then(|value| value.parse::<u16>().ok())
|
||||
.unwrap_or(default_provider_port)
|
||||
);
|
||||
|
||||
let codex_oss_base_url = std::env::var("AKODE_OSS_BASE_URL")
|
||||
.ok()
|
||||
.filter(|v| !v.trim().is_empty())
|
||||
.unwrap_or(default_codex_oss_base_url);
|
||||
create_oss_provider_with_base_url(&codex_oss_base_url, wire_api)
|
||||
}
|
||||
|
||||
pub fn create_oss_provider_with_base_url(base_url: &str, wire_api: WireApi) -> ModelProviderInfo {
|
||||
ModelProviderInfo {
|
||||
name: "gpt-oss".into(),
|
||||
base_url: Some(base_url.into()),
|
||||
model_catalog_url: None,
|
||||
env_key: None,
|
||||
env_key_instructions: None,
|
||||
experimental_bearer_token: None,
|
||||
auth: None,
|
||||
gateway_oauth: None,
|
||||
wire_api,
|
||||
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,
|
||||
capabilities: None,
|
||||
include_internal_metadata: false,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "model_provider_info_tests.rs"]
|
||||
mod tests;
|
||||
472
akode-rs/model-provider-info/src/model_provider_info_tests.rs
Normal file
472
akode-rs/model-provider-info/src/model_provider_info_tests.rs
Normal file
@@ -0,0 +1,472 @@
|
||||
use super::*;
|
||||
use akode_utils_absolute_path::AbsolutePathBuf;
|
||||
use akode_utils_absolute_path::AbsolutePathBufGuard;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::num::NonZeroU64;
|
||||
use tempfile::tempdir;
|
||||
|
||||
#[test]
|
||||
fn runtime_internal_metadata_opt_in_is_not_serialized_or_configurable() {
|
||||
let trusted = ModelProviderInfo {
|
||||
include_internal_metadata: true,
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(
|
||||
toml::to_string(&trusted).unwrap(),
|
||||
toml::to_string(&ModelProviderInfo::default()).unwrap(),
|
||||
);
|
||||
assert_eq!(
|
||||
toml::from_str::<ModelProviderInfo>("include_internal_metadata = true").unwrap(),
|
||||
ModelProviderInfo::default(),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_api_provider_applies_current_managed_residency() {
|
||||
let info = ModelProviderInfo {
|
||||
http_headers: Some(maplit::hashmap! {
|
||||
"X-OpenAI-Internal-Codex-Residency".to_string() => "eu".into(),
|
||||
"x-provider-header".to_string() => "preserved".into(),
|
||||
}),
|
||||
..ModelProviderInfo::create_responses_provider(
|
||||
"test",
|
||||
Some("https://example.test/v1".to_string()),
|
||||
)
|
||||
};
|
||||
let original_info = info.clone();
|
||||
let previous_requirement = read_managed_residency_requirement();
|
||||
set_managed_residency_requirement(Some(ResidencyRequirement::Us));
|
||||
let managed = info.to_api_provider();
|
||||
set_managed_residency_requirement(/*enforce_residency*/ None);
|
||||
let unmanaged = info.to_api_provider();
|
||||
set_managed_residency_requirement(previous_requirement);
|
||||
|
||||
assert_eq!(
|
||||
managed.expect("managed provider should resolve").headers,
|
||||
HeaderMap::from_iter([
|
||||
(
|
||||
HeaderName::from_static(RESIDENCY_HEADER_NAME),
|
||||
HeaderValue::from_static("us")
|
||||
),
|
||||
(
|
||||
HeaderName::from_static("x-provider-header"),
|
||||
HeaderValue::from_static("preserved")
|
||||
),
|
||||
])
|
||||
);
|
||||
assert_eq!(
|
||||
unmanaged
|
||||
.expect("unmanaged provider should resolve")
|
||||
.headers,
|
||||
HeaderMap::from_iter([
|
||||
(
|
||||
HeaderName::from_static(RESIDENCY_HEADER_NAME),
|
||||
HeaderValue::from_static("eu")
|
||||
),
|
||||
(
|
||||
HeaderName::from_static("x-provider-header"),
|
||||
HeaderValue::from_static("preserved")
|
||||
),
|
||||
])
|
||||
);
|
||||
assert_eq!(info, original_info);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_deserialize_ollama_model_provider_toml() {
|
||||
let azure_provider_toml = r#"
|
||||
name = "Ollama"
|
||||
base_url = "http://localhost:11434/v1"
|
||||
"#;
|
||||
let expected_provider = ModelProviderInfo {
|
||||
name: "Ollama".into(),
|
||||
base_url: Some("http://localhost:11434/v1".into()),
|
||||
model_catalog_url: None,
|
||||
env_key: None,
|
||||
env_key_instructions: None,
|
||||
experimental_bearer_token: None,
|
||||
auth: None,
|
||||
gateway_oauth: None,
|
||||
api_key: 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,
|
||||
capabilities: None,
|
||||
merge_system_messages: None,
|
||||
keyring_account: None,
|
||||
include_internal_metadata: false,
|
||||
};
|
||||
|
||||
let provider: ModelProviderInfo = toml::from_str(azure_provider_toml).unwrap();
|
||||
assert_eq!(expected_provider, provider);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_deserialize_azure_model_provider_toml() {
|
||||
let azure_provider_toml = r#"
|
||||
name = "Azure"
|
||||
base_url = "https://xxxxx.openai.azure.com/openai"
|
||||
env_key = "AZURE_OPENAI_API_KEY"
|
||||
query_params = { api-version = "2025-04-01-preview" }
|
||||
"#;
|
||||
let expected_provider = ModelProviderInfo {
|
||||
name: "Azure".into(),
|
||||
base_url: Some("https://xxxxx.openai.azure.com/openai".into()),
|
||||
model_catalog_url: None,
|
||||
env_key: Some("AZURE_OPENAI_API_KEY".into()),
|
||||
env_key_instructions: None,
|
||||
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(),
|
||||
}),
|
||||
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,
|
||||
capabilities: None,
|
||||
merge_system_messages: None,
|
||||
keyring_account: None,
|
||||
include_internal_metadata: false,
|
||||
};
|
||||
|
||||
let provider: ModelProviderInfo = toml::from_str(azure_provider_toml).unwrap();
|
||||
assert_eq!(expected_provider, provider);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_deserialize_example_model_provider_toml() {
|
||||
let azure_provider_toml = r#"
|
||||
name = "Example"
|
||||
base_url = "https://example.com"
|
||||
env_key = "API_KEY"
|
||||
http_headers = { "X-Example-Header" = "example-value" }
|
||||
env_http_headers = { "X-Example-Env-Header" = "EXAMPLE_ENV_VAR" }
|
||||
supports_standalone_web_search = true
|
||||
"#;
|
||||
let expected_provider = ModelProviderInfo {
|
||||
name: "Example".into(),
|
||||
base_url: Some("https://example.com".into()),
|
||||
model_catalog_url: None,
|
||||
env_key: Some("API_KEY".into()),
|
||||
env_key_instructions: None,
|
||||
experimental_bearer_token: None,
|
||||
auth: None,
|
||||
gateway_oauth: None,
|
||||
api_key: None,
|
||||
wire_api: WireApi::Responses,
|
||||
query_params: None,
|
||||
http_headers: Some(maplit::hashmap! {
|
||||
"X-Example-Header".to_string() => "example-value".into(),
|
||||
}),
|
||||
env_http_headers: Some(maplit::hashmap! {
|
||||
"X-Example-Env-Header".to_string() => "EXAMPLE_ENV_VAR".to_string(),
|
||||
}),
|
||||
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: true,
|
||||
capabilities: None,
|
||||
merge_system_messages: None,
|
||||
keyring_account: None,
|
||||
include_internal_metadata: false,
|
||||
};
|
||||
|
||||
let provider: ModelProviderInfo = toml::from_str(azure_provider_toml).unwrap();
|
||||
assert_eq!(expected_provider, provider);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_deserialize_chat_wire_api_shows_helpful_error() {
|
||||
let provider_toml = r#"
|
||||
name = "OpenAI using Chat Completions"
|
||||
base_url = "https://api.openai.com/v1"
|
||||
env_key = "OPENAI_API_KEY"
|
||||
wire_api = "chat"
|
||||
"#;
|
||||
|
||||
let err = toml::from_str::<ModelProviderInfo>(provider_toml).unwrap_err();
|
||||
assert!(err.to_string().contains(CHAT_WIRE_API_REMOVED_ERROR));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_deserialize_websocket_connect_timeout() {
|
||||
let provider_toml = r#"
|
||||
name = "OpenAI"
|
||||
base_url = "https://api.openai.com/v1"
|
||||
websocket_connect_timeout_ms = 15000
|
||||
supports_websockets = true
|
||||
"#;
|
||||
|
||||
let provider: ModelProviderInfo = toml::from_str(provider_toml).unwrap();
|
||||
assert_eq!(provider.websocket_connect_timeout_ms, Some(15_000));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_deserialize_provider_auth_config_defaults() {
|
||||
let base_dir = tempdir().unwrap();
|
||||
let provider_toml = r#"
|
||||
name = "Corp"
|
||||
|
||||
[auth]
|
||||
command = "./scripts/print-token"
|
||||
args = ["--format=text"]
|
||||
"#;
|
||||
|
||||
let provider: ModelProviderInfo = {
|
||||
let _guard = AbsolutePathBufGuard::new(base_dir.path());
|
||||
toml::from_str(provider_toml).unwrap()
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
provider.auth,
|
||||
Some(ModelProviderAuthInfo {
|
||||
command: "./scripts/print-token".to_string(),
|
||||
args: vec!["--format=text".into()],
|
||||
timeout_ms: NonZeroU64::new(5_000).unwrap(),
|
||||
refresh_interval_ms: 300_000,
|
||||
cwd: AbsolutePathBuf::resolve_path_against_base(".", base_dir.path()),
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_merge_configured_model_providers_adds_custom_provider() {
|
||||
let custom_provider = ModelProviderInfo {
|
||||
name: "Custom".to_string(),
|
||||
base_url: Some("https://example.com/v1".to_string()),
|
||||
..ModelProviderInfo::default()
|
||||
};
|
||||
let configured_model_providers =
|
||||
std::collections::HashMap::from([("custom".to_string(), custom_provider.clone())]);
|
||||
|
||||
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(), configured_model_providers,),
|
||||
Ok(expected)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_deserialize_provider_auth_config_allows_zero_refresh_interval() {
|
||||
let base_dir = tempdir().unwrap();
|
||||
let provider_toml = r#"
|
||||
name = "Corp"
|
||||
|
||||
[auth]
|
||||
command = "./scripts/print-token"
|
||||
refresh_interval_ms = 0
|
||||
"#;
|
||||
|
||||
let provider: ModelProviderInfo = {
|
||||
let _guard = AbsolutePathBufGuard::new(base_dir.path());
|
||||
toml::from_str(provider_toml).unwrap()
|
||||
};
|
||||
|
||||
let auth = provider.auth.expect("auth config should deserialize");
|
||||
assert_eq!(auth.refresh_interval_ms, 0);
|
||||
assert_eq!(auth.refresh_interval(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_catalog_url_deserializes_without_changing_inference_routing() {
|
||||
let provider: ModelProviderInfo = toml::from_str(
|
||||
r#"
|
||||
name = "Gateway"
|
||||
base_url = "https://gateway.example/v1"
|
||||
model_catalog_url = "https://gateway.example/codex/catalog?token=catalog-secret"
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(!format!("{provider:?}").contains("catalog-secret"));
|
||||
assert_eq!(
|
||||
provider,
|
||||
ModelProviderInfo {
|
||||
name: "Gateway".to_string(),
|
||||
base_url: Some("https://gateway.example/v1".to_string()),
|
||||
model_catalog_url: Some(
|
||||
"https://gateway.example/codex/catalog?token=catalog-secret".into()
|
||||
),
|
||||
..ModelProviderInfo::default()
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
provider.to_api_provider().unwrap().base_url,
|
||||
"https://gateway.example/v1"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_cyber_access_programs_capability_is_accepted_and_ignored() {
|
||||
for configured in [None, Some(false), Some(true)] {
|
||||
let config = match configured {
|
||||
Some(enabled) => {
|
||||
format!("name = \"OpenAI\"\n[capabilities]\ncyber_access_programs = {enabled}\n")
|
||||
}
|
||||
None => "name = \"OpenAI\"\n".to_owned(),
|
||||
};
|
||||
let provider: ModelProviderInfo = toml::from_str(&config).unwrap();
|
||||
let round_trip: ModelProviderInfo =
|
||||
toml::from_str(&toml::to_string(&provider).unwrap()).unwrap();
|
||||
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("AKODE_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());
|
||||
}
|
||||
}
|
||||
41
akode-rs/model-provider-info/src/oauth_session.rs
Normal file
41
akode-rs/model-provider-info/src/oauth_session.rs
Normal file
@@ -0,0 +1,41 @@
|
||||
//! Public-client OAuth settings shared by managed configuration and service sign-in.
|
||||
|
||||
use schemars::JsonSchema;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use std::fmt;
|
||||
|
||||
/// Settings identifying a configured OAuth grant, independent of token delivery.
|
||||
#[derive(Clone, PartialEq, Eq, Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct OAuthSessionConfig {
|
||||
pub authorization_url: String,
|
||||
pub token_url: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub device_authorization_url: Option<String>,
|
||||
pub client_id: String,
|
||||
pub resource: Option<String>,
|
||||
#[serde(default)]
|
||||
pub scopes: Vec<String>,
|
||||
pub redirect_port: Option<u16>,
|
||||
/// Selected by a gateway provider. Managed config-server OAuth uses the default store.
|
||||
#[serde(skip)]
|
||||
pub credentials_store: OAuthCredentialsStore,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize, PartialEq, Eq, JsonSchema)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum OAuthCredentialsStore {
|
||||
/// Encrypt credentials using a passphrase kept in the OS keyring.
|
||||
#[default]
|
||||
Keyring,
|
||||
/// Store credentials in plaintext in `$AKODE_HOME/secrets/gateway_oauth.json`.
|
||||
File,
|
||||
}
|
||||
|
||||
impl fmt::Debug for OAuthSessionConfig {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
// Issuer settings may contain credentials in arbitrary query parameters.
|
||||
f.debug_struct("OAuthSessionConfig").finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user