mirror of
https://github.com/openai/codex.git
synced 2026-11-23 23:10:47 +00:00
feat(models): support authoritative remote catalogs
This commit is contained in:
Generated
+1
@@ -3354,6 +3354,7 @@ dependencies = [
|
||||
"codex-app-server-protocol",
|
||||
"codex-collaboration-mode-templates",
|
||||
"codex-login",
|
||||
"codex-model-provider-info",
|
||||
"codex-otel",
|
||||
"codex-protocol",
|
||||
"codex-utils-output-truncation",
|
||||
|
||||
@@ -312,6 +312,7 @@ mod tests {
|
||||
stream_idle_timeout_ms: None,
|
||||
websocket_connect_timeout_ms: None,
|
||||
requires_openai_auth: false,
|
||||
model_catalog_policy: Default::default(),
|
||||
supports_websockets: true,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,6 +48,7 @@ message ModelProvider {
|
||||
optional uint64 websocket_connect_timeout_ms = 15;
|
||||
bool requires_openai_auth = 16;
|
||||
bool supports_websockets = 17;
|
||||
ModelCatalogPolicy model_catalog_policy = 18;
|
||||
}
|
||||
|
||||
message StringMap {
|
||||
@@ -66,3 +67,9 @@ enum WireApi {
|
||||
WIRE_API_UNSPECIFIED = 0;
|
||||
WIRE_API_RESPONSES = 1;
|
||||
}
|
||||
|
||||
enum ModelCatalogPolicy {
|
||||
MODEL_CATALOG_POLICY_UNSPECIFIED = 0;
|
||||
MODEL_CATALOG_POLICY_AUTO = 1;
|
||||
MODEL_CATALOG_POLICY_REMOTE_AUTHORITATIVE = 2;
|
||||
}
|
||||
|
||||
@@ -75,6 +75,8 @@ pub struct ModelProvider {
|
||||
pub requires_openai_auth: bool,
|
||||
#[prost(bool, tag = "17")]
|
||||
pub supports_websockets: bool,
|
||||
#[prost(enumeration = "ModelCatalogPolicy", tag = "18")]
|
||||
pub model_catalog_policy: i32,
|
||||
}
|
||||
#[derive(Clone, PartialEq, ::prost::Message)]
|
||||
pub struct StringMap {
|
||||
@@ -121,6 +123,35 @@ impl WireApi {
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)]
|
||||
#[repr(i32)]
|
||||
pub enum ModelCatalogPolicy {
|
||||
Unspecified = 0,
|
||||
Auto = 1,
|
||||
RemoteAuthoritative = 2,
|
||||
}
|
||||
impl ModelCatalogPolicy {
|
||||
/// String value of the enum field names used in the ProtoBuf definition.
|
||||
///
|
||||
/// The values are not transformed in any way and thus are considered stable
|
||||
/// (if the ProtoBuf definition does not change) and safe for programmatic use.
|
||||
pub fn as_str_name(&self) -> &'static str {
|
||||
match self {
|
||||
Self::Unspecified => "MODEL_CATALOG_POLICY_UNSPECIFIED",
|
||||
Self::Auto => "MODEL_CATALOG_POLICY_AUTO",
|
||||
Self::RemoteAuthoritative => "MODEL_CATALOG_POLICY_REMOTE_AUTHORITATIVE",
|
||||
}
|
||||
}
|
||||
/// Creates an enum from field names used in the ProtoBuf definition.
|
||||
pub fn from_str_name(value: &str) -> ::core::option::Option<Self> {
|
||||
match value {
|
||||
"MODEL_CATALOG_POLICY_UNSPECIFIED" => Some(Self::Unspecified),
|
||||
"MODEL_CATALOG_POLICY_AUTO" => Some(Self::Auto),
|
||||
"MODEL_CATALOG_POLICY_REMOTE_AUTHORITATIVE" => Some(Self::RemoteAuthoritative),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Generated client implementations.
|
||||
pub mod thread_config_loader_client {
|
||||
#![allow(
|
||||
|
||||
@@ -4,6 +4,7 @@ use std::num::NonZeroU64;
|
||||
use std::time::Duration;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use codex_model_provider_info::ModelCatalogPolicy;
|
||||
use codex_model_provider_info::ModelProviderInfo;
|
||||
use codex_model_provider_info::WireApi;
|
||||
use codex_protocol::config_types::ModelProviderAuthInfo;
|
||||
@@ -163,6 +164,21 @@ fn model_provider_from_proto(
|
||||
)));
|
||||
}
|
||||
};
|
||||
let model_catalog_policy =
|
||||
match proto::ModelCatalogPolicy::try_from(provider.model_catalog_policy) {
|
||||
Ok(proto::ModelCatalogPolicy::Unspecified | proto::ModelCatalogPolicy::Auto) => {
|
||||
ModelCatalogPolicy::Auto
|
||||
}
|
||||
Ok(proto::ModelCatalogPolicy::RemoteAuthoritative) => {
|
||||
ModelCatalogPolicy::RemoteAuthoritative
|
||||
}
|
||||
Err(_) => {
|
||||
return Err(parse_error(format!(
|
||||
"remote thread config returned unknown model_catalog_policy: {}",
|
||||
provider.model_catalog_policy
|
||||
)));
|
||||
}
|
||||
};
|
||||
let info = ModelProviderInfo {
|
||||
name: provider.name,
|
||||
base_url: provider.base_url,
|
||||
@@ -183,6 +199,7 @@ fn model_provider_from_proto(
|
||||
stream_idle_timeout_ms: provider.stream_idle_timeout_ms,
|
||||
websocket_connect_timeout_ms: provider.websocket_connect_timeout_ms,
|
||||
requires_openai_auth: provider.requires_openai_auth,
|
||||
model_catalog_policy,
|
||||
supports_websockets: provider.supports_websockets,
|
||||
};
|
||||
Ok((id, info))
|
||||
@@ -210,6 +227,7 @@ fn model_provider_to_proto(
|
||||
stream_idle_timeout_ms,
|
||||
websocket_connect_timeout_ms,
|
||||
requires_openai_auth,
|
||||
model_catalog_policy,
|
||||
supports_websockets,
|
||||
} = provider;
|
||||
|
||||
@@ -231,6 +249,12 @@ fn model_provider_to_proto(
|
||||
websocket_connect_timeout_ms,
|
||||
requires_openai_auth,
|
||||
supports_websockets,
|
||||
model_catalog_policy: match model_catalog_policy {
|
||||
ModelCatalogPolicy::Auto => proto::ModelCatalogPolicy::Auto.into(),
|
||||
ModelCatalogPolicy::RemoteAuthoritative => {
|
||||
proto::ModelCatalogPolicy::RemoteAuthoritative.into()
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -448,6 +472,8 @@ mod tests {
|
||||
websocket_connect_timeout_ms: Some(10_000),
|
||||
requires_openai_auth: false,
|
||||
supports_websockets: true,
|
||||
model_catalog_policy: proto::ModelCatalogPolicy::RemoteAuthoritative
|
||||
.into(),
|
||||
}],
|
||||
features: HashMap::from([
|
||||
("plugins".to_string(), false),
|
||||
@@ -510,6 +536,7 @@ mod tests {
|
||||
stream_idle_timeout_ms: Some(9_000),
|
||||
websocket_connect_timeout_ms: Some(10_000),
|
||||
requires_openai_auth: false,
|
||||
model_catalog_policy: ModelCatalogPolicy::RemoteAuthoritative,
|
||||
supports_websockets: true,
|
||||
aws: None,
|
||||
}
|
||||
|
||||
@@ -1403,6 +1403,25 @@
|
||||
},
|
||||
"type": "object"
|
||||
},
|
||||
"ModelCatalogPolicy": {
|
||||
"description": "Controls how Codex obtains model metadata for a configured provider.",
|
||||
"oneOf": [
|
||||
{
|
||||
"description": "Preserve the default behavior inferred from the provider's authentication mode.",
|
||||
"enum": [
|
||||
"auto"
|
||||
],
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"description": "Treat the provider's `/models` response as the authoritative account-scoped catalog.",
|
||||
"enum": [
|
||||
"remote_authoritative"
|
||||
],
|
||||
"type": "string"
|
||||
}
|
||||
]
|
||||
},
|
||||
"ModelProviderAuthInfo": {
|
||||
"additionalProperties": false,
|
||||
"description": "Configuration for obtaining a provider bearer token from a command.",
|
||||
@@ -1512,6 +1531,14 @@
|
||||
"description": "Additional HTTP headers to include in requests to this provider where the (key, value) pairs are the header name and value.",
|
||||
"type": "object"
|
||||
},
|
||||
"model_catalog_policy": {
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/ModelCatalogPolicy"
|
||||
}
|
||||
],
|
||||
"description": "Determines whether this provider supplies authoritative model metadata remotely."
|
||||
},
|
||||
"name": {
|
||||
"default": "",
|
||||
"description": "Friendly display name.",
|
||||
|
||||
@@ -234,6 +234,7 @@ fn should_use_remote_compact_task_for_azure_provider() {
|
||||
stream_idle_timeout_ms: None,
|
||||
websocket_connect_timeout_ms: None,
|
||||
requires_openai_auth: false,
|
||||
model_catalog_policy: Default::default(),
|
||||
supports_websockets: false,
|
||||
};
|
||||
|
||||
|
||||
@@ -538,6 +538,9 @@ impl Codex {
|
||||
} else {
|
||||
codex_models_manager::manager::RefreshStrategy::OnlineIfUncached
|
||||
};
|
||||
models_manager
|
||||
.ensure_model_catalog(refresh_strategy)
|
||||
.await?;
|
||||
if config.model.is_none()
|
||||
|| !matches!(
|
||||
refresh_strategy,
|
||||
@@ -549,6 +552,7 @@ impl Codex {
|
||||
let model = models_manager
|
||||
.get_default_model(&config.model, refresh_strategy)
|
||||
.await;
|
||||
models_manager.ensure_model_available(&model).await?;
|
||||
|
||||
// Resolve base instructions for the session. Priority order:
|
||||
// 1. config.base_instructions override
|
||||
|
||||
@@ -36,6 +36,7 @@ use codex_protocol::config_types::CollaborationModeMask;
|
||||
use codex_protocol::error::CodexErr;
|
||||
use codex_protocol::error::Result as CodexResult;
|
||||
use codex_protocol::openai_models::ModelPreset;
|
||||
use codex_protocol::openai_models::ModelsResponse;
|
||||
use codex_protocol::protocol::Event;
|
||||
use codex_protocol::protocol::EventMsg;
|
||||
use codex_protocol::protocol::InitialHistory;
|
||||
@@ -202,6 +203,8 @@ pub(crate) struct ThreadManagerState {
|
||||
thread_created_tx: broadcast::Sender<ThreadId>,
|
||||
auth_manager: Arc<AuthManager>,
|
||||
models_manager: SharedModelsManager,
|
||||
models_manager_provider: ModelProviderInfo,
|
||||
models_manager_catalog: Option<ModelsResponse>,
|
||||
environment_manager: Arc<EnvironmentManager>,
|
||||
skills_manager: Arc<SkillsManager>,
|
||||
plugins_manager: Arc<PluginsManager>,
|
||||
@@ -281,6 +284,8 @@ impl ThreadManager {
|
||||
threads: Arc::new(RwLock::new(HashMap::new())),
|
||||
thread_created_tx,
|
||||
models_manager: build_models_manager(config, auth_manager.clone()),
|
||||
models_manager_provider: config.model_provider.clone(),
|
||||
models_manager_catalog: config.model_catalog.clone(),
|
||||
environment_manager,
|
||||
skills_manager,
|
||||
plugins_manager,
|
||||
@@ -376,12 +381,15 @@ impl ThreadManager {
|
||||
},
|
||||
state_db.clone(),
|
||||
));
|
||||
let models_manager_provider = provider.clone();
|
||||
Self {
|
||||
state: Arc::new(ThreadManagerState {
|
||||
threads: Arc::new(RwLock::new(HashMap::new())),
|
||||
thread_created_tx,
|
||||
models_manager: create_model_provider(provider, Some(auth_manager.clone()))
|
||||
.models_manager(codex_home, /*config_model_catalog*/ None),
|
||||
models_manager_provider,
|
||||
models_manager_catalog: None,
|
||||
environment_manager,
|
||||
skills_manager,
|
||||
plugins_manager,
|
||||
@@ -1306,13 +1314,20 @@ impl ThreadManagerState {
|
||||
forked_from_thread_id,
|
||||
)
|
||||
.await;
|
||||
let models_manager = if config.model_provider == self.models_manager_provider
|
||||
&& config.model_catalog == self.models_manager_catalog
|
||||
{
|
||||
Arc::clone(&self.models_manager)
|
||||
} else {
|
||||
build_models_manager(&config, auth_manager.clone())
|
||||
};
|
||||
let CodexSpawnOk {
|
||||
codex, thread_id, ..
|
||||
} = Box::pin(Codex::spawn(CodexSpawnArgs {
|
||||
config,
|
||||
installation_id: self.installation_id.clone(),
|
||||
auth_manager,
|
||||
models_manager: Arc::clone(&self.models_manager),
|
||||
models_manager,
|
||||
environment_manager: Arc::clone(&self.environment_manager),
|
||||
skills_manager: Arc::clone(&self.skills_manager),
|
||||
plugins_manager: Arc::clone(&self.plugins_manager),
|
||||
|
||||
@@ -9,6 +9,7 @@ use crate::tasks::InterruptedTurnHistoryMarker;
|
||||
use crate::tasks::interrupted_turn_history_marker;
|
||||
use codex_extension_api::empty_extension_registry;
|
||||
use codex_features::Feature;
|
||||
use codex_models_manager::bundled_models_response;
|
||||
use codex_models_manager::manager::RefreshStrategy;
|
||||
use codex_protocol::models::ContentItem;
|
||||
use codex_protocol::models::ReasoningItemReasoningSummary;
|
||||
@@ -972,6 +973,62 @@ async fn new_uses_active_provider_for_model_refresh() {
|
||||
assert_eq!(models_mock.requests().len(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn thread_provider_override_uses_its_own_model_manager() {
|
||||
let mut config = test_config().await;
|
||||
let mut model = bundled_models_response()
|
||||
.expect("bundled models should parse")
|
||||
.models
|
||||
.into_iter()
|
||||
.next()
|
||||
.expect("bundled catalog should contain a model");
|
||||
config.model_catalog = Some(ModelsResponse {
|
||||
models: vec![model.clone()],
|
||||
});
|
||||
let auth_manager =
|
||||
AuthManager::from_auth_for_testing(CodexAuth::create_dummy_chatgpt_auth_for_testing());
|
||||
let manager = ThreadManager::new(
|
||||
&config,
|
||||
auth_manager,
|
||||
SessionSource::Exec,
|
||||
Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()),
|
||||
empty_extension_registry(),
|
||||
/*analytics_events_client*/ None,
|
||||
thread_store_from_config(&config, /*state_db*/ None),
|
||||
/*state_db*/ None,
|
||||
TEST_INSTALLATION_ID.to_string(),
|
||||
/*attestation_provider*/ None,
|
||||
);
|
||||
|
||||
model.base_instructions = "thread provider instructions".to_string();
|
||||
let mut thread_config = config.clone();
|
||||
thread_config.model_provider.name = "thread provider".to_string();
|
||||
thread_config.model_catalog = Some(ModelsResponse {
|
||||
models: vec![model.clone()],
|
||||
});
|
||||
let thread = manager
|
||||
.start_thread(thread_config)
|
||||
.await
|
||||
.expect("thread should start");
|
||||
|
||||
assert_eq!(
|
||||
thread
|
||||
.thread
|
||||
.codex
|
||||
.session
|
||||
.services
|
||||
.models_manager
|
||||
.get_remote_models()
|
||||
.await,
|
||||
vec![model]
|
||||
);
|
||||
thread
|
||||
.thread
|
||||
.shutdown_and_wait()
|
||||
.await
|
||||
.expect("thread should shut down");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interrupted_fork_snapshot_appends_interrupt_boundary() {
|
||||
let committed_history =
|
||||
|
||||
@@ -67,6 +67,7 @@ async fn responses_stream_includes_subagent_header_on_review() {
|
||||
stream_idle_timeout_ms: Some(5_000),
|
||||
websocket_connect_timeout_ms: None,
|
||||
requires_openai_auth: false,
|
||||
model_catalog_policy: Default::default(),
|
||||
supports_websockets: false,
|
||||
};
|
||||
|
||||
@@ -195,6 +196,7 @@ async fn responses_stream_includes_subagent_header_on_other() {
|
||||
stream_idle_timeout_ms: Some(5_000),
|
||||
websocket_connect_timeout_ms: None,
|
||||
requires_openai_auth: false,
|
||||
model_catalog_policy: Default::default(),
|
||||
supports_websockets: false,
|
||||
};
|
||||
|
||||
@@ -308,6 +310,7 @@ async fn responses_respects_model_info_overrides_from_config() {
|
||||
stream_idle_timeout_ms: Some(5_000),
|
||||
websocket_connect_timeout_ms: None,
|
||||
requires_openai_auth: false,
|
||||
model_catalog_policy: Default::default(),
|
||||
supports_websockets: false,
|
||||
};
|
||||
|
||||
|
||||
@@ -869,6 +869,7 @@ async fn send_provider_auth_request(server: &MockServer, auth: ModelProviderAuth
|
||||
stream_idle_timeout_ms: Some(5_000),
|
||||
websocket_connect_timeout_ms: None,
|
||||
requires_openai_auth: false,
|
||||
model_catalog_policy: Default::default(),
|
||||
supports_websockets: false,
|
||||
};
|
||||
|
||||
@@ -2390,6 +2391,7 @@ async fn azure_responses_request_includes_store_and_reasoning_ids() {
|
||||
stream_idle_timeout_ms: Some(5_000),
|
||||
websocket_connect_timeout_ms: None,
|
||||
requires_openai_auth: false,
|
||||
model_catalog_policy: Default::default(),
|
||||
supports_websockets: false,
|
||||
};
|
||||
|
||||
@@ -3004,6 +3006,7 @@ async fn azure_overrides_assign_properties_used_for_responses_url() {
|
||||
stream_idle_timeout_ms: None,
|
||||
websocket_connect_timeout_ms: None,
|
||||
requires_openai_auth: false,
|
||||
model_catalog_policy: Default::default(),
|
||||
supports_websockets: false,
|
||||
};
|
||||
|
||||
@@ -3094,6 +3097,7 @@ async fn env_var_overrides_loaded_auth() {
|
||||
stream_idle_timeout_ms: None,
|
||||
websocket_connect_timeout_ms: None,
|
||||
requires_openai_auth: false,
|
||||
model_catalog_policy: Default::default(),
|
||||
supports_websockets: false,
|
||||
};
|
||||
|
||||
|
||||
@@ -1917,6 +1917,7 @@ fn websocket_provider_with_connect_timeout(
|
||||
stream_idle_timeout_ms: Some(5_000),
|
||||
websocket_connect_timeout_ms,
|
||||
requires_openai_auth: false,
|
||||
model_catalog_policy: Default::default(),
|
||||
supports_websockets: true,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
#![allow(clippy::expect_used)]
|
||||
use anyhow::Result;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_model_provider_info::ModelCatalogPolicy;
|
||||
use codex_model_provider_info::ModelProviderInfo;
|
||||
use codex_model_provider_info::built_in_model_providers;
|
||||
use codex_models_manager::bundled_models_response;
|
||||
@@ -758,7 +759,7 @@ async fn remote_models_apply_remote_base_instructions() -> Result<()> {
|
||||
effective_context_window_percent: 95,
|
||||
experimental_supported_tools: Vec::new(),
|
||||
};
|
||||
mount_models_once(
|
||||
let models_mock = mount_models_once(
|
||||
&server,
|
||||
ModelsResponse {
|
||||
models: vec![remote_model],
|
||||
@@ -776,30 +777,12 @@ async fn remote_models_apply_remote_base_instructions() -> Result<()> {
|
||||
)
|
||||
.await;
|
||||
|
||||
let mut builder = test_codex()
|
||||
.with_auth(CodexAuth::create_dummy_chatgpt_auth_for_testing())
|
||||
.with_config(|config| {
|
||||
config.model = Some("gpt-5.2".to_string());
|
||||
});
|
||||
let TestCodex {
|
||||
codex,
|
||||
cwd,
|
||||
config,
|
||||
thread_manager,
|
||||
..
|
||||
} = builder.build(&server).await?;
|
||||
|
||||
let models_manager = thread_manager.get_models_manager();
|
||||
wait_for_model_available(&models_manager, model).await;
|
||||
|
||||
core_test_support::submit_thread_settings(
|
||||
&codex,
|
||||
codex_protocol::protocol::ThreadSettingsOverrides {
|
||||
model: Some(model.to_string()),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
let mut builder = test_codex().with_config(|config| {
|
||||
config.model = Some(model.to_string());
|
||||
config.model_provider.requires_openai_auth = false;
|
||||
config.model_provider.model_catalog_policy = ModelCatalogPolicy::RemoteAuthoritative;
|
||||
});
|
||||
let TestCodex { codex, cwd, .. } = builder.build(&server).await?;
|
||||
|
||||
let cwd_path = cwd.path().to_path_buf();
|
||||
let (sandbox_policy, permission_profile) =
|
||||
@@ -827,12 +810,9 @@ async fn remote_models_apply_remote_base_instructions() -> Result<()> {
|
||||
|
||||
wait_for_event(&codex, |event| matches!(event, EventMsg::TurnComplete(_))).await;
|
||||
|
||||
let base_model_info = models_manager
|
||||
.get_model_info("gpt-5.2", &config.to_models_manager_config())
|
||||
.await;
|
||||
let body = response_mock.single_request().body_json();
|
||||
let instructions = body["instructions"].as_str().unwrap();
|
||||
assert_eq!(instructions, base_model_info.base_instructions);
|
||||
assert_eq!(body["instructions"].as_str(), Some(remote_base));
|
||||
assert_eq!(models_mock.requests().len(), 1);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -80,6 +80,7 @@ async fn continue_after_stream_error() {
|
||||
stream_idle_timeout_ms: Some(2_000),
|
||||
websocket_connect_timeout_ms: None,
|
||||
requires_openai_auth: false,
|
||||
model_catalog_policy: Default::default(),
|
||||
supports_websockets: false,
|
||||
};
|
||||
|
||||
|
||||
@@ -63,6 +63,7 @@ async fn retries_on_early_close() {
|
||||
stream_idle_timeout_ms: Some(2000),
|
||||
websocket_connect_timeout_ms: None,
|
||||
requires_openai_auth: false,
|
||||
model_catalog_policy: Default::default(),
|
||||
supports_websockets: false,
|
||||
};
|
||||
|
||||
|
||||
@@ -79,6 +79,24 @@ impl<'de> Deserialize<'de> for WireApi {
|
||||
}
|
||||
}
|
||||
|
||||
/// Controls how Codex obtains model metadata for a configured provider.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ModelCatalogPolicy {
|
||||
/// Preserve the default behavior inferred from the provider's authentication mode.
|
||||
#[default]
|
||||
Auto,
|
||||
/// Treat the provider's `/models` response as the authoritative account-scoped catalog.
|
||||
RemoteAuthoritative,
|
||||
}
|
||||
|
||||
impl ModelCatalogPolicy {
|
||||
#[allow(clippy::trivially_copy_pass_by_ref)]
|
||||
fn is_auto(&self) -> bool {
|
||||
matches!(self, Self::Auto)
|
||||
}
|
||||
}
|
||||
|
||||
/// Serializable representation of a provider definition.
|
||||
#[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
@@ -131,6 +149,9 @@ pub struct ModelProviderInfo {
|
||||
/// and API key (if needed) comes from the "env_key" environment variable.
|
||||
#[serde(default)]
|
||||
pub requires_openai_auth: bool,
|
||||
/// Determines whether this provider supplies authoritative model metadata remotely.
|
||||
#[serde(default, skip_serializing_if = "ModelCatalogPolicy::is_auto")]
|
||||
pub model_catalog_policy: ModelCatalogPolicy,
|
||||
/// Whether this provider supports the Responses API WebSocket transport.
|
||||
#[serde(default)]
|
||||
pub supports_websockets: bool,
|
||||
@@ -178,6 +199,15 @@ impl ModelProviderInfo {
|
||||
}
|
||||
}
|
||||
|
||||
if self.model_catalog_policy == ModelCatalogPolicy::RemoteAuthoritative
|
||||
&& self.requires_openai_auth
|
||||
{
|
||||
return Err(
|
||||
"remote_authoritative model catalogs require provider-owned authentication"
|
||||
.to_string(),
|
||||
);
|
||||
}
|
||||
|
||||
let Some(auth) = self.auth.as_ref() else {
|
||||
return Ok(());
|
||||
};
|
||||
@@ -349,6 +379,7 @@ impl ModelProviderInfo {
|
||||
stream_idle_timeout_ms: None,
|
||||
websocket_connect_timeout_ms: None,
|
||||
requires_openai_auth: true,
|
||||
model_catalog_policy: ModelCatalogPolicy::Auto,
|
||||
supports_websockets: true,
|
||||
}
|
||||
}
|
||||
@@ -379,6 +410,7 @@ impl ModelProviderInfo {
|
||||
stream_idle_timeout_ms: None,
|
||||
websocket_connect_timeout_ms: None,
|
||||
requires_openai_auth: false,
|
||||
model_catalog_policy: ModelCatalogPolicy::Auto,
|
||||
supports_websockets: false,
|
||||
}
|
||||
}
|
||||
@@ -510,6 +542,7 @@ pub fn create_oss_provider_with_base_url(base_url: &str, wire_api: WireApi) -> M
|
||||
stream_idle_timeout_ms: None,
|
||||
websocket_connect_timeout_ms: None,
|
||||
requires_openai_auth: false,
|
||||
model_catalog_policy: ModelCatalogPolicy::Auto,
|
||||
supports_websockets: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,6 +28,7 @@ base_url = "http://localhost:11434/v1"
|
||||
stream_idle_timeout_ms: None,
|
||||
websocket_connect_timeout_ms: None,
|
||||
requires_openai_auth: false,
|
||||
model_catalog_policy: ModelCatalogPolicy::Auto,
|
||||
supports_websockets: false,
|
||||
};
|
||||
|
||||
@@ -62,6 +63,7 @@ query_params = { api-version = "2025-04-01-preview" }
|
||||
stream_idle_timeout_ms: None,
|
||||
websocket_connect_timeout_ms: None,
|
||||
requires_openai_auth: false,
|
||||
model_catalog_policy: ModelCatalogPolicy::Auto,
|
||||
supports_websockets: false,
|
||||
};
|
||||
|
||||
@@ -99,6 +101,7 @@ env_http_headers = { "X-Example-Env-Header" = "EXAMPLE_ENV_VAR" }
|
||||
stream_idle_timeout_ms: None,
|
||||
websocket_connect_timeout_ms: None,
|
||||
requires_openai_auth: false,
|
||||
model_catalog_policy: ModelCatalogPolicy::Auto,
|
||||
supports_websockets: false,
|
||||
};
|
||||
|
||||
@@ -132,6 +135,38 @@ supports_websockets = true
|
||||
assert_eq!(provider.websocket_connect_timeout_ms, Some(15_000));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_deserialize_remote_authoritative_model_catalog_policy() {
|
||||
let provider_toml = r#"
|
||||
name = "Codex backend"
|
||||
base_url = "https://example.com/api/codex"
|
||||
model_catalog_policy = "remote_authoritative"
|
||||
"#;
|
||||
|
||||
let provider: ModelProviderInfo = toml::from_str(provider_toml).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
provider.model_catalog_policy,
|
||||
ModelCatalogPolicy::RemoteAuthoritative
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validate_remote_authoritative_catalog_rejects_openai_auth() {
|
||||
let provider = ModelProviderInfo {
|
||||
model_catalog_policy: ModelCatalogPolicy::RemoteAuthoritative,
|
||||
requires_openai_auth: true,
|
||||
..ModelProviderInfo::default()
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
provider.validate(),
|
||||
Err(
|
||||
"remote_authoritative model catalogs require provider-owned authentication".to_string()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_supports_remote_compaction_for_openai() {
|
||||
let provider = ModelProviderInfo::create_openai_provider(/*base_url*/ None);
|
||||
@@ -158,6 +193,7 @@ fn test_supports_remote_compaction_for_azure_name() {
|
||||
stream_idle_timeout_ms: None,
|
||||
websocket_connect_timeout_ms: None,
|
||||
requires_openai_auth: false,
|
||||
model_catalog_policy: ModelCatalogPolicy::Auto,
|
||||
supports_websockets: false,
|
||||
};
|
||||
|
||||
@@ -183,6 +219,7 @@ fn test_supports_remote_compaction_for_non_openai_non_azure_provider() {
|
||||
stream_idle_timeout_ms: None,
|
||||
websocket_connect_timeout_ms: None,
|
||||
requires_openai_auth: false,
|
||||
model_catalog_policy: ModelCatalogPolicy::Auto,
|
||||
supports_websockets: false,
|
||||
};
|
||||
|
||||
@@ -266,6 +303,7 @@ fn test_create_amazon_bedrock_provider() {
|
||||
stream_idle_timeout_ms: None,
|
||||
websocket_connect_timeout_ms: None,
|
||||
requires_openai_auth: false,
|
||||
model_catalog_policy: ModelCatalogPolicy::Auto,
|
||||
supports_websockets: false,
|
||||
}
|
||||
);
|
||||
|
||||
@@ -7,6 +7,7 @@ use codex_api::AuthProvider;
|
||||
use codex_api::SharedAuthProvider;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_model_provider_info::ModelCatalogPolicy;
|
||||
use codex_model_provider_info::ModelProviderInfo;
|
||||
use http::HeaderMap;
|
||||
use http::HeaderValue;
|
||||
@@ -62,15 +63,17 @@ pub fn unauthenticated_auth_provider() -> SharedAuthProvider {
|
||||
Arc::new(UnauthenticatedAuthProvider)
|
||||
}
|
||||
|
||||
/// Returns the provider-scoped auth manager when this provider uses command-backed auth.
|
||||
/// Returns the auth manager that this provider may use.
|
||||
///
|
||||
/// Providers without custom auth continue using the caller-supplied base manager, when present.
|
||||
/// Command-backed providers get an isolated manager. Authoritative remote catalogs never inherit
|
||||
/// OpenAI-owned credentials. Other providers continue using the caller-supplied manager.
|
||||
pub(crate) fn auth_manager_for_provider(
|
||||
auth_manager: Option<Arc<AuthManager>>,
|
||||
provider: &ModelProviderInfo,
|
||||
) -> Option<Arc<AuthManager>> {
|
||||
match provider.auth.clone() {
|
||||
Some(config) => Some(AuthManager::external_bearer_only(config)),
|
||||
None if provider.model_catalog_policy == ModelCatalogPolicy::RemoteAuthoritative => None,
|
||||
None => auth_manager,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ use codex_login::AuthManager;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_login::collect_auth_env_telemetry;
|
||||
use codex_login::default_client::build_reqwest_client;
|
||||
use codex_model_provider_info::ModelCatalogPolicy;
|
||||
use codex_model_provider_info::ModelProviderInfo;
|
||||
use codex_models_manager::manager::ModelsEndpointClient;
|
||||
use codex_otel::TelemetryAuthMode;
|
||||
@@ -67,6 +68,10 @@ impl OpenAiModelsEndpoint {
|
||||
|
||||
#[async_trait]
|
||||
impl ModelsEndpointClient for OpenAiModelsEndpoint {
|
||||
fn model_catalog_policy(&self) -> ModelCatalogPolicy {
|
||||
self.provider_info.model_catalog_policy
|
||||
}
|
||||
|
||||
fn has_command_auth(&self) -> bool {
|
||||
self.provider_info.has_command_auth()
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ use codex_api::Provider;
|
||||
use codex_api::SharedAuthProvider;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_model_provider_info::ModelCatalogPolicy;
|
||||
use codex_model_provider_info::ModelProviderInfo;
|
||||
use codex_models_manager::manager::OpenAiModelsManager;
|
||||
use codex_models_manager::manager::SharedModelsManager;
|
||||
@@ -240,22 +241,23 @@ impl ModelProvider for ConfiguredModelProvider {
|
||||
codex_home: PathBuf,
|
||||
config_model_catalog: Option<ModelsResponse>,
|
||||
) -> SharedModelsManager {
|
||||
match config_model_catalog {
|
||||
Some(model_catalog) => Arc::new(StaticModelsManager::new(
|
||||
if let Some(model_catalog) = config_model_catalog
|
||||
&& self.info.model_catalog_policy != ModelCatalogPolicy::RemoteAuthoritative
|
||||
{
|
||||
Arc::new(StaticModelsManager::new(
|
||||
self.auth_manager.clone(),
|
||||
model_catalog,
|
||||
)),
|
||||
None => {
|
||||
let endpoint = Arc::new(OpenAiModelsEndpoint::new(
|
||||
self.info.clone(),
|
||||
self.auth_manager.clone(),
|
||||
));
|
||||
Arc::new(OpenAiModelsManager::new(
|
||||
codex_home,
|
||||
endpoint,
|
||||
self.auth_manager.clone(),
|
||||
))
|
||||
}
|
||||
))
|
||||
} else {
|
||||
let endpoint = Arc::new(OpenAiModelsEndpoint::new(
|
||||
self.info.clone(),
|
||||
self.auth_manager.clone(),
|
||||
));
|
||||
Arc::new(OpenAiModelsManager::new(
|
||||
codex_home,
|
||||
endpoint,
|
||||
self.auth_manager.clone(),
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -320,6 +322,7 @@ mod tests {
|
||||
stream_idle_timeout_ms: Some(5_000),
|
||||
websocket_connect_timeout_ms: None,
|
||||
requires_openai_auth: false,
|
||||
model_catalog_policy: ModelCatalogPolicy::Auto,
|
||||
supports_websockets: false,
|
||||
}
|
||||
}
|
||||
@@ -419,6 +422,20 @@ mod tests {
|
||||
assert!(provider.auth_manager().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remote_authoritative_provider_does_not_inherit_openai_auth_manager() {
|
||||
let mut provider_info = provider_for("https://example.test/v1".to_string());
|
||||
provider_info.model_catalog_policy = ModelCatalogPolicy::RemoteAuthoritative;
|
||||
let provider = create_model_provider(
|
||||
provider_info,
|
||||
Some(AuthManager::from_auth_for_testing(
|
||||
CodexAuth::create_dummy_chatgpt_auth_for_testing(),
|
||||
)),
|
||||
);
|
||||
|
||||
assert!(provider.auth_manager().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn openai_provider_returns_unauthenticated_openai_account_state() {
|
||||
let provider = create_model_provider(
|
||||
|
||||
@@ -18,6 +18,7 @@ chrono = { workspace = true, features = ["serde"] }
|
||||
codex-app-server-protocol = { workspace = true }
|
||||
codex-collaboration-mode-templates = { workspace = true }
|
||||
codex-login = { workspace = true }
|
||||
codex-model-provider-info = { workspace = true }
|
||||
codex-otel = { workspace = true }
|
||||
codex-protocol = { workspace = true }
|
||||
codex-utils-output-truncation = { workspace = true }
|
||||
|
||||
@@ -5,7 +5,9 @@ use crate::model_info;
|
||||
use async_trait::async_trait;
|
||||
use codex_app_server_protocol::AuthMode;
|
||||
use codex_login::AuthManager;
|
||||
use codex_model_provider_info::ModelCatalogPolicy;
|
||||
use codex_protocol::config_types::CollaborationModeMask;
|
||||
use codex_protocol::error::CodexErr;
|
||||
use codex_protocol::error::Result as CoreResult;
|
||||
use codex_protocol::openai_models::ModelInfo;
|
||||
use codex_protocol::openai_models::ModelPreset;
|
||||
@@ -14,8 +16,11 @@ use codex_protocol::openai_models::ModelsResponse;
|
||||
use std::fmt;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicU64;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::Duration;
|
||||
use tokio::sync::RwLock;
|
||||
use tokio::sync::Semaphore;
|
||||
use tokio::sync::TryLockError;
|
||||
use tracing::Instrument as _;
|
||||
use tracing::error;
|
||||
@@ -31,6 +36,11 @@ const DEFAULT_MODEL_CACHE_TTL: Duration = Duration::from_secs(300);
|
||||
/// this endpoint only when it decides a remote refresh should happen.
|
||||
#[async_trait]
|
||||
pub trait ModelsEndpointClient: fmt::Debug + Send + Sync {
|
||||
/// Returns the provider's explicit policy for remote model metadata.
|
||||
fn model_catalog_policy(&self) -> ModelCatalogPolicy {
|
||||
ModelCatalogPolicy::Auto
|
||||
}
|
||||
|
||||
/// Returns whether this provider can authenticate command-scoped requests.
|
||||
fn has_command_auth(&self) -> bool;
|
||||
|
||||
@@ -76,6 +86,16 @@ type SharedModelsEndpointClient = Arc<dyn ModelsEndpointClient>;
|
||||
/// Coordinates model discovery plus cached metadata on disk.
|
||||
#[async_trait]
|
||||
pub trait ModelsManager: fmt::Debug + Send + Sync {
|
||||
/// Ensure required provider-owned model metadata is available before a session starts.
|
||||
async fn ensure_model_catalog(&self, _refresh_strategy: RefreshStrategy) -> CoreResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Ensure the selected model exists when the provider owns the complete catalog.
|
||||
async fn ensure_model_available(&self, _model: &str) -> CoreResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// List all available models, refreshing according to the specified strategy.
|
||||
///
|
||||
/// Returns model presets sorted by priority and filtered by auth mode and visibility.
|
||||
@@ -105,6 +125,11 @@ pub trait ModelsManager: fmt::Debug + Send + Sync {
|
||||
/// Return the auth manager used for picker filtering.
|
||||
fn auth_manager(&self) -> Option<&AuthManager>;
|
||||
|
||||
/// Returns whether the active catalog is already filtered for the current account.
|
||||
fn catalog_is_account_scoped(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// Build picker-ready presets from the active catalog snapshot.
|
||||
fn build_available_models(&self, mut remote_models: Vec<ModelInfo>) -> Vec<ModelPreset> {
|
||||
remote_models.sort_by_key(|model| model.priority);
|
||||
@@ -112,7 +137,8 @@ pub trait ModelsManager: fmt::Debug + Send + Sync {
|
||||
let mut presets: Vec<ModelPreset> = remote_models.into_iter().map(Into::into).collect();
|
||||
let uses_codex_backend = self
|
||||
.auth_manager()
|
||||
.is_some_and(AuthManager::current_auth_uses_codex_backend);
|
||||
.is_some_and(AuthManager::current_auth_uses_codex_backend)
|
||||
|| self.catalog_is_account_scoped();
|
||||
presets = ModelPreset::filter_by_auth(presets, uses_codex_backend);
|
||||
|
||||
ModelPreset::mark_default_by_picker_visibility(&mut presets);
|
||||
@@ -185,6 +211,9 @@ pub struct OpenAiModelsManager {
|
||||
cache_manager: ModelsCacheManager,
|
||||
endpoint_client: SharedModelsEndpointClient,
|
||||
auth_manager: Option<Arc<AuthManager>>,
|
||||
authoritative_catalog_generation: AtomicU64,
|
||||
authoritative_refreshes_completed: AtomicU64,
|
||||
authoritative_catalog_refresh: Semaphore,
|
||||
}
|
||||
|
||||
/// Static model manager backed by an authoritative in-process catalog.
|
||||
@@ -210,6 +239,9 @@ impl OpenAiModelsManager {
|
||||
cache_manager,
|
||||
endpoint_client,
|
||||
auth_manager,
|
||||
authoritative_catalog_generation: AtomicU64::new(0),
|
||||
authoritative_refreshes_completed: AtomicU64::new(0),
|
||||
authoritative_catalog_refresh: Semaphore::new(1),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -226,10 +258,51 @@ impl StaticModelsManager {
|
||||
|
||||
#[async_trait]
|
||||
impl ModelsManager for OpenAiModelsManager {
|
||||
async fn ensure_model_catalog(&self, refresh_strategy: RefreshStrategy) -> CoreResult<()> {
|
||||
if !self.catalog_is_account_scoped() {
|
||||
return Ok(());
|
||||
}
|
||||
match refresh_strategy {
|
||||
RefreshStrategy::Online | RefreshStrategy::OnlineIfUncached => {
|
||||
self.refresh_authoritative_catalog().await
|
||||
}
|
||||
RefreshStrategy::Offline if self.authoritative_catalog_is_loaded() => Ok(()),
|
||||
RefreshStrategy::Offline => Err(CodexErr::Fatal(
|
||||
"authoritative model catalog is unavailable offline".to_string(),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
async fn ensure_model_available(&self, model: &str) -> CoreResult<()> {
|
||||
if !self.catalog_is_account_scoped() {
|
||||
return Ok(());
|
||||
}
|
||||
let models = self.remote_models.read().await;
|
||||
let namespaced_suffix = model.split_once('/').and_then(|(namespace, suffix)| {
|
||||
(!suffix.contains('/')
|
||||
&& !namespace.is_empty()
|
||||
&& namespace
|
||||
.chars()
|
||||
.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-'))
|
||||
.then_some(suffix)
|
||||
});
|
||||
if models.iter().any(|candidate| {
|
||||
candidate.slug == model || namespaced_suffix == Some(candidate.slug.as_str())
|
||||
}) {
|
||||
return Ok(());
|
||||
}
|
||||
Err(CodexErr::InvalidRequest(format!(
|
||||
"model `{model}` is not available in the provider's authoritative catalog"
|
||||
)))
|
||||
}
|
||||
|
||||
async fn raw_model_catalog(&self, refresh_strategy: RefreshStrategy) -> ModelsResponse {
|
||||
if let Err(err) = self.refresh_available_models(refresh_strategy).await {
|
||||
error!("failed to refresh available models: {err}");
|
||||
}
|
||||
if self.catalog_is_account_scoped() && !self.authoritative_catalog_is_loaded() {
|
||||
return ModelsResponse { models: Vec::new() };
|
||||
}
|
||||
ModelsResponse {
|
||||
models: self.get_remote_models().await,
|
||||
}
|
||||
@@ -247,11 +320,21 @@ impl ModelsManager for OpenAiModelsManager {
|
||||
self.auth_manager.as_deref()
|
||||
}
|
||||
|
||||
fn catalog_is_account_scoped(&self) -> bool {
|
||||
self.endpoint_client.model_catalog_policy() == ModelCatalogPolicy::RemoteAuthoritative
|
||||
}
|
||||
|
||||
fn list_collaboration_modes(&self) -> Vec<CollaborationModeMask> {
|
||||
builtin_collaboration_mode_presets()
|
||||
}
|
||||
|
||||
async fn refresh_if_new_etag(&self, etag: String) {
|
||||
if self.catalog_is_account_scoped() {
|
||||
if let Err(err) = self.refresh_authoritative_catalog_for_etag(&etag).await {
|
||||
error!("failed to refresh available models: {err}");
|
||||
}
|
||||
return;
|
||||
}
|
||||
let current_etag = self.get_etag().await;
|
||||
if current_etag.clone().is_some() && current_etag.as_deref() == Some(etag.as_str()) {
|
||||
if let Err(err) = self.cache_manager.renew_cache_ttl().await {
|
||||
@@ -268,6 +351,19 @@ impl ModelsManager for OpenAiModelsManager {
|
||||
impl OpenAiModelsManager {
|
||||
/// Refresh available models according to the specified strategy.
|
||||
async fn refresh_available_models(&self, refresh_strategy: RefreshStrategy) -> CoreResult<()> {
|
||||
if self.catalog_is_account_scoped() {
|
||||
return match refresh_strategy {
|
||||
RefreshStrategy::Online => self.refresh_authoritative_catalog().await,
|
||||
RefreshStrategy::Offline if self.authoritative_catalog_is_loaded() => Ok(()),
|
||||
RefreshStrategy::Offline => Err(CodexErr::Fatal(
|
||||
"authoritative model catalog is unavailable offline".to_string(),
|
||||
)),
|
||||
RefreshStrategy::OnlineIfUncached if self.authoritative_catalog_is_loaded() => {
|
||||
Ok(())
|
||||
}
|
||||
RefreshStrategy::OnlineIfUncached => self.refresh_authoritative_catalog().await,
|
||||
};
|
||||
}
|
||||
if !self.should_refresh_models().await {
|
||||
if matches!(
|
||||
refresh_strategy,
|
||||
@@ -303,11 +399,44 @@ impl OpenAiModelsManager {
|
||||
async fn fetch_and_update_models(&self) -> CoreResult<()> {
|
||||
let client_version = crate::client_version_to_whole();
|
||||
let (models, etag) = self.endpoint_client.list_models(&client_version).await?;
|
||||
self.apply_fetched_models(models, etag, client_version)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn fetch_and_update_models_for_etag(&self, expected_etag: &str) -> CoreResult<()> {
|
||||
let client_version = crate::client_version_to_whole();
|
||||
let (models, etag) = self.endpoint_client.list_models(&client_version).await?;
|
||||
if etag.as_deref() != Some(expected_etag) {
|
||||
return Err(CodexErr::Fatal(format!(
|
||||
"authoritative model catalog returned ETag {etag:?}; expected {expected_etag}"
|
||||
)));
|
||||
}
|
||||
self.apply_fetched_models(models, etag, client_version)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn apply_fetched_models(
|
||||
&self,
|
||||
models: Vec<ModelInfo>,
|
||||
etag: Option<String>,
|
||||
client_version: String,
|
||||
) -> CoreResult<()> {
|
||||
let authoritative = self.catalog_is_account_scoped();
|
||||
if authoritative && models.is_empty() {
|
||||
return Err(CodexErr::Fatal(
|
||||
"authoritative model catalog is empty".to_string(),
|
||||
));
|
||||
}
|
||||
self.apply_remote_models(models.clone()).await;
|
||||
*self.etag.write().await = etag.clone();
|
||||
self.cache_manager
|
||||
.persist_cache(&models, etag, client_version)
|
||||
.await;
|
||||
if authoritative {
|
||||
self.authoritative_catalog_generation
|
||||
.fetch_add(1, Ordering::AcqRel);
|
||||
} else {
|
||||
self.cache_manager
|
||||
.persist_cache(&models, etag, client_version)
|
||||
.await;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -319,20 +448,77 @@ impl OpenAiModelsManager {
|
||||
self.etag.read().await.clone()
|
||||
}
|
||||
|
||||
fn authoritative_catalog_is_loaded(&self) -> bool {
|
||||
self.authoritative_catalog_generation
|
||||
.load(Ordering::Acquire)
|
||||
> 0
|
||||
}
|
||||
|
||||
async fn refresh_authoritative_catalog(&self) -> CoreResult<()> {
|
||||
let observed_generation = self
|
||||
.authoritative_catalog_generation
|
||||
.load(Ordering::Acquire);
|
||||
let observed_refreshes = self
|
||||
.authoritative_refreshes_completed
|
||||
.load(Ordering::Acquire);
|
||||
let _refresh_permit = self
|
||||
.authoritative_catalog_refresh
|
||||
.acquire()
|
||||
.await
|
||||
.map_err(|_| CodexErr::Fatal("model catalog refresh coordinator closed".to_string()))?;
|
||||
if self
|
||||
.authoritative_refreshes_completed
|
||||
.load(Ordering::Acquire)
|
||||
!= observed_refreshes
|
||||
{
|
||||
return if self
|
||||
.authoritative_catalog_generation
|
||||
.load(Ordering::Acquire)
|
||||
!= observed_generation
|
||||
{
|
||||
Ok(())
|
||||
} else {
|
||||
Err(CodexErr::Fatal(
|
||||
"concurrent authoritative model catalog refresh failed".to_string(),
|
||||
))
|
||||
};
|
||||
}
|
||||
let result = self.fetch_and_update_models().await;
|
||||
self.authoritative_refreshes_completed
|
||||
.fetch_add(1, Ordering::AcqRel);
|
||||
result
|
||||
}
|
||||
|
||||
async fn refresh_authoritative_catalog_for_etag(&self, expected_etag: &str) -> CoreResult<()> {
|
||||
let _refresh_permit = self
|
||||
.authoritative_catalog_refresh
|
||||
.acquire()
|
||||
.await
|
||||
.map_err(|_| CodexErr::Fatal("model catalog refresh coordinator closed".to_string()))?;
|
||||
if self.get_etag().await.as_deref() == Some(expected_etag) {
|
||||
return Ok(());
|
||||
}
|
||||
let result = self.fetch_and_update_models_for_etag(expected_etag).await;
|
||||
self.authoritative_refreshes_completed
|
||||
.fetch_add(1, Ordering::AcqRel);
|
||||
result
|
||||
}
|
||||
|
||||
/// Replace the cached remote models and rebuild the derived presets list.
|
||||
async fn apply_remote_models(&self, models: Vec<ModelInfo>) {
|
||||
// Use the remote models list as the source of truth if it contains at least one
|
||||
// non-hidden model and the user is using ChatGPT auth.
|
||||
let should_use_remote_models_only = !models.is_empty()
|
||||
&& models
|
||||
.iter()
|
||||
.any(|model| model.visibility == ModelVisibility::List)
|
||||
&& self.auth_manager.as_ref().is_some_and(|auth_manager| {
|
||||
matches!(
|
||||
auth_manager.auth_mode(),
|
||||
Some(AuthMode::Chatgpt | AuthMode::ChatgptAuthTokens)
|
||||
)
|
||||
});
|
||||
// Authoritative providers replace bundled models; preserve automatic ChatGPT behavior.
|
||||
let should_use_remote_models_only = self.endpoint_client.model_catalog_policy()
|
||||
== ModelCatalogPolicy::RemoteAuthoritative
|
||||
|| (!models.is_empty()
|
||||
&& models
|
||||
.iter()
|
||||
.any(|model| model.visibility == ModelVisibility::List)
|
||||
&& self.auth_manager.as_ref().is_some_and(|auth_manager| {
|
||||
matches!(
|
||||
auth_manager.auth_mode(),
|
||||
Some(AuthMode::Chatgpt | AuthMode::ChatgptAuthTokens)
|
||||
)
|
||||
}));
|
||||
if should_use_remote_models_only {
|
||||
*self.remote_models.write().await = models;
|
||||
return;
|
||||
|
||||
@@ -74,6 +74,7 @@ fn assert_models_contain(actual: &[ModelInfo], expected: &[ModelInfo]) {
|
||||
struct TestModelsEndpoint {
|
||||
has_command_auth: bool,
|
||||
uses_codex_backend: bool,
|
||||
model_catalog_policy: ModelCatalogPolicy,
|
||||
responses: Mutex<VecDeque<Vec<ModelInfo>>>,
|
||||
fetch_count: AtomicUsize,
|
||||
}
|
||||
@@ -83,6 +84,7 @@ impl TestModelsEndpoint {
|
||||
Arc::new(Self {
|
||||
has_command_auth: false,
|
||||
uses_codex_backend: true,
|
||||
model_catalog_policy: ModelCatalogPolicy::Auto,
|
||||
responses: Mutex::new(responses.into()),
|
||||
fetch_count: AtomicUsize::new(0),
|
||||
})
|
||||
@@ -92,6 +94,7 @@ impl TestModelsEndpoint {
|
||||
Arc::new(Self {
|
||||
has_command_auth: false,
|
||||
uses_codex_backend: false,
|
||||
model_catalog_policy: ModelCatalogPolicy::Auto,
|
||||
responses: Mutex::new(responses.into()),
|
||||
fetch_count: AtomicUsize::new(0),
|
||||
})
|
||||
@@ -146,6 +149,10 @@ impl ExternalAuth for TestUnresolvedExternalApiKeyAuth {
|
||||
|
||||
#[async_trait]
|
||||
impl ModelsEndpointClient for TestModelsEndpoint {
|
||||
fn model_catalog_policy(&self) -> ModelCatalogPolicy {
|
||||
self.model_catalog_policy
|
||||
}
|
||||
|
||||
fn has_command_auth(&self) -> bool {
|
||||
self.has_command_auth
|
||||
}
|
||||
@@ -169,6 +176,69 @@ impl ModelsEndpointClient for TestModelsEndpoint {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct FailingAuthoritativeModelsEndpoint;
|
||||
|
||||
#[async_trait]
|
||||
impl ModelsEndpointClient for FailingAuthoritativeModelsEndpoint {
|
||||
fn model_catalog_policy(&self) -> ModelCatalogPolicy {
|
||||
ModelCatalogPolicy::RemoteAuthoritative
|
||||
}
|
||||
|
||||
fn has_command_auth(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
async fn uses_codex_backend(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
async fn list_models(
|
||||
&self,
|
||||
_client_version: &str,
|
||||
) -> CoreResult<(Vec<ModelInfo>, Option<String>)> {
|
||||
Err(codex_protocol::error::CodexErr::Fatal(
|
||||
"catalog unavailable".to_string(),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct YieldingAuthoritativeModelsEndpoint {
|
||||
fetch_count: AtomicUsize,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl ModelsEndpointClient for YieldingAuthoritativeModelsEndpoint {
|
||||
fn model_catalog_policy(&self) -> ModelCatalogPolicy {
|
||||
ModelCatalogPolicy::RemoteAuthoritative
|
||||
}
|
||||
|
||||
fn has_command_auth(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
async fn uses_codex_backend(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
async fn list_models(
|
||||
&self,
|
||||
_client_version: &str,
|
||||
) -> CoreResult<(Vec<ModelInfo>, Option<String>)> {
|
||||
self.fetch_count.fetch_add(1, Ordering::SeqCst);
|
||||
tokio::task::yield_now().await;
|
||||
Ok((
|
||||
vec![remote_model(
|
||||
"account-model",
|
||||
"Account Model",
|
||||
/*priority*/ 0,
|
||||
)],
|
||||
None,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
fn openai_manager_for_tests(
|
||||
codex_home: std::path::PathBuf,
|
||||
endpoint_client: Arc<dyn ModelsEndpointClient>,
|
||||
@@ -498,6 +568,7 @@ async fn refresh_available_models_keeps_merging_for_api_auth() {
|
||||
let endpoint = Arc::new(TestModelsEndpoint {
|
||||
has_command_auth: true,
|
||||
uses_codex_backend: false,
|
||||
model_catalog_policy: ModelCatalogPolicy::Auto,
|
||||
responses: Mutex::new(vec![remote_models.clone()].into()),
|
||||
fetch_count: AtomicUsize::new(0),
|
||||
});
|
||||
@@ -520,6 +591,165 @@ async fn refresh_available_models_keeps_merging_for_api_auth() {
|
||||
assert_eq!(endpoint.fetch_count(), 1, "expected a single model fetch");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn authoritative_remote_catalog_refreshes_without_auth_and_replaces_bundled_models() {
|
||||
let mut remote = remote_model("account-model", "Account Model", /*priority*/ 0);
|
||||
remote.supported_in_api = false;
|
||||
remote.base_instructions = "live account instructions".to_string();
|
||||
let codex_home = tempdir().expect("temp dir");
|
||||
let endpoint = Arc::new(TestModelsEndpoint {
|
||||
has_command_auth: false,
|
||||
uses_codex_backend: false,
|
||||
model_catalog_policy: ModelCatalogPolicy::RemoteAuthoritative,
|
||||
responses: Mutex::new(vec![vec![remote.clone()]].into()),
|
||||
fetch_count: AtomicUsize::new(0),
|
||||
});
|
||||
let manager = openai_manager_for_tests_with_auth(
|
||||
codex_home.path().to_path_buf(),
|
||||
endpoint.clone(),
|
||||
/*auth_manager*/ None,
|
||||
);
|
||||
|
||||
manager
|
||||
.refresh_available_models(RefreshStrategy::OnlineIfUncached)
|
||||
.await
|
||||
.expect("refresh succeeds");
|
||||
|
||||
assert_eq!(manager.get_remote_models().await, vec![remote.clone()]);
|
||||
let mut expected_preset: ModelPreset = remote.into();
|
||||
expected_preset.is_default = true;
|
||||
assert_eq!(
|
||||
manager.list_models(RefreshStrategy::Offline).await,
|
||||
vec![expected_preset]
|
||||
);
|
||||
assert_eq!(endpoint.fetch_count(), 1, "expected a single model fetch");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn authoritative_remote_catalog_propagates_refresh_failure() {
|
||||
let codex_home = tempdir().expect("temp dir");
|
||||
let manager = openai_manager_for_tests_with_auth(
|
||||
codex_home.path().to_path_buf(),
|
||||
Arc::new(FailingAuthoritativeModelsEndpoint),
|
||||
/*auth_manager*/ None,
|
||||
);
|
||||
|
||||
let err = manager
|
||||
.ensure_model_catalog(RefreshStrategy::OnlineIfUncached)
|
||||
.await
|
||||
.expect_err("authoritative refresh should fail closed");
|
||||
|
||||
assert_eq!(err.to_string(), "Fatal error: catalog unavailable");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn authoritative_remote_catalog_refreshes_each_root_session() {
|
||||
let first = remote_model("first", "First", /*priority*/ 0);
|
||||
let second = remote_model("second", "Second", /*priority*/ 0);
|
||||
let codex_home = tempdir().expect("temp dir");
|
||||
let endpoint = Arc::new(TestModelsEndpoint {
|
||||
has_command_auth: false,
|
||||
uses_codex_backend: false,
|
||||
model_catalog_policy: ModelCatalogPolicy::RemoteAuthoritative,
|
||||
responses: Mutex::new(vec![vec![first], vec![second.clone()]].into()),
|
||||
fetch_count: AtomicUsize::new(0),
|
||||
});
|
||||
let manager = openai_manager_for_tests_with_auth(
|
||||
codex_home.path().to_path_buf(),
|
||||
endpoint.clone(),
|
||||
/*auth_manager*/ None,
|
||||
);
|
||||
|
||||
manager
|
||||
.ensure_model_catalog(RefreshStrategy::OnlineIfUncached)
|
||||
.await
|
||||
.expect("first startup refresh succeeds");
|
||||
manager
|
||||
.ensure_model_catalog(RefreshStrategy::OnlineIfUncached)
|
||||
.await
|
||||
.expect("second startup refresh succeeds");
|
||||
|
||||
assert_eq!(manager.get_remote_models().await, vec![second]);
|
||||
assert_eq!(endpoint.fetch_count(), 2);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn concurrent_authoritative_refreshes_share_one_request() {
|
||||
let codex_home = tempdir().expect("temp dir");
|
||||
let endpoint = Arc::new(YieldingAuthoritativeModelsEndpoint {
|
||||
fetch_count: AtomicUsize::new(0),
|
||||
});
|
||||
let manager = openai_manager_for_tests_with_auth(
|
||||
codex_home.path().to_path_buf(),
|
||||
endpoint.clone(),
|
||||
/*auth_manager*/ None,
|
||||
);
|
||||
|
||||
let (first, second) = tokio::join!(
|
||||
manager.ensure_model_catalog(RefreshStrategy::OnlineIfUncached),
|
||||
manager.ensure_model_catalog(RefreshStrategy::OnlineIfUncached),
|
||||
);
|
||||
|
||||
first.expect("first refresh succeeds");
|
||||
second.expect("concurrent refresh succeeds");
|
||||
assert_eq!(endpoint.fetch_count.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn authoritative_remote_catalog_rejects_unavailable_catalog_or_model() {
|
||||
let codex_home = tempdir().expect("temp dir");
|
||||
let catalog_model = remote_model("gpt-5", "GPT-5", /*priority*/ 0);
|
||||
let endpoint = Arc::new(TestModelsEndpoint {
|
||||
has_command_auth: false,
|
||||
uses_codex_backend: false,
|
||||
model_catalog_policy: ModelCatalogPolicy::RemoteAuthoritative,
|
||||
responses: Mutex::new(vec![Vec::new(), vec![catalog_model]].into()),
|
||||
fetch_count: AtomicUsize::new(0),
|
||||
});
|
||||
let manager = openai_manager_for_tests_with_auth(
|
||||
codex_home.path().to_path_buf(),
|
||||
endpoint,
|
||||
/*auth_manager*/ None,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
manager
|
||||
.ensure_model_catalog(RefreshStrategy::Offline)
|
||||
.await
|
||||
.expect_err("offline startup requires an in-memory catalog")
|
||||
.to_string(),
|
||||
"Fatal error: authoritative model catalog is unavailable offline"
|
||||
);
|
||||
assert_eq!(
|
||||
manager.raw_model_catalog(RefreshStrategy::Offline).await,
|
||||
ModelsResponse { models: Vec::new() }
|
||||
);
|
||||
assert_eq!(
|
||||
manager
|
||||
.ensure_model_catalog(RefreshStrategy::OnlineIfUncached)
|
||||
.await
|
||||
.expect_err("empty authoritative catalog is invalid")
|
||||
.to_string(),
|
||||
"Fatal error: authoritative model catalog is empty"
|
||||
);
|
||||
manager
|
||||
.ensure_model_catalog(RefreshStrategy::OnlineIfUncached)
|
||||
.await
|
||||
.expect("non-empty authoritative catalog is valid");
|
||||
manager
|
||||
.ensure_model_available("gpt-5")
|
||||
.await
|
||||
.expect("exact model match is valid");
|
||||
assert_eq!(
|
||||
manager
|
||||
.ensure_model_available("gpt-5.5")
|
||||
.await
|
||||
.expect_err("prefix match must not authorize an absent model")
|
||||
.to_string(),
|
||||
"model `gpt-5.5` is not available in the provider's authoritative catalog"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn refresh_available_models_uses_cache_when_fresh() {
|
||||
let remote_models = vec![remote_model("cached", "Cached", /*priority*/ 5)];
|
||||
|
||||
Reference in New Issue
Block a user