533 lines
19 KiB
Rust
533 lines
19 KiB
Rust
use std::fmt;
|
|
use std::future::Future;
|
|
use std::path::PathBuf;
|
|
use std::pin::Pin;
|
|
use std::sync::Arc;
|
|
|
|
use crate::GatewayAuthManager;
|
|
use akode_api::ApiError;
|
|
use akode_api::Provider;
|
|
use akode_api::SharedAuthProvider;
|
|
use akode_api::TransportError;
|
|
use akode_login::AuthManager;
|
|
use akode_login::CodexAuth;
|
|
use akode_model_provider_info::ModelProviderInfo;
|
|
use akode_models_manager::cache::ModelsCache;
|
|
use akode_models_manager::manager::ModelCatalogSettings;
|
|
use akode_models_manager::manager::OpenAiModelsManager;
|
|
use akode_models_manager::manager::SharedModelsManager;
|
|
use akode_models_manager::manager::StaticModelsManager;
|
|
use akode_protocol::account::ProviderAccount;
|
|
use akode_protocol::error::CodexErr;
|
|
use akode_protocol::openai_models::ModelsResponse;
|
|
|
|
use crate::ProviderCapabilities;
|
|
use crate::auth::ResolvedProviderAuth;
|
|
use crate::auth::auth_manager_for_provider;
|
|
use crate::auth::resolve_provider_auth;
|
|
use crate::combined_auth::compose_auth;
|
|
use crate::local_models::LocalModelsManager;
|
|
use crate::models_endpoint::OpenAiModelsEndpoint;
|
|
use crate::request_setup::resolve_request_auth;
|
|
|
|
/// Current app-visible account state for a model provider.
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub struct ProviderAccountState {
|
|
pub account: Option<ProviderAccount>,
|
|
pub requires_openai_auth: bool,
|
|
}
|
|
|
|
/// Outcome of a provider-owned attempt to recover from an authentication failure.
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
pub enum ProviderUnauthorizedRecovery {
|
|
/// The provider has no provider-specific authentication recovery configured.
|
|
NotConfigured,
|
|
/// The provider recovered its authentication state and the request can be retried.
|
|
Recovered,
|
|
}
|
|
|
|
/// User-facing lifecycle messages for provider-owned authentication recovery.
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
pub struct ProviderAuthRecoveryMessages {
|
|
pub started: &'static str,
|
|
pub succeeded: &'static str,
|
|
}
|
|
|
|
/// Error returned when a provider cannot construct its app-visible account state.
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
pub enum ProviderAccountError {}
|
|
|
|
impl fmt::Display for ProviderAccountError {
|
|
fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
match *self {}
|
|
}
|
|
}
|
|
|
|
impl std::error::Error for ProviderAccountError {}
|
|
|
|
pub type ProviderAccountResult = std::result::Result<ProviderAccountState, ProviderAccountError>;
|
|
|
|
/// Default model used for automatic approval review when a provider does not
|
|
/// require a backend-specific model ID.
|
|
pub const DEFAULT_APPROVAL_REVIEW_PREFERRED_MODEL: &str = "codex-auto-review";
|
|
|
|
const API_KEY_APPROVAL_REVIEW_PREFERRED_MODEL: &str = "gpt-5.6-luna";
|
|
|
|
/// Default model used for memory extraction when a provider does not require a
|
|
/// backend-specific model ID.
|
|
pub const DEFAULT_MEMORY_EXTRACTION_PREFERRED_MODEL: &str = "gpt-6-luna";
|
|
|
|
/// Default model used for memory consolidation when a provider does not require
|
|
/// a backend-specific model ID.
|
|
pub const DEFAULT_MEMORY_CONSOLIDATION_PREFERRED_MODEL: &str = "gpt-6.1-terra";
|
|
|
|
/// Runtime provider abstraction used by model execution.
|
|
///
|
|
/// Implementations own provider-specific behavior for a model backend. The
|
|
/// `ModelProviderInfo` returned by `info` is the serialized/configured provider
|
|
/// metadata used by the default OpenAI-compatible implementation.
|
|
///
|
|
/// OpenAI-compatible catalog caches are keyed by provider settings and the request
|
|
/// credentials, so a changed credential never reuses another principal's catalog.
|
|
pub trait ModelProvider: fmt::Debug + Send + Sync {
|
|
/// Returns the configured provider metadata.
|
|
fn info(&self) -> &ModelProviderInfo;
|
|
|
|
/// Returns whether the resolved Responses provider may receive internal tool metadata.
|
|
fn include_internal_metadata(&self, provider: &Provider) -> bool {
|
|
let _ = provider;
|
|
self.info().include_internal_metadata
|
|
}
|
|
|
|
/// Returns the provider-owned capability upper bounds.
|
|
fn capabilities(&self) -> ProviderCapabilities {
|
|
ProviderCapabilities::default()
|
|
}
|
|
|
|
/// Returns the preferred model used for automatic approval review.
|
|
///
|
|
/// Providers that require backend-specific model IDs should override this.
|
|
fn approval_review_preferred_model(&self) -> &'static str {
|
|
DEFAULT_APPROVAL_REVIEW_PREFERRED_MODEL
|
|
}
|
|
|
|
/// Returns the preferred model used for memory extraction.
|
|
///
|
|
/// Providers that require backend-specific model IDs should override this.
|
|
fn memory_extraction_preferred_model(&self) -> &'static str {
|
|
DEFAULT_MEMORY_EXTRACTION_PREFERRED_MODEL
|
|
}
|
|
|
|
/// Returns the preferred model used for memory consolidation.
|
|
///
|
|
/// Providers that require backend-specific model IDs should override this.
|
|
fn memory_consolidation_preferred_model(&self) -> &'static str {
|
|
DEFAULT_MEMORY_CONSOLIDATION_PREFERRED_MODEL
|
|
}
|
|
|
|
/// Returns the provider-scoped auth manager, when this provider uses one.
|
|
///
|
|
/// TODO(celia-oai): Make auth manager access internal to this crate so callers
|
|
/// resolve provider-specific auth only through `ModelProvider`. We first need
|
|
/// to think through whether Codex should have a unified provider-specific auth
|
|
/// manager throughout the codebase; that is a larger refactor than this change.
|
|
fn auth_manager(&self) -> Option<Arc<AuthManager>>;
|
|
|
|
/// Returns the gateway credential manager shared with inference and model discovery.
|
|
/// Hosts use this handle for explicit login; configured setup failures remain errors.
|
|
fn gateway_auth_manager(&self) -> std::io::Result<Option<Arc<GatewayAuthManager>>> {
|
|
Ok(None)
|
|
}
|
|
|
|
/// Returns whether this transport failure can be recovered by provider-scoped authentication.
|
|
///
|
|
/// The default preserves existing unauthorized-response handling. Providers with other
|
|
/// authentication failure shapes may recognize additional response or request-signing errors.
|
|
fn is_recoverable_auth_error(&self, error: &TransportError) -> bool {
|
|
matches!(
|
|
error,
|
|
TransportError::Http { status, .. } if *status == http::StatusCode::UNAUTHORIZED
|
|
)
|
|
}
|
|
|
|
/// Returns lifecycle messages when provider-owned authentication recovery is active.
|
|
fn auth_recovery_messages(&self) -> Option<ProviderAuthRecoveryMessages> {
|
|
None
|
|
}
|
|
|
|
/// Attempts provider-owned authentication recovery before using the auth manager.
|
|
fn recover_from_unauthorized(
|
|
&self,
|
|
) -> ModelProviderFuture<'_, akode_protocol::error::Result<ProviderUnauthorizedRecovery>> {
|
|
Box::pin(async { Ok(ProviderUnauthorizedRecovery::NotConfigured) })
|
|
}
|
|
|
|
/// Returns the current provider-scoped auth value, if one is configured.
|
|
fn auth(&self) -> ModelProviderFuture<'_, Option<CodexAuth>>;
|
|
|
|
/// Returns the current app-visible account state for this provider.
|
|
fn account_state(&self) -> ProviderAccountResult;
|
|
|
|
/// Maps an API client error into the provider's user-facing error representation.
|
|
fn map_api_error(&self, error: ApiError) -> CodexErr {
|
|
akode_api::map_api_error(error)
|
|
}
|
|
|
|
/// Returns provider configuration adapted for the API client.
|
|
fn api_provider(&self) -> ModelProviderFuture<'_, akode_protocol::error::Result<Provider>> {
|
|
Box::pin(async move {
|
|
let auth = self.auth().await;
|
|
self.api_provider_for_auth(auth.as_ref())
|
|
})
|
|
}
|
|
|
|
/// Adapt routing from the same frozen credential selected for the request.
|
|
fn api_provider_for_auth(
|
|
&self,
|
|
auth: Option<&CodexAuth>,
|
|
) -> akode_protocol::error::Result<Provider> {
|
|
resolve_api_provider(self.info(), auth)
|
|
}
|
|
|
|
/// Returns the provider base URL that will be used at request time.
|
|
fn runtime_base_url(
|
|
&self,
|
|
) -> ModelProviderFuture<'_, akode_protocol::error::Result<Option<String>>> {
|
|
Box::pin(async { Ok(self.info().base_url.clone()) })
|
|
}
|
|
|
|
/// Returns the auth provider used to attach request credentials.
|
|
fn api_auth(
|
|
&self,
|
|
) -> ModelProviderFuture<'_, akode_protocol::error::Result<SharedAuthProvider>> {
|
|
Box::pin(async move {
|
|
let auth = self.auth().await;
|
|
resolve_provider_auth(auth.as_ref(), self.info())
|
|
})
|
|
}
|
|
|
|
/// Adds provider-owned credentials, such as gateway OAuth, to already selected primary auth.
|
|
fn compose_auth(
|
|
&self,
|
|
resolved: ResolvedProviderAuth,
|
|
) -> ModelProviderFuture<'_, akode_protocol::error::Result<ResolvedProviderAuth>> {
|
|
Box::pin(async move { Ok(resolved) })
|
|
}
|
|
|
|
/// Resolve auth together with metadata needed to route and admit this request.
|
|
fn request_auth(
|
|
&self,
|
|
) -> ModelProviderFuture<'_, akode_protocol::error::Result<ResolvedProviderAuth>> {
|
|
Box::pin(async { self.api_auth().await.map(ResolvedProviderAuth::new) })
|
|
}
|
|
|
|
/// Resolve the endpoint before headers for providers whose setup may refresh credentials.
|
|
fn request_provider_and_auth(
|
|
&self,
|
|
) -> ModelProviderFuture<'_, akode_protocol::error::Result<(Provider, ResolvedProviderAuth)>>
|
|
{
|
|
Box::pin(async move { Ok((self.api_provider().await?, self.request_auth().await?)) })
|
|
}
|
|
|
|
/// Creates the model manager implementation appropriate for this provider.
|
|
fn models_manager(
|
|
&self,
|
|
codex_home: PathBuf,
|
|
config_model_catalog: Option<ModelsResponse>,
|
|
) -> SharedModelsManager;
|
|
|
|
/// Build a thread catalog with the same cache and live discovery policy as its harness.
|
|
fn models_manager_with_settings(
|
|
&self,
|
|
config_model_catalog: Option<ModelsResponse>,
|
|
_settings: ModelCatalogSettings,
|
|
) -> SharedModelsManager {
|
|
self.models_manager_without_cache(config_model_catalog)
|
|
}
|
|
|
|
/// Creates a model manager with caching disabled.
|
|
///
|
|
/// Providers that fetch model catalogs should override this method. The default uses an
|
|
/// authoritative in-memory catalog so hosted callers cannot accidentally write to disk.
|
|
fn models_manager_without_cache(
|
|
&self,
|
|
config_model_catalog: Option<ModelsResponse>,
|
|
) -> SharedModelsManager {
|
|
let origin = if config_model_catalog.is_some() {
|
|
akode_models_manager::ModelOrigin::ExplicitConfig
|
|
} else {
|
|
akode_models_manager::ModelOrigin::Bundled
|
|
};
|
|
let model_catalog = config_model_catalog
|
|
.or_else(|| akode_models_manager::bundled_models_response().ok())
|
|
.unwrap_or_default();
|
|
Arc::new(StaticModelsManager::new(
|
|
self.auth_manager(),
|
|
model_catalog,
|
|
origin,
|
|
))
|
|
}
|
|
|
|
/// Creates a model manager that can use a caller-provided cache for remote catalogs.
|
|
///
|
|
/// Providers with remote catalogs should override this method. The default preserves the
|
|
/// authoritative catalog returned by [`ModelProvider::models_manager_without_cache`] and does
|
|
/// not consult `cache`. Implementations should likewise ignore the cache when
|
|
/// `config_model_catalog` supplies an authoritative static catalog.
|
|
fn models_manager_with_cache(
|
|
&self,
|
|
config_model_catalog: Option<ModelsResponse>,
|
|
cache: Arc<dyn ModelsCache>,
|
|
) -> SharedModelsManager {
|
|
drop(cache);
|
|
self.models_manager_without_cache(config_model_catalog)
|
|
}
|
|
}
|
|
|
|
pub type ModelProviderFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
|
|
|
|
/// Shared runtime model provider handle.
|
|
pub type SharedModelProvider = Arc<dyn ModelProvider>;
|
|
|
|
/// Resolve credential-dependent defaults without changing configured endpoints.
|
|
pub fn resolve_api_provider(
|
|
info: &ModelProviderInfo,
|
|
auth: Option<&CodexAuth>,
|
|
) -> akode_protocol::error::Result<Provider> {
|
|
let _ = auth;
|
|
info.to_api_provider()
|
|
}
|
|
|
|
/// Whether requests use the credential stored by `akode login --with-api-key` (or supplied
|
|
/// by a host) rather than provider-owned keyring, env, bearer, or command credentials.
|
|
pub fn provider_uses_stored_auth(provider: &ModelProviderInfo) -> bool {
|
|
provider.requires_openai_auth
|
|
&& provider.api_key.is_none()
|
|
&& provider.env_key.is_none()
|
|
&& provider.experimental_bearer_token.is_none()
|
|
&& provider.auth.is_none()
|
|
}
|
|
|
|
/// Creates the default model provider for configured provider metadata.
|
|
pub fn create_model_provider(
|
|
provider_info: ModelProviderInfo,
|
|
auth_manager: Option<Arc<AuthManager>>,
|
|
) -> SharedModelProvider {
|
|
Arc::new(ConfiguredModelProvider::new(provider_info, auth_manager))
|
|
}
|
|
|
|
/// Runtime model provider that orchestrates primary and gateway credentials.
|
|
#[derive(Clone, Debug)]
|
|
struct ConfiguredModelProvider {
|
|
info: ModelProviderInfo,
|
|
auth_manager: Option<Arc<AuthManager>>,
|
|
// Construct eagerly; report setup failures when auth is requested because the factory is infallible.
|
|
gateway_auth_manager: Option<Result<Arc<GatewayAuthManager>, String>>,
|
|
}
|
|
|
|
impl ConfiguredModelProvider {
|
|
fn new(info: ModelProviderInfo, auth_manager: Option<Arc<AuthManager>>) -> Self {
|
|
let gateway_auth_manager = info.gateway_oauth.as_ref().map(|config| {
|
|
info.validate()?;
|
|
let manager = auth_manager
|
|
.as_ref()
|
|
.ok_or_else(|| "gateway_oauth requires auth runtime configuration".to_string())?;
|
|
GatewayAuthManager::new(&info, config, manager).map(Arc::new)
|
|
});
|
|
let auth_manager = auth_manager_for_provider(auth_manager, &info);
|
|
Self {
|
|
info,
|
|
auth_manager,
|
|
gateway_auth_manager,
|
|
}
|
|
}
|
|
|
|
async fn resolve_auth(&self) -> akode_protocol::error::Result<ResolvedProviderAuth> {
|
|
let resolved = resolve_request_auth(self.info.clone(), self.auth_manager.clone()).await?;
|
|
self.compose_auth(resolved).await
|
|
}
|
|
}
|
|
|
|
impl ModelProvider for ConfiguredModelProvider {
|
|
fn info(&self) -> &ModelProviderInfo {
|
|
&self.info
|
|
}
|
|
|
|
fn capabilities(&self) -> ProviderCapabilities {
|
|
ProviderCapabilities::from_config(&self.info)
|
|
}
|
|
|
|
fn approval_review_preferred_model(&self) -> &'static str {
|
|
if self
|
|
.auth_manager
|
|
.as_ref()
|
|
.and_then(|auth_manager| auth_manager.auth_cached())
|
|
.is_some_and(|auth| auth.is_api_key_auth())
|
|
{
|
|
API_KEY_APPROVAL_REVIEW_PREFERRED_MODEL
|
|
} else {
|
|
DEFAULT_APPROVAL_REVIEW_PREFERRED_MODEL
|
|
}
|
|
}
|
|
|
|
fn auth_manager(&self) -> Option<Arc<AuthManager>> {
|
|
self.auth_manager.clone()
|
|
}
|
|
|
|
fn gateway_auth_manager(&self) -> std::io::Result<Option<Arc<GatewayAuthManager>>> {
|
|
self.gateway_auth_manager
|
|
.clone()
|
|
.transpose()
|
|
.map_err(std::io::Error::other)
|
|
}
|
|
|
|
fn recover_from_unauthorized(
|
|
&self,
|
|
) -> ModelProviderFuture<'_, akode_protocol::error::Result<ProviderUnauthorizedRecovery>> {
|
|
Box::pin(async {
|
|
let Some(gateway) = self.gateway_auth_manager()? else {
|
|
return Ok(ProviderUnauthorizedRecovery::NotConfigured);
|
|
};
|
|
Ok(gateway.prepare_retry().await)
|
|
})
|
|
}
|
|
|
|
fn auth(&self) -> ModelProviderFuture<'_, Option<CodexAuth>> {
|
|
Box::pin(async move {
|
|
match self.auth_manager.as_ref() {
|
|
Some(auth_manager) => auth_manager.auth().await,
|
|
None => None,
|
|
}
|
|
})
|
|
}
|
|
|
|
fn request_auth(
|
|
&self,
|
|
) -> ModelProviderFuture<'_, akode_protocol::error::Result<ResolvedProviderAuth>> {
|
|
Box::pin(self.resolve_auth())
|
|
}
|
|
|
|
fn request_provider_and_auth(
|
|
&self,
|
|
) -> ModelProviderFuture<'_, akode_protocol::error::Result<(Provider, ResolvedProviderAuth)>>
|
|
{
|
|
Box::pin(async move {
|
|
let resolved = self.resolve_auth().await?;
|
|
let provider = self.api_provider_for_auth(resolved.credential.as_ref())?;
|
|
Ok((provider, resolved))
|
|
})
|
|
}
|
|
|
|
fn api_auth(
|
|
&self,
|
|
) -> ModelProviderFuture<'_, akode_protocol::error::Result<SharedAuthProvider>> {
|
|
Box::pin(async move { Ok(self.resolve_auth().await?.auth) })
|
|
}
|
|
|
|
fn compose_auth(
|
|
&self,
|
|
resolved: ResolvedProviderAuth,
|
|
) -> ModelProviderFuture<'_, akode_protocol::error::Result<ResolvedProviderAuth>> {
|
|
Box::pin(compose_auth(
|
|
&self.info,
|
|
self.gateway_auth_manager.as_ref(),
|
|
resolved,
|
|
))
|
|
}
|
|
|
|
fn account_state(&self) -> ProviderAccountResult {
|
|
let account = if self.info.requires_openai_auth {
|
|
self.auth_manager
|
|
.as_ref()
|
|
.and_then(|auth_manager| {
|
|
let auth = auth_manager.auth_cached()?;
|
|
if auth_manager.refresh_failure_for_auth(&auth).is_some() {
|
|
return None;
|
|
}
|
|
if matches!(auth, CodexAuth::Headers(_)) {
|
|
return None;
|
|
}
|
|
Some(auth)
|
|
})
|
|
.map(|auth| match &auth {
|
|
CodexAuth::ApiKey(_) => ProviderAccount::ApiKey,
|
|
CodexAuth::Headers(_) => {
|
|
unreachable!("header auth is filtered out above")
|
|
}
|
|
})
|
|
} else {
|
|
None
|
|
};
|
|
|
|
Ok(ProviderAccountState {
|
|
account,
|
|
requires_openai_auth: self.info.requires_openai_auth,
|
|
})
|
|
}
|
|
|
|
fn models_manager(
|
|
&self,
|
|
codex_home: PathBuf,
|
|
config_model_catalog: Option<ModelsResponse>,
|
|
) -> SharedModelsManager {
|
|
self.models_manager_with_settings(
|
|
config_model_catalog,
|
|
ModelCatalogSettings::disk(codex_home),
|
|
)
|
|
}
|
|
|
|
fn models_manager_with_settings(
|
|
&self,
|
|
config_model_catalog: Option<ModelsResponse>,
|
|
settings: ModelCatalogSettings,
|
|
) -> SharedModelsManager {
|
|
if let Some(model_catalog) = config_model_catalog {
|
|
return Arc::new(StaticModelsManager::new(
|
|
self.auth_manager.clone(),
|
|
model_catalog,
|
|
akode_models_manager::ModelOrigin::ExplicitConfig,
|
|
));
|
|
}
|
|
let endpoint = Arc::new(OpenAiModelsEndpoint::new(
|
|
self.info.clone(),
|
|
self.auth_manager.clone(),
|
|
self.gateway_auth_manager.clone(),
|
|
));
|
|
let auth_manager = self.auth_manager.clone();
|
|
match &self.info.model_catalog_url {
|
|
// A Codex-format catalog configured for this provider.
|
|
Some(_) => Arc::new(
|
|
OpenAiModelsManager::with_settings(settings, endpoint, auth_manager)
|
|
.with_provider_catalog(),
|
|
),
|
|
// No built-in catalog: list the server's OpenAI-format `/models`.
|
|
None => {
|
|
let _ = settings;
|
|
Arc::new(LocalModelsManager::new(endpoint, auth_manager))
|
|
}
|
|
}
|
|
}
|
|
|
|
fn models_manager_without_cache(
|
|
&self,
|
|
config_model_catalog: Option<ModelsResponse>,
|
|
) -> SharedModelsManager {
|
|
self.models_manager_with_settings(config_model_catalog, ModelCatalogSettings::default())
|
|
}
|
|
|
|
fn models_manager_with_cache(
|
|
&self,
|
|
config_model_catalog: Option<ModelsResponse>,
|
|
cache: Arc<dyn ModelsCache>,
|
|
) -> SharedModelsManager {
|
|
self.models_manager_with_settings(
|
|
config_model_catalog,
|
|
ModelCatalogSettings::with_cache(cache),
|
|
)
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
#[path = "provider_tests.rs"]
|
|
mod tests;
|