Base: codex-main originale (prima del fork aKode)

This commit is contained in:
Andrea
2026-11-09 10:37:42 +01:00
commit 7874033c81
10166 changed files with 2728937 additions and 0 deletions

View File

@@ -0,0 +1,116 @@
//! API-key discovery opt-outs must gate network requests and cached catalog authority.
use super::*;
use codex_protocol::openai_models::ModelOrigin;
use pretty_assertions::assert_eq;
#[tokio::test]
async fn api_key_discovery_disabled_preserves_command_auth_discovery_and_merging() {
let models = vec![remote_model(
"command-auth",
"Command Auth",
/*priority*/ 0,
)];
let endpoint = Arc::new(TestModelsEndpoint {
has_command_auth: true,
responses: Mutex::new(vec![Ok(models.clone())].into()),
..TestModelsEndpoint::default()
});
let manager = OpenAiModelsManager::new_without_cache(
endpoint.clone(),
Some(AuthManager::from_auth_for_testing(CodexAuth::from_api_key(
"test-key",
))),
);
let mut merged = load_remote_models_from_file().unwrap();
merged.extend(models.clone());
assert_eq!(
manager
.raw_model_catalog(RefreshStrategy::Online, DEFAULT_HTTP_CLIENT_FACTORY)
.await
.models,
merged
);
assert_eq!(endpoint.fetch_count(), 1);
}
#[tokio::test]
async fn api_key_discovery_flag_controls_fetches_and_cached_catalogs() {
let home = tempdir().unwrap();
let models = vec![remote_model("dynamic", "Dynamic", /*priority*/ 0)];
let endpoint = TestModelsEndpoint::without_refresh(vec![models.clone()]);
let auth = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("test-key"));
let manager =
OpenAiModelsManager::new(home.path().into(), endpoint.clone(), Some(auth.clone()));
let bundled = load_remote_models_from_file().unwrap();
let config = ModelsManagerConfig::default();
for strategy in [
RefreshStrategy::Online,
RefreshStrategy::OnlineIfUncached,
RefreshStrategy::Offline,
] {
assert_eq!(
manager
.raw_model_catalog(strategy, DEFAULT_HTTP_CLIENT_FACTORY)
.await
.models,
bundled
);
}
assert_eq!(endpoint.fetch_count(), 0);
let manager =
OpenAiModelsManager::new(home.path().into(), endpoint.clone(), Some(auth.clone()));
manager.set_api_key_model_discovery_enabled(/*enabled*/ true);
assert_eq!(
manager
.raw_model_catalog(RefreshStrategy::Online, DEFAULT_HTTP_CLIENT_FACTORY)
.await
.models,
models
);
assert_eq!(endpoint.fetch_count(), 1);
assert_eq!(
manager.get_model_info("dynamic", &config).await,
CatalogModel {
model: models[0].clone().into(),
origin: ModelOrigin::Provider
}
);
// A runtime rollback must also suppress the already-loaded catalog.
manager.set_api_key_model_discovery_enabled(/*enabled*/ false);
assert_eq!(
manager
.raw_model_catalog(RefreshStrategy::Online, DEFAULT_HTTP_CLIENT_FACTORY)
.await
.models,
bundled
);
assert_eq!(manager.try_get_remote_models().unwrap(), bundled);
assert_eq!(
manager.get_model_info("dynamic", &config).await.origin,
ModelOrigin::Synthetic
);
assert_eq!(endpoint.fetch_count(), 1);
// A new session must honor its startup flag even when a matching disk cache exists.
for enabled in [false, true] {
let restarted =
OpenAiModelsManager::new(home.path().into(), endpoint.clone(), Some(auth.clone()));
restarted.set_api_key_model_discovery_enabled(enabled);
let expected = if enabled { &models } else { &bundled };
for strategy in [RefreshStrategy::Offline, RefreshStrategy::OnlineIfUncached] {
assert_eq!(
&restarted
.raw_model_catalog(strategy, DEFAULT_HTTP_CLIENT_FACTORY)
.await
.models,
expected
);
}
assert_eq!(&restarted.try_get_remote_models().unwrap(), expected);
}
assert_eq!(endpoint.fetch_count(), 1);
}

View File

@@ -0,0 +1,267 @@
use crate::ModelCatalogOriginator;
use chrono::DateTime;
use chrono::Utc;
use codex_protocol::openai_models::ModelInfo;
use serde::Deserialize;
use serde::Serialize;
use std::fmt;
use std::future::Future;
use std::io;
use std::io::ErrorKind;
use std::path::PathBuf;
use std::pin::Pin;
use std::sync::Arc;
use std::time::Duration;
use tokio::fs;
use tracing::info;
/// Asynchronous storage for model catalog snapshots used by the models manager.
///
/// Implementations own cache freshness and lookup partitioning. [`ModelsCache::load`] must not
/// return stale entries or entries for a different client version. A shared backend must also keep
/// catalogs for different providers and tenants separate. The manager also validates the entry
/// identity against the current endpoint before using it.
///
/// Cache failures are non-fatal. The models manager logs them and falls back to the configured
/// models endpoint.
pub trait ModelsCache: fmt::Debug + Send + Sync {
/// Return a separate cache partition, or `None` to disable storage for this originator.
/// Implementations must isolate loads, writes, and TTL renewal from the default catalog.
fn for_originator(&self, _originator: ModelCatalogOriginator) -> Option<Arc<dyn ModelsCache>> {
None
}
/// Loads a fresh entry for `client_version`.
///
/// Returns `Ok(None)` for a normal miss, including an absent, stale, or version-mismatched
/// entry. Returns `Err` when the backend could not complete the lookup; the models manager
/// treats that error as a miss and fetches the catalog from the models endpoint.
fn load<'a>(
&'a self,
client_version: &'a str,
) -> ModelsCacheFuture<'a, Result<Option<ModelsCacheEntry>, ModelsCacheError>>;
/// Stores `entry`, replacing the snapshot for this cache implementation's lookup identity.
///
/// The implementation derives that identity from its own configuration and the entry metadata.
/// For example, a shared backend can capture provider and tenant identity when it is constructed.
fn store<'a>(
&'a self,
entry: &'a ModelsCacheEntry,
) -> ModelsCacheFuture<'a, Result<(), ModelsCacheError>>;
/// Extends freshness only if the stored version, identity, and ETag match.
///
/// The models manager calls this after the endpoint confirms that the cached ETag is still
/// current. Implementations must preserve the models, identity, ETag, and client version. This operation
/// cannot be expressed in terms of [`ModelsCache::load`], because `load` intentionally omits
/// expired entries. File-backed implementations can read and revalidate the stored entry
/// directly, while backends with native TTL support can extend the entry in place.
fn refresh_ttl<'a>(
&'a self,
client_version: &'a str,
identity: &'a str,
etag: &'a str,
) -> ModelsCacheFuture<'a, Result<(), ModelsCacheError>>;
}
/// Boxed future returned by [`ModelsCache`] implementations.
pub type ModelsCacheFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
/// Serialized model catalog and validation metadata stored in a [`ModelsCache`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ModelsCacheEntry {
/// Time when the catalog was fetched or last revalidated with the models endpoint.
///
/// `DateTime::<Utc>::MIN_UTC` marks an invalidated catalog, both in memory and in storage.
/// The manager rejects it even if the backend uses native TTL.
pub fetched_at: DateTime<Utc>,
/// Endpoint ETag used to revalidate the catalog without downloading an unchanged payload.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub etag: Option<String>,
/// Client version for which this catalog was returned.
///
/// The models manager rejects entries whose value is absent or differs from its current version.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub client_version: Option<String>,
/// Opaque provider and auth identity. Unscoped legacy entries are cache misses.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub identity: Option<String>,
/// Models returned by the catalog endpoint.
#[serde(
deserialize_with = "codex_protocol::openai_models::deserialize_model_infos_with_legacy_base"
)]
pub models: Vec<ModelInfo>,
}
impl ModelsCacheEntry {
/// Returns `true` when the cache entry has not exceeded the configured TTL.
fn is_fresh(&self, ttl: Duration) -> bool {
if ttl.is_zero() {
return false;
}
let Ok(ttl_duration) = chrono::Duration::from_std(ttl) else {
return false;
};
let age = Utc::now().signed_duration_since(self.fetched_at);
age <= ttl_duration
}
}
/// Error returned by a [`ModelsCache`] implementation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ModelsCacheError {
message: String,
}
impl ModelsCacheError {
/// Create a cache error without exposing backend-specific error types.
pub fn new(message: impl Into<String>) -> Self {
Self {
message: message.into(),
}
}
}
impl fmt::Display for ModelsCacheError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.message)
}
}
impl std::error::Error for ModelsCacheError {}
/// Built-in file-backed model catalog cache.
#[derive(Debug)]
pub(crate) struct FileModelsCache {
cache_path: PathBuf,
cache_ttl: Duration,
}
impl FileModelsCache {
/// Create a file-backed cache with the given path and TTL.
pub(crate) fn new(cache_path: PathBuf, cache_ttl: Duration) -> Self {
Self {
cache_path,
cache_ttl,
}
}
}
impl ModelsCache for FileModelsCache {
fn for_originator(&self, originator: ModelCatalogOriginator) -> Option<Arc<dyn ModelsCache>> {
Some(Arc::new(Self::new(
self.cache_path
.with_extension(format!("{}.json", originator.as_str())),
self.cache_ttl,
)))
}
fn load<'a>(
&'a self,
client_version: &'a str,
) -> ModelsCacheFuture<'a, Result<Option<ModelsCacheEntry>, ModelsCacheError>> {
Box::pin(
async move { load_fresh_file(&self.cache_path, self.cache_ttl, client_version).await },
)
}
fn store<'a>(
&'a self,
entry: &'a ModelsCacheEntry,
) -> ModelsCacheFuture<'a, Result<(), ModelsCacheError>> {
Box::pin(async move { save_file(&self.cache_path, entry).await })
}
fn refresh_ttl<'a>(
&'a self,
client_version: &'a str,
identity: &'a str,
etag: &'a str,
) -> ModelsCacheFuture<'a, Result<(), ModelsCacheError>> {
Box::pin(async move {
let mut entry = load_file(&self.cache_path)
.await
.map_err(cache_error)?
.ok_or_else(|| ModelsCacheError::new("cache not found"))?;
if entry.client_version.as_deref() != Some(client_version)
|| entry.identity.as_deref() != Some(identity)
|| entry.etag.as_deref() != Some(etag)
|| entry.is_fresh(self.cache_ttl / 2)
{
return Ok(());
}
entry.fetched_at = Utc::now();
save_file(&self.cache_path, &entry).await
})
}
}
async fn load_fresh_file(
cache_path: &PathBuf,
cache_ttl: Duration,
expected_version: &str,
) -> Result<Option<ModelsCacheEntry>, ModelsCacheError> {
info!(
cache_path = %cache_path.display(),
expected_version,
"models cache: attempting load_fresh"
);
let Some(cache) = load_file(cache_path).await.map_err(cache_error)? else {
return Ok(None);
};
info!(
cache_path = %cache_path.display(),
cached_version = ?cache.client_version,
fetched_at = %cache.fetched_at,
"models cache: loaded cache file"
);
if cache.client_version.as_deref() != Some(expected_version) {
info!(
cache_path = %cache_path.display(),
expected_version,
cached_version = ?cache.client_version,
"models cache: cache version mismatch"
);
return Ok(None);
}
if !cache.is_fresh(cache_ttl) {
info!(
cache_path = %cache_path.display(),
cache_ttl_secs = cache_ttl.as_secs(),
fetched_at = %cache.fetched_at,
"models cache: cache is stale"
);
return Ok(None);
}
info!(
cache_path = %cache_path.display(),
cache_ttl_secs = cache_ttl.as_secs(),
"models cache: cache hit"
);
Ok(Some(cache))
}
async fn load_file(cache_path: &PathBuf) -> io::Result<Option<ModelsCacheEntry>> {
match fs::read(cache_path).await {
Ok(contents) => {
let cache = serde_json::from_slice(&contents)
.map_err(|err| io::Error::new(ErrorKind::InvalidData, err.to_string()))?;
Ok(Some(cache))
}
Err(err) if err.kind() == ErrorKind::NotFound => Ok(None),
Err(err) => Err(err),
}
}
async fn save_file(cache_path: &PathBuf, cache: &ModelsCacheEntry) -> Result<(), ModelsCacheError> {
if let Some(parent) = cache_path.parent() {
fs::create_dir_all(parent).await.map_err(cache_error)?;
}
let json = serde_json::to_vec_pretty(cache).map_err(cache_error)?;
fs::write(cache_path, json).await.map_err(cache_error)
}
fn cache_error(error: impl fmt::Display) -> ModelsCacheError {
ModelsCacheError::new(error.to_string())
}

View File

@@ -0,0 +1,83 @@
//! Coverage for cache identity validation and conditional freshness updates.
use super::*;
use pretty_assertions::assert_eq;
#[tokio::test]
async fn mismatched_and_legacy_cache_entries_fetch_the_current_catalog() {
for identity in [None, Some("other-provider-or-account".to_string())] {
let stale = remote_model("stale", "Stale", /*priority*/ 0);
let current = remote_model("current", "Current", /*priority*/ 0);
let cache = TestModelsCache::with_entry(ModelsCacheEntry {
fetched_at: Utc::now(),
etag: Some("old-etag".into()),
client_version: Some(crate::client_version_to_whole()),
identity,
models: vec![stale],
});
let endpoint = TestModelsEndpoint::new(vec![vec![current.clone()]]);
let manager = OpenAiModelsManager::new_with_cache(
cache.clone(),
endpoint.clone(),
Some(AuthManager::from_auth_for_testing(
CodexAuth::create_dummy_chatgpt_auth_for_testing(),
)),
);
manager
.ensure_initialized(DEFAULT_HTTP_CLIENT_FACTORY)
.await;
assert_eq!(
manager
.raw_model_catalog(RefreshStrategy::InMemory, DEFAULT_HTTP_CLIENT_FACTORY)
.await
.models,
vec![current.clone()]
);
assert_eq!(endpoint.fetch_count(), 1);
}
}
#[tokio::test]
async fn matching_etag_cannot_renew_a_different_identity_or_catalog() {
let home = tempdir().unwrap();
let cache = FileModelsCache::new(home.path().join(MODEL_CACHE_FILE), DEFAULT_MODEL_CACHE_TTL);
let expected = ModelsCacheEntry {
fetched_at: Utc::now() - chrono::Duration::hours(1),
etag: Some("etag".into()),
client_version: Some(crate::client_version_to_whole()),
identity: Some("first-account".into()),
models: vec![remote_model("model", "Model", /*priority*/ 0)],
};
for (key, etag, version) in [
("other-account", "etag", crate::client_version_to_whole()),
(
"first-account",
"new-etag",
crate::client_version_to_whole(),
),
("first-account", "etag", "other-version".into()),
] {
let stored = ModelsCacheEntry {
identity: Some(key.into()),
etag: Some(etag.into()),
client_version: Some(version),
..expected.clone()
};
cache.store(&stored).await.unwrap();
cache
.refresh_ttl(
expected.client_version.as_deref().unwrap(),
expected.identity.as_deref().unwrap(),
expected.etag.as_deref().unwrap(),
)
.await
.unwrap();
let actual: ModelsCacheEntry = serde_json::from_slice(
&tokio::fs::read(home.path().join(MODEL_CACHE_FILE))
.await
.unwrap(),
)
.unwrap();
assert_eq!(actual, stored);
}
}

View File

@@ -0,0 +1,81 @@
//! Tracks the source of model metadata without changing the catalog wire or cache formats.
use std::borrow::Cow;
use std::collections::HashSet;
use codex_protocol::openai_models::ModelInfo;
use crate::cache::ModelsCacheEntry;
pub use codex_protocol::openai_models::CatalogModel;
pub use codex_protocol::openai_models::ModelOrigin;
/// Catalog authority is independent of whether its model metadata is borrowed or owned.
pub(crate) enum SelectedCatalog<'a> {
CurrentSnapshot(Cow<'a, [ModelInfo]>),
Fallback(Cow<'a, [ModelInfo]>),
}
impl<'a> SelectedCatalog<'a> {
pub fn into_models(self) -> Cow<'a, [ModelInfo]> {
match self {
Self::CurrentSnapshot(models) | Self::Fallback(models) => models,
}
}
}
/// The effective catalog and the IDs in the unmerged provider response share one lock.
#[derive(Debug)]
pub(crate) struct CatalogState {
pub entry: ModelsCacheEntry,
pub provider_model_ids: HashSet<String>,
// Distinguishes a successfully loaded empty catalog from the initial bundled seed.
pub initialized: bool,
}
impl CatalogState {
pub fn bundled(entry: ModelsCacheEntry) -> Self {
Self {
entry,
provider_model_ids: HashSet::new(),
initialized: false,
}
}
pub fn provider(entry: ModelsCacheEntry) -> Self {
// Capture raw response IDs before merging, including when loading from disk cache.
let provider_model_ids = entry
.models
.iter()
.map(|model| model.slug.clone())
.collect();
Self {
entry,
provider_model_ids,
initialized: true,
}
}
pub fn model_origin(&self, selected: &SelectedCatalog<'_>, slug: &str) -> ModelOrigin {
if matches!(selected, SelectedCatalog::CurrentSnapshot(_))
&& self.provider_model_ids.contains(slug)
{
ModelOrigin::Provider
} else {
ModelOrigin::Bundled
}
}
pub fn model_catalog(&self, selected: SelectedCatalog<'_>) -> Vec<CatalogModel> {
let models = match &selected {
SelectedCatalog::CurrentSnapshot(models) | SelectedCatalog::Fallback(models) => models,
};
models
.iter()
.map(|model| CatalogModel {
origin: self.model_origin(&selected, &model.slug),
model: model.clone().into(),
})
.collect()
}
}

View File

@@ -0,0 +1,183 @@
#![cfg(test)]
//! Catalog origins survive merges, cache reloads, and changes of provider identity.
use super::*;
use pretty_assertions::assert_eq;
#[tokio::test]
async fn catalog_origins_survive_reload_and_auth_change() {
for (slug, reviewer_origin) in [
("codex-auto-review", ModelOrigin::Provider),
("gateway-model", ModelOrigin::Bundled),
] {
let home = tempdir().unwrap();
let model = remote_model_with_visibility(slug, "Gateway", /*priority*/ 0, "hide");
let auth =
AuthManager::from_auth_for_testing(CodexAuth::create_dummy_chatgpt_auth_for_testing());
let endpoint =
TestAuthAwareModelsEndpoint::new(Some(auth.clone()), vec![vec![model.clone()]]);
let manager =
OpenAiModelsManager::new(home.path().into(), endpoint.clone(), Some(auth.clone()));
let mut updates = manager.model_catalog_updates().unwrap();
manager.set_api_key_model_discovery_enabled(/*enabled*/ true);
let bundled = manager
.model_catalog_with_origins(RefreshStrategy::Offline, DEFAULT_HTTP_CLIENT_FACTORY)
.await;
assert!(manager.refreshed_model_catalog().is_none());
assert!(!updates.has_changed().unwrap());
let catalog = manager
.model_catalog_with_origins(RefreshStrategy::Online, DEFAULT_HTTP_CLIENT_FACTORY)
.await;
assert_eq!(
manager.refreshed_model_catalog().as_deref(),
Some([model.clone()].as_slice())
);
assert!(updates.has_changed().unwrap());
updates.borrow_and_update();
assert!(catalog.contains(&CatalogModel {
model: model.into(),
origin: ModelOrigin::Provider
}));
assert_eq!(
catalog
.iter()
.find(|entry| entry.model.slug == "codex-auto-review")
.map(|entry| entry.origin),
Some(reviewer_origin)
);
let restarted = openai_manager_for_tests(home.path().to_path_buf(), endpoint.clone());
assert_eq!(
restarted
.model_catalog_with_origins(RefreshStrategy::Offline, DEFAULT_HTTP_CLIENT_FACTORY)
.await,
catalog
);
assert_eq!(endpoint.fetch_count(), 1);
assert!(
restarted.refreshed_model_catalog().is_none(),
"disk cache is not a fresh provider response"
);
assert_eq!(
restarted
.get_model_info(
&format!("gateway/{slug}-variant"),
&ModelsManagerConfig::default()
)
.await
.origin,
ModelOrigin::Provider
);
// An empty subsequent response restores bundled origins instead of retaining old IDs.
assert_eq!(
restarted
.model_catalog_with_origins(RefreshStrategy::Online, DEFAULT_HTTP_CLIENT_FACTORY)
.await,
bundled
);
// The original manager still holds provider IDs, but its identity is no longer current.
auth.set_external_auth(Arc::new(TestExternalApiKeyAuth))
.await
.unwrap();
assert!(
manager.refreshed_model_catalog().is_none(),
"a previous identity cannot normalize settings"
);
assert_eq!(
manager
.model_catalog_with_origins(RefreshStrategy::Offline, DEFAULT_HTTP_CLIENT_FACTORY)
.await,
bundled
);
assert_eq!(endpoint.fetch_count(), 2);
assert_eq!(
manager
.get_model_info("codex-auto-review", &ModelsManagerConfig::default())
.await
.origin,
ModelOrigin::Bundled
);
}
}
#[tokio::test]
async fn static_catalog_records_its_supplied_origin() {
let model = remote_model("reviewer", "Reviewer", /*priority*/ 0);
for origin in [
ModelOrigin::Bundled,
ModelOrigin::Provider,
ModelOrigin::ExplicitConfig,
] {
let manager = StaticModelsManager::new(
/*auth_manager*/ None,
ModelsResponse {
models: vec![model.clone()],
},
origin,
);
assert_eq!(
manager
.get_model_info(
"namespace/reviewer-variant",
&ModelsManagerConfig::default()
)
.await,
CatalogModel {
model: ModelInfo {
slug: "namespace/reviewer-variant".to_string(),
..model.clone()
}
.into(),
origin
}
);
assert_eq!(
manager
.model_catalog_with_origins(RefreshStrategy::Offline, DEFAULT_HTTP_CLIENT_FACTORY)
.await,
vec![CatalogModel {
model: model.clone().into(),
origin
}]
);
}
}
#[tokio::test]
async fn refreshing_retained_originators_keeps_catalog_notifications_isolated() {
let root_model = remote_model("root-model", "Root", /*priority*/ 0);
let work_model = remote_model("work-model", "Work", /*priority*/ 0);
let root_endpoint = TestModelsEndpoint::new(vec![vec![root_model.clone()]]);
let work_endpoint = TestModelsEndpoint::new(vec![vec![work_model.clone()]]);
let root =
OpenAiModelsManager::new_without_cache(root_endpoint.clone(), /*auth_manager*/ None);
let work = Arc::new(OpenAiModelsManager::new_without_cache(
work_endpoint.clone(),
/*auth_manager*/ None,
));
root.list_models(RefreshStrategy::Online, DEFAULT_HTTP_CLIENT_FACTORY)
.await;
let root_updates = root.model_catalog_updates().unwrap();
let work_updates = work.model_catalog_updates().unwrap();
root.originator_managers
.lock()
.unwrap()
.insert(ModelCatalogOriginator::WorkDesktop, work.clone());
root.refresh_originator_catalogs(DEFAULT_HTTP_CLIENT_FACTORY)
.await;
assert_eq!(
root.refreshed_model_catalog().as_deref(),
Some([root_model].as_slice())
);
assert_eq!(
work.refreshed_model_catalog().as_deref(),
Some([work_model].as_slice())
);
assert!(!root_updates.has_changed().unwrap());
assert!(work_updates.has_changed().unwrap());
assert_eq!(root_endpoint.fetch_count(), 1);
assert_eq!(work_endpoint.fetch_count(), 1);
assert_eq!(root.originator_managers.lock().unwrap().len(), 1);
}

View File

@@ -0,0 +1,28 @@
use codex_prompts::ResolvedModelMessages;
use codex_protocol::config_types::CollaborationModeMask;
use codex_protocol::config_types::ModeKind;
use codex_protocol::openai_models::ReasoningEffort;
pub fn builtin_collaboration_mode_presets() -> Vec<CollaborationModeMask> {
let messages = ResolvedModelMessages::bundled().collaboration_modes();
vec![
CollaborationModeMask {
name: ModeKind::Plan.display_name().to_string(),
mode: Some(ModeKind::Plan),
model: None,
reasoning_effort: Some(Some(ReasoningEffort::Medium)),
developer_instructions: Some(Some(messages.plan.text().to_string())),
},
CollaborationModeMask {
name: ModeKind::Default.display_name().to_string(),
mode: Some(ModeKind::Default),
model: None,
reasoning_effort: None,
developer_instructions: Some(Some(messages.default.text().to_string())),
},
]
}
#[cfg(test)]
#[path = "collaboration_mode_presets_tests.rs"]
mod tests;

View File

@@ -0,0 +1,34 @@
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn preset_names_use_mode_display_names() {
let presets = builtin_collaboration_mode_presets();
let [plan, default] = presets.as_slice() else {
panic!("expected Plan and Default presets");
};
assert_eq!(plan.name, ModeKind::Plan.display_name());
assert_eq!(default.name, ModeKind::Default.display_name());
assert_eq!(plan.model, None);
assert_eq!(plan.reasoning_effort, Some(Some(ReasoningEffort::Medium)));
assert_eq!(default.model, None);
assert_eq!(default.reasoning_effort, None);
}
#[test]
fn default_mode_instructions_follow_user_input_tool_availability() {
let presets = builtin_collaboration_mode_presets();
let default_instructions = presets[1]
.developer_instructions
.as_ref()
.expect("default preset should include instructions")
.as_ref()
.expect("default instructions should be set");
assert!(default_instructions.contains(
"Use the `request_user_input` tool only when it is listed in the available tools"
));
assert!(
default_instructions.contains("Ask the user directly with one concise plain-text question")
);
}

View File

@@ -0,0 +1,12 @@
use codex_protocol::config_types::Personality;
use codex_protocol::openai_models::ModelsResponse;
#[derive(Debug, Clone, Default)]
pub struct ModelsManagerConfig {
pub model_context_window: Option<i64>,
pub model_auto_compact_token_limit: Option<i64>,
pub tool_output_token_limit: Option<usize>,
pub base_instructions: Option<String>,
pub personality: Option<Personality>,
pub model_catalog: Option<ModelsResponse>,
}

View File

@@ -0,0 +1,31 @@
pub mod cache;
mod catalog;
pub mod collaboration_mode_presets;
pub(crate) mod config;
pub mod manager;
pub mod model_info;
pub mod model_presets;
mod originator;
pub mod test_support;
pub use catalog::CatalogModel;
pub use catalog::ModelOrigin;
pub use codex_protocol::auth::AuthMode;
pub use config::ModelsManagerConfig;
pub use originator::ModelCatalogOriginator;
/// Load the bundled model catalog shipped with `codex-models-manager`.
pub fn bundled_models_response()
-> std::result::Result<codex_protocol::openai_models::ModelsResponse, serde_json::Error> {
serde_json::from_str(include_str!("../models.json"))
}
/// Convert the client version string to a whole version string (e.g. "1.2.3-alpha.4" -> "1.2.3").
pub fn client_version_to_whole() -> String {
format!(
"{}.{}.{}",
env!("CARGO_PKG_VERSION_MAJOR"),
env!("CARGO_PKG_VERSION_MINOR"),
env!("CARGO_PKG_VERSION_PATCH")
)
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,160 @@
use codex_protocol::config_types::Personality;
use codex_protocol::config_types::ReasoningSummary;
use codex_protocol::openai_models::ConfigShellToolType;
use codex_protocol::openai_models::ModelInfo;
use codex_protocol::openai_models::ModelMessages;
use codex_protocol::openai_models::ModelVisibility;
use codex_protocol::openai_models::TruncationMode;
use codex_protocol::openai_models::TruncationPolicyConfig;
use codex_protocol::openai_models::WebSearchToolType;
use codex_protocol::openai_models::default_input_modalities;
use crate::config::ModelsManagerConfig;
use codex_utils_output_truncation::approx_bytes_for_tokens;
use tracing::warn;
pub const BASE_INSTRUCTIONS: &str = include_str!("../prompt.md");
const PERSONALITY_SECTION_HEADER: &str = "# Personality";
pub fn with_config_overrides(mut model: ModelInfo, config: &ModelsManagerConfig) -> ModelInfo {
if let Some(context_window) = config.model_context_window {
model.context_window = Some(
model
.max_context_window
.map_or(context_window, |max_context_window| {
context_window.min(max_context_window)
}),
);
}
if let Some(auto_compact_token_limit) = config.model_auto_compact_token_limit {
model.auto_compact_token_limit = Some(auto_compact_token_limit);
}
if let Some(token_limit) = config.tool_output_token_limit {
model.truncation_policy = match model.truncation_policy.mode {
TruncationMode::Bytes => {
let byte_limit =
i64::try_from(approx_bytes_for_tokens(token_limit)).unwrap_or(i64::MAX);
TruncationPolicyConfig::bytes(byte_limit)
}
TruncationMode::Tokens => {
let limit = i64::try_from(token_limit).unwrap_or(i64::MAX);
TruncationPolicyConfig::tokens(limit)
}
};
}
if let Some(base_instructions) = &config.base_instructions {
let model_messages = model.model_messages.get_or_insert_default();
model_messages.instructions_template = Some(base_instructions.clone());
} else if config.personality == Some(Personality::None)
&& let Some(instructions_template) = model
.model_messages
.as_mut()
.and_then(|messages| messages.instructions_template.as_mut())
{
*instructions_template = strip_personality_section(std::mem::take(instructions_template));
}
model
}
fn strip_personality_section(mut instructions: String) -> String {
let mut section_start = None;
let mut section_end = None;
let mut offset = 0;
for line_with_ending in instructions.split_inclusive('\n') {
let line = match line_with_ending.strip_suffix('\n') {
Some(line) => line.strip_suffix('\r').unwrap_or(line),
None => line_with_ending,
};
if section_start.is_some() {
if is_h1_heading(line) {
section_end = Some(offset);
break;
}
} else if line == PERSONALITY_SECTION_HEADER {
section_start = Some(offset);
}
offset += line_with_ending.len();
}
if let Some(section_start) = section_start {
let section_end = section_end.unwrap_or(instructions.len());
instructions.replace_range(section_start..section_end, "");
}
instructions
}
fn is_h1_heading(line: &str) -> bool {
let Some(rest) = line.strip_prefix('#') else {
return false;
};
rest.is_empty() || rest.starts_with(' ') || rest.starts_with('\t')
}
/// Build a minimal fallback model descriptor for missing/unknown slugs.
pub fn model_info_from_slug(slug: &str) -> ModelInfo {
warn!("Unknown model {slug} is used. This will use fallback model metadata.");
ModelInfo {
slug: slug.to_string(),
display_name: slug.to_string(),
description: None,
default_reasoning_level: None,
supported_reasoning_levels: Vec::new(),
shell_type: ConfigShellToolType::UnifiedExec,
visibility: ModelVisibility::None,
supported_in_api: true,
priority: 99,
additional_speed_tiers: Vec::new(),
service_tiers: Vec::new(),
default_service_tier: None,
available_access_programs: None,
availability_nux: None,
upgrade: None,
model_messages: Some(local_model_messages()),
include_skills_usage_instructions: false,
include_plugin_usage_instructions: false,
include_apps_usage_instructions: false,
supports_reasoning_summary_parameter: true,
default_reasoning_summary: ReasoningSummary::Auto,
support_verbosity: false,
default_verbosity: None,
apply_patch_tool_type: None,
web_search_tool_type: WebSearchToolType::Text,
web_search_provider: None,
truncation_policy: TruncationPolicyConfig::bytes(/*limit*/ 10_000),
supports_image_detail_original: false,
context_window: Some(272_000),
max_context_window: Some(272_000),
auto_compact_token_limit: None,
comp_hash: None,
effective_context_window_percent: 95,
experimental_supported_tools: Vec::new(),
input_modalities: default_input_modalities(),
supports_search_tool: false,
supports_experimental_context: false,
use_responses_lite: false,
supports_reasoning_effort_updates: false,
guardian: None,
node_repl_auto_review_required: false,
node_repl_disabled: false,
auto_review_model_override: None,
model_specialty: None,
tool_mode: None,
multi_agent_version: None,
multi_agent_reasoning_effort: None,
}
}
fn local_model_messages() -> ModelMessages {
ModelMessages {
instructions_template: Some(BASE_INSTRUCTIONS.to_string()),
..Default::default()
}
}
#[cfg(test)]
#[path = "model_info_tests.rs"]
mod tests;

View File

@@ -0,0 +1,45 @@
use crate::ModelsManagerConfig;
use crate::manager::ModelsManager;
use codex_protocol::openai_models::TruncationPolicyConfig;
use pretty_assertions::assert_eq;
use tempfile::TempDir;
use super::TestModelsEndpoint;
use super::openai_manager_for_tests;
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn offline_model_info_without_tool_output_override() {
let codex_home = TempDir::new().expect("create temp dir");
let config = ModelsManagerConfig::default();
let manager = openai_manager_for_tests(
codex_home.path().to_path_buf(),
TestModelsEndpoint::new(Vec::new()),
);
let model_info = manager.get_model_info("unknown-model", &config).await;
assert_eq!(
model_info.truncation_policy,
TruncationPolicyConfig::bytes(/*limit*/ 10_000)
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn offline_model_info_with_tool_output_override() {
let codex_home = TempDir::new().expect("create temp dir");
let config = ModelsManagerConfig {
tool_output_token_limit: Some(123),
..Default::default()
};
let manager = openai_manager_for_tests(
codex_home.path().to_path_buf(),
TestModelsEndpoint::new(Vec::new()),
);
let model_info = manager.get_model_info("gpt-5.5", &config).await;
assert_eq!(
model_info.truncation_policy,
TruncationPolicyConfig::tokens(/*limit*/ 123)
);
}

View File

@@ -0,0 +1,281 @@
use super::*;
use crate::ModelsManagerConfig;
use codex_prompts::render_model_instructions;
use codex_protocol::config_types::Personality;
use codex_protocol::openai_models::ApprovalMessages;
use codex_protocol::openai_models::AppsMessages;
use codex_protocol::openai_models::AutoReviewMessages;
use codex_protocol::openai_models::CollaborationModeMessages;
use codex_protocol::openai_models::ConfirmationPolicies;
use codex_protocol::openai_models::GranularApprovalMessages;
use codex_protocol::openai_models::GuardianV2ModelConfig;
use codex_protocol::openai_models::ModelTokenBudgetConfig;
use codex_protocol::openai_models::MultiAgentMessages;
use codex_protocol::openai_models::MultiAgentModeMessages;
use codex_protocol::openai_models::MultiAgentRoleMessages;
use codex_protocol::openai_models::MultiAgentToolMessages;
use codex_protocol::openai_models::PermissionMessages;
use codex_protocol::openai_models::ToolMessage;
use codex_protocol::openai_models::ToolMessages;
use pretty_assertions::assert_eq;
fn config_with_personality(personality: Option<Personality>) -> ModelsManagerConfig {
ModelsManagerConfig {
personality,
..Default::default()
}
}
#[test]
fn base_instruction_override_is_literal_and_preserves_catalog_messages() {
let override_instructions = "override {{ personality }}\n# Personality\nKeep me";
let persistent_instructions = "Follow up on the active task.";
let async_message_description = "Catalog async message description.";
let mut model = model_info_from_slug("unknown-model");
let approvals = ApprovalMessages {
on_request: Some("user approvals".to_string()),
on_request_auto_review: Some("auto approvals".to_string()),
never: Some("never approvals".to_string()),
unless_trusted: Some("unless-trusted approvals".to_string()),
granular: Some(GranularApprovalMessages {
intro: Some("Catalog: {{ policy }}".to_string()),
prompted_categories: Some("Allowed: {{ categories }}".to_string()),
rejected_categories: Some("Denied: {{ categories }}".to_string()),
}),
..Default::default()
};
let collaboration_modes = CollaborationModeMessages {
default: Some("default instructions".to_string()),
plan: Some("plan instructions".to_string()),
};
let auto_review = AutoReviewMessages {
policy: Some("review policy".to_string()),
policy_template: Some("review policy template".to_string()),
node_repl_policy: None,
rejection_instructions: Some("rejection instructions".to_string()),
timeout_instructions: Some(String::new()),
};
let permissions = PermissionMessages {
danger_full_access: Some("danger".to_string()),
workspace_write: Some(String::new()),
read_only: None,
approved_prefixes: None,
..PermissionMessages::default()
};
let multi_agent = MultiAgentMessages {
role: Some(MultiAgentRoleMessages {
root: Some("root base".to_string()),
subagent: Some("subagent base".to_string()),
}),
mode: Some(MultiAgentModeMessages {
explicit: Some("explicit mode".to_string()),
proactive: Some("proactive mode".to_string()),
hint_text: Some("mode hint".to_string()),
}),
};
let token_budget = ModelTokenBudgetConfig {
enabled: false,
use_history_notes_extension: false,
reminder_threshold_tokens: 128,
reminder_message_template: "budget reminder".to_string(),
guidance_message: "budget guidance".to_string(),
auto_compact_fallback_prompt: "compact prompt".to_string(),
auto_compact_fallback_buffer_tokens: 64,
};
let guardian_v2 = GuardianV2ModelConfig {
classifier_instructions: Some("Guardian experiment".to_string()),
..Default::default()
};
let confirmation_policies = ConfirmationPolicies {
browser_use: Some("# Browser policy\n\n{{literal_markdown}}\n".to_string()),
computer_use: Some(" # Native policy\r\n\n${native_markdown}\n".to_string()),
};
let mut messages = ModelMessages {
apps: Some(AppsMessages {
usage_instructions: Some("Catalog Apps instructions.".to_string()),
}),
plugins: None,
content_filter_guidance: None,
persistent_instructions: Some(persistent_instructions.to_string()),
tools: Some(ToolMessages {
send_user_message_async: Some(ToolMessage {
description: Some(async_message_description.to_string()),
..Default::default()
}),
multi_agent: Some(MultiAgentToolMessages {
spawn_agent: Some(ToolMessage {
description: Some("Catalog spawn description.".to_string()),
..Default::default()
}),
..Default::default()
}),
..Default::default()
}),
instructions_template: Some("template".to_string()),
approvals: Some(approvals),
collaboration_modes: Some(collaboration_modes),
auto_review: Some(auto_review),
permissions: Some(permissions),
multi_agent: Some(multi_agent),
token_budget: Some(token_budget),
confirmation_policies: Some(confirmation_policies),
guardian_v2: Some(guardian_v2),
};
model.model_messages = Some(messages.clone());
let config = ModelsManagerConfig {
base_instructions: Some(override_instructions.to_string()),
personality: Some(Personality::None),
..Default::default()
};
let updated = with_config_overrides(model, &config);
messages.instructions_template = Some(override_instructions.to_string());
assert_eq!(updated.model_messages, Some(messages));
assert_eq!(render_model_instructions(&updated), override_instructions);
}
#[test]
fn personality_none_strips_catalog_instruction_sources_through_the_next_h1() {
let config = config_with_personality(Some(Personality::None));
for (instructions, expected) in [
(
"Intro\n\n# Personality\n\nRemove me\n\n## Writing Style\n\nRemove me too\n\n# Safety\n\nKeep me",
"Intro\n\n# Safety\n\nKeep me",
),
("Intro\n\n# Personality\n\nRemove me", "Intro\n\n"),
(
"Intro\n\n## Personality\n\nKeep me",
"Intro\n\n## Personality\n\nKeep me",
),
(
"Intro\n\n# Personality \n\nKeep me",
"Intro\n\n# Personality \n\nKeep me",
),
(
"Intro\r\n\r\n# Personality\r\n\r\nRemove me\r\n\r\n## Writing Style\r\n\r\nRemove me too\r\n\r\n# General\r\n\r\nKeep me",
"Intro\r\n\r\n# General\r\n\r\nKeep me",
),
] {
let mut messages = ModelMessages {
instructions_template: Some(instructions.to_string()),
persistent_instructions: Some(String::new()),
tools: Some(ToolMessages {
send_user_message_async: Some(ToolMessage {
description: Some(String::new()),
..Default::default()
}),
multi_agent: Some(MultiAgentToolMessages {
spawn_agent: Some(ToolMessage {
description: Some(String::new()),
..Default::default()
}),
..Default::default()
}),
..Default::default()
}),
approvals: Some(ApprovalMessages {
on_request: Some("user approvals".to_string()),
on_request_auto_review: None,
never: None,
unless_trusted: None,
granular: None,
..Default::default()
}),
..Default::default()
};
let mut model = model_info_from_slug("unknown-model");
model.model_messages = Some(messages.clone());
let updated = with_config_overrides(model, &config);
messages.instructions_template = Some(expected.to_string());
assert_eq!(updated.model_messages, Some(messages));
}
}
#[test]
fn baked_personality_section_is_preserved_without_explicit_none() {
let instructions = "Intro\n# Personality\nKeep me\n# General\nKeep me too";
let configs = [
config_with_personality(/*personality*/ None),
config_with_personality(Some(Personality::Friendly)),
config_with_personality(Some(Personality::Pragmatic)),
];
for config in configs {
let mut model = model_info_from_slug("unknown-model");
model
.model_messages
.as_mut()
.expect("fallback model messages")
.instructions_template = Some(instructions.to_string());
assert_eq!(
render_model_instructions(&with_config_overrides(model, &config)),
instructions
);
}
}
#[test]
fn explicit_empty_base_instructions_stay_empty_with_personality_none() {
let mut model = model_info_from_slug("unknown-model");
model
.model_messages
.as_mut()
.expect("fallback model messages")
.instructions_template = Some("Intro\n# Personality\nRemove me".to_string());
let config = ModelsManagerConfig {
base_instructions: Some(String::new()),
personality: Some(Personality::None),
..Default::default()
};
let updated = with_config_overrides(model, &config);
assert_eq!(
updated
.model_messages
.as_ref()
.and_then(|messages| messages.instructions_template.as_deref()),
Some("")
);
assert_eq!(render_model_instructions(&updated), "");
}
#[test]
fn unknown_model_uses_builtin_instruction_template() {
let model = model_info_from_slug("unknown-model");
assert_eq!(render_model_instructions(&model), BASE_INSTRUCTIONS);
}
#[test]
fn model_context_window_override_clamps_to_max_context_window() {
let mut model = model_info_from_slug("unknown-model");
model.context_window = Some(273_000);
model.max_context_window = Some(400_000);
let config = ModelsManagerConfig {
model_context_window: Some(500_000),
..Default::default()
};
let updated = with_config_overrides(model.clone(), &config);
let mut expected = model;
expected.context_window = Some(400_000);
assert_eq!(updated, expected);
}
#[test]
fn model_context_window_uses_model_value_without_override() {
let mut model = model_info_from_slug("unknown-model");
model.context_window = Some(273_000);
model.max_context_window = Some(400_000);
let config = ModelsManagerConfig::default();
let updated = with_config_overrides(model.clone(), &config);
assert_eq!(updated, model);
}

View File

@@ -0,0 +1,6 @@
/// Legacy notice keys kept for config compatibility with older migration prompts.
///
/// Hardcoded model presets were removed; model listings are now derived from the active catalog.
pub const HIDE_GPT5_1_MIGRATION_PROMPT_CONFIG: &str = "hide_gpt5_1_migration_prompt";
pub const HIDE_GPT_5_1_CODEX_MAX_MIGRATION_PROMPT_CONFIG: &str =
"hide_gpt-5.1-codex-max_migration_prompt";

View File

@@ -0,0 +1,33 @@
//! Bounded catalog partitions for callers migrated to CCA. Other callers keep the default catalog.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum ModelCatalogOriginator {
Work,
WorkWeb,
WorkDesktop,
WorkMobile,
Chat,
}
impl ModelCatalogOriginator {
pub fn from_originator(originator: &str) -> Option<Self> {
match originator {
"codex_work_cca" => Some(Self::Work),
"codex_work_web" => Some(Self::WorkWeb),
"codex_work_desktop" => Some(Self::WorkDesktop),
"codex_work_mobile" => Some(Self::WorkMobile),
"chatgpt_cca" => Some(Self::Chat),
_ => None,
}
}
pub fn as_str(self) -> &'static str {
match self {
Self::Work => "codex_work_cca",
Self::WorkWeb => "codex_work_web",
Self::WorkDesktop => "codex_work_desktop",
Self::WorkMobile => "codex_work_mobile",
Self::Chat => "chatgpt_cca",
}
}
}

View File

@@ -0,0 +1,40 @@
//! Test-only helpers exposed for dependent crate tests.
//!
//! Production code should not depend on this module.
use crate::CatalogModel;
use crate::ModelOrigin;
use crate::ModelsManagerConfig;
use crate::bundled_models_response;
use crate::manager::construct_model_info_from_candidates;
use codex_protocol::openai_models::ModelInfo;
use codex_protocol::openai_models::ModelPreset;
/// Get model identifier without consulting remote state or cache.
pub fn get_model_offline_for_tests(model: Option<&str>) -> String {
if let Some(model) = model {
return model.to_string();
}
let mut response = bundled_models_response().unwrap_or_default();
response.models.sort_by_key(|model| model.priority);
let presets: Vec<ModelPreset> = response.models.into_iter().map(Into::into).collect();
presets
.iter()
.find(|preset| preset.show_in_picker)
.or_else(|| presets.first())
.map(|preset| preset.model.clone())
.unwrap_or_default()
}
/// Resolve metadata and its source without consulting remote state or cache.
pub fn construct_model_info_offline_for_tests(
model: &str,
config: &ModelsManagerConfig,
) -> CatalogModel {
let candidates: &[ModelInfo] = if let Some(model_catalog) = config.model_catalog.as_ref() {
&model_catalog.models
} else {
&[]
};
construct_model_info_from_candidates(model, candidates, ModelOrigin::ExplicitConfig, config)
}