| 1 | use chrono::Utc; |
| 2 | use codewhale_config::ProviderKind; |
| 3 | use codewhale_runtime::codex_model_roster::{ |
| 4 | CatalogSnapshot, CodexModelCacheFreshness, CodexModelMetadata, CodexModelRoster, |
| 5 | MAX_MODEL_CACHE_BYTES, cached_roster_for, invalidate_roster_cache, load_snapshot, |
| 6 | snapshot_path, |
| 7 | }; |
| 8 | use codewhale_runtime::config::Config; |
| 9 | |
| 10 | #[must_use] |
| 11 | pub fn model_roster_for(config: &Config) -> CodexModelRoster { |
| 12 | let mut roster = cached_roster_for(config); |
| 13 | enrich_reasoning_from_catalog(&mut roster); |
| 14 | roster |
| 15 | } |
| 16 | |
| 17 | fn enrich_reasoning_from_catalog(roster: &mut CodexModelRoster) { |
| 18 | for model in &mut roster.models { |
| 19 | if model.reasoning == Some(false) |
| 20 | || (model.reasoning.is_some() && !model.efforts.is_empty()) |
| 21 | { |
| 22 | continue; |
| 23 | } |
| 24 | let Some(offering) = |
| 25 | crate::provider_lake::catalog_offering_for_model(ProviderKind::Openai, &model.id) |
| 26 | else { |
| 27 | continue; |
| 28 | }; |
| 29 | if model.reasoning.is_none() { |
| 30 | model.reasoning = offering.reasoning; |
| 31 | } |
| 32 | if model.efforts.is_empty() |
| 33 | && let Some(efforts) = |
| 34 | crate::reasoning_preference::ReasoningEffort::catalog_effort_values_for_offering( |
| 35 | &offering, |
| 36 | ) |
| 37 | { |
| 38 | model.efforts = efforts |
| 39 | .into_iter() |
| 40 | .map(|effort| effort.as_setting().to_string()) |
| 41 | .collect(); |
| 42 | } |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | fn prepare_chatgpt_refresh( |
| 47 | config: &Config, |
| 48 | ) -> Result<(std::path::PathBuf, crate::client::CodewhaleClient, Config), &'static str> { |
| 49 | let mut selected = config.clone(); |
| 50 | let identity = selected |
| 51 | .builtin_provider_identity(ProviderKind::OpenaiCodex) |
| 52 | .map_err(|_| "chatgpt_plan_permission_required")?; |
| 53 | selected |
| 54 | .scope_to_provider_identity(&identity) |
| 55 | .map_err(|_| "chatgpt_plan_permission_required")?; |
| 56 | let path = snapshot_path(&selected).ok_or("chatgpt_plan_permission_required")?; |
| 57 | let client = crate::client::CodewhaleClient::for_catalog_refresh(&selected) |
| 58 | .map_err(|_| "chatgpt_plan_credentials_unavailable")?; |
| 59 | Ok((path, client, selected)) |
| 60 | } |
| 61 | |
| 62 | /// Fetch through the existing provider client. A registration change during |
| 63 | /// the request cannot publish an old account's models under a new account. |
| 64 | pub async fn update_from_chatgpt(config: &Config) -> Result<CodexModelRoster, &'static str> { |
| 65 | let prepared = config.clone(); |
| 66 | #[cfg(any(test, feature = "test-support"))] |
| 67 | let ticket = crate::test_support::env_scope_ticket(); |
| 68 | let (path, client, config, identity, observation, refresh_ticket, _refresh) = |
| 69 | tokio::task::spawn_blocking(move || { |
| 70 | #[cfg(any(test, feature = "test-support"))] |
| 71 | let _membership = crate::test_support::join_env_scope(ticket); |
| 72 | let (path, client, config) = prepare_chatgpt_refresh(&prepared)?; |
| 73 | let identity = config |
| 74 | .active_provider_identity() |
| 75 | .map_err(|_| "provider_identity_changed")?; |
| 76 | let (_, generation) = crate::provider_catalog_live::inventory_scope(&config, &identity) |
| 77 | .map_err(|_| "provider_identity_changed")?; |
| 78 | let refresh = crate::provider_catalog_live::try_inventory_refresh(&identity) |
| 79 | .ok_or("refresh_pending")?; |
| 80 | let observation = |
| 81 | crate::provider_readiness::inventory_observation_for_route(&config, &identity); |
| 82 | let refresh_ticket = crate::provider_catalog_live::begin_inventory_refresh( |
| 83 | &identity, |
| 84 | &config.base_url_for_route(&identity), |
| 85 | generation, |
| 86 | ) |
| 87 | .ok_or("refresh_superseded")?; |
| 88 | Ok::<_, &'static str>(( |
| 89 | path, |
| 90 | client, |
| 91 | config, |
| 92 | identity, |
| 93 | observation, |
| 94 | refresh_ticket, |
| 95 | refresh, |
| 96 | )) |
| 97 | }) |
| 98 | .await |
| 99 | .map_err(|_| "chatgpt_plan_credentials_unavailable")??; |
| 100 | let available = tokio::time::timeout(std::time::Duration::from_secs(20), client.list_models()) |
| 101 | .await |
| 102 | .map_err(|_| { |
| 103 | crate::provider_catalog_live::record_inventory_error( |
| 104 | &refresh_ticket, |
| 105 | Some(codewhale_config::catalog::CatalogRefreshError::Network), |
| 106 | ); |
| 107 | "chatgpt_models_timeout" |
| 108 | })? |
| 109 | .map_err(|_| { |
| 110 | crate::provider_catalog_live::record_inventory_error( |
| 111 | &refresh_ticket, |
| 112 | Some(codewhale_config::catalog::CatalogRefreshError::Network), |
| 113 | ); |
| 114 | "chatgpt_models_unavailable" |
| 115 | })?; |
| 116 | if available.iter().any(|model| { |
| 117 | !codewhale_runtime::catalog_cache::valid_catalog_model_id(&model.id) |
| 118 | || model |
| 119 | .display_name |
| 120 | .as_ref() |
| 121 | .is_some_and(|name| name.len() > 512 || name.chars().any(char::is_control)) |
| 122 | }) { |
| 123 | crate::provider_catalog_live::record_inventory_error( |
| 124 | &refresh_ticket, |
| 125 | Some(codewhale_config::catalog::CatalogRefreshError::InvalidResponse), |
| 126 | ); |
| 127 | return Err("chatgpt_models_invalid_response"); |
| 128 | } |
| 129 | let models = available |
| 130 | .into_iter() |
| 131 | .map(|model| CodexModelMetadata { |
| 132 | id: model.id, |
| 133 | display_name: model.display_name, |
| 134 | context_window: model |
| 135 | .context_window |
| 136 | .filter(|window| (1..=16_000_000).contains(window)), |
| 137 | reasoning: model.reasoning, |
| 138 | efforts: model.efforts, |
| 139 | }) |
| 140 | .collect(); |
| 141 | let snapshot = CatalogSnapshot { |
| 142 | fetched_at: Utc::now(), |
| 143 | models, |
| 144 | }; |
| 145 | #[cfg(any(test, feature = "test-support"))] |
| 146 | let ticket = crate::test_support::env_scope_ticket(); |
| 147 | let publication_ticket = refresh_ticket.clone(); |
| 148 | let result = tokio::task::spawn_blocking(move || { |
| 149 | #[cfg(any(test, feature = "test-support"))] |
| 150 | let _membership = crate::test_support::join_env_scope(ticket); |
| 151 | if snapshot_path(&config).as_ref() != Some(&path) |
| 152 | || crate::provider_readiness::inventory_observation_for_route(&config, &identity) |
| 153 | != observation |
| 154 | { |
| 155 | return Err("refresh_credentials_changed"); |
| 156 | } |
| 157 | let encoded = serde_json::to_vec(&snapshot).map_err(|_| "cache_write_failed")?; |
| 158 | if encoded.len() as u64 > MAX_MODEL_CACHE_BYTES { |
| 159 | return Err("chatgpt_models_response_too_large"); |
| 160 | } |
| 161 | crate::provider_catalog_live::with_current_route_ticket( |
| 162 | &refresh_ticket, |
| 163 | identity.provider, |
| 164 | identity.key.as_str(), |
| 165 | &config.base_url_for_route(&identity), |
| 166 | || { |
| 167 | codewhale_config::persistence::atomic_write(&path, &encoded) |
| 168 | .map_err(|_| "cache_write_failed")?; |
| 169 | invalidate_roster_cache(); |
| 170 | Ok(load_snapshot(&path, Utc::now())) |
| 171 | }, |
| 172 | ) |
| 173 | .ok_or("refresh_superseded")? |
| 174 | }) |
| 175 | .await |
| 176 | .map_err(|_| "cache_write_failed")?; |
| 177 | crate::provider_catalog_live::record_inventory_error( |
| 178 | &publication_ticket, |
| 179 | result |
| 180 | .as_ref() |
| 181 | .err() |
| 182 | .map(|_| codewhale_config::catalog::CatalogRefreshError::Network), |
| 183 | ); |
| 184 | if let Ok(ref roster) = result { |
| 185 | let missing_context_windows: Vec<&str> = roster |
| 186 | .models |
| 187 | .iter() |
| 188 | .filter(|model| model.context_window.is_none()) |
| 189 | .map(|model| model.id.as_str()) |
| 190 | .collect(); |
| 191 | if !missing_context_windows.is_empty() { |
| 192 | tracing::warn!( |
| 193 | target: "codex_model_cache", |
| 194 | missing_count = missing_context_windows.len(), |
| 195 | total_count = roster.models.len(), |
| 196 | models = ?missing_context_windows, |
| 197 | "ChatGPT model roster omitted context_window for one or more models; affected models will use the unverified 128000 fallback" |
| 198 | ); |
| 199 | } |
| 200 | } |
| 201 | result |
| 202 | } |
| 203 | |
| 204 | fn roster_needs_refresh(roster: &CodexModelRoster) -> bool { |
| 205 | roster.freshness != CodexModelCacheFreshness::Fresh |
| 206 | || (!roster.models.is_empty() |
| 207 | && roster |
| 208 | .models |
| 209 | .iter() |
| 210 | .all(|model| model.context_window.is_none())) |
| 211 | } |
| 212 | |
| 213 | pub fn spawn_refresh_if_stale(config: &Config) { |
| 214 | let Ok(handle) = tokio::runtime::Handle::try_current() else { |
| 215 | return; |
| 216 | }; |
| 217 | let config = config.clone(); |
| 218 | handle.spawn(async move { |
| 219 | let probe = config.clone(); |
| 220 | let Ok(needs_refresh) = |
| 221 | tokio::task::spawn_blocking(move || roster_needs_refresh(&model_roster_for(&probe))) |
| 222 | .await |
| 223 | else { |
| 224 | return; |
| 225 | }; |
| 226 | if !needs_refresh { |
| 227 | return; |
| 228 | } |
| 229 | match update_from_chatgpt(&config).await { |
| 230 | Ok(roster) => tracing::debug!( |
| 231 | target: "codex_model_cache", |
| 232 | model_count = roster.models.len(), |
| 233 | "ChatGPT plan roster refreshed" |
| 234 | ), |
| 235 | Err(err) => tracing::debug!( |
| 236 | target: "codex_model_cache", |
| 237 | error = %err, |
| 238 | "ChatGPT plan roster refresh skipped" |
| 239 | ), |
| 240 | } |
| 241 | }); |
| 242 | } |
| 243 | |
| 244 | #[cfg(test)] |
| 245 | mod tests { |
| 246 | use super::*; |
| 247 | use codewhale_runtime::codex_model_roster::install_test_chatgpt_roster; |
| 248 | |
| 249 | #[test] |
| 250 | fn own_roster_follows_selected_registration_and_disappears_after_sign_out() { |
| 251 | let _env = crate::test_support::lock_test_env(); |
| 252 | let directory = tempfile::tempdir().unwrap(); |
| 253 | let directory_path = directory.path().canonicalize().unwrap(); |
| 254 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &directory_path); |
| 255 | let mut account_a = Config::default(); |
| 256 | account_a.provider = Some(ProviderKind::Deepseek.as_str().to_string()); |
| 257 | codewhale_runtime::oauth::install_test_chatgpt_registration_for( |
| 258 | &mut account_a, |
| 259 | "account-a", |
| 260 | "oaiapp_workspace_a", |
| 261 | ) |
| 262 | .unwrap(); |
| 263 | let path_a = snapshot_path(&account_a).unwrap(); |
| 264 | let legacy_name = path_a.file_name().unwrap().to_string_lossy().replacen( |
| 265 | "chatgpt-plan-v2-", |
| 266 | "chatgpt-plan-", |
| 267 | 1, |
| 268 | ); |
| 269 | let legacy_path = path_a.with_file_name(legacy_name); |
| 270 | let legacy = CatalogSnapshot { |
| 271 | fetched_at: Utc::now(), |
| 272 | models: vec![CodexModelMetadata { |
| 273 | id: "deepseek-flash".to_string(), |
| 274 | display_name: None, |
| 275 | context_window: None, |
| 276 | reasoning: None, |
| 277 | efforts: Vec::new(), |
| 278 | }], |
| 279 | }; |
| 280 | codewhale_config::persistence::atomic_write( |
| 281 | &legacy_path, |
| 282 | &serde_json::to_vec(&legacy).unwrap(), |
| 283 | ) |
| 284 | .unwrap(); |
| 285 | assert!(model_roster_for(&account_a).models.is_empty()); |
| 286 | let (refresh_path, client, selected) = prepare_chatgpt_refresh(&account_a).unwrap(); |
| 287 | assert_eq!(refresh_path, path_a); |
| 288 | assert_eq!(client.api_provider(), ProviderKind::OpenaiCodex); |
| 289 | assert_eq!(client.base_url(), "https://api.openai.com/v1"); |
| 290 | assert_eq!( |
| 291 | selected.active_provider_identity().unwrap().provider, |
| 292 | ProviderKind::OpenaiCodex |
| 293 | ); |
| 294 | assert_eq!( |
| 295 | account_a.active_provider_identity().unwrap().provider, |
| 296 | ProviderKind::Deepseek |
| 297 | ); |
| 298 | let mut proxy = account_a.clone(); |
| 299 | let identity = proxy |
| 300 | .builtin_provider_identity(ProviderKind::OpenaiCodex) |
| 301 | .unwrap(); |
| 302 | proxy.provider_config_for_mut(&identity).unwrap().base_url = |
| 303 | Some("https://relay.example/v1".to_string()); |
| 304 | assert!(prepare_chatgpt_refresh(&proxy).is_err()); |
| 305 | install_test_chatgpt_roster(&account_a, &["z-first", "a-second"]).unwrap(); |
| 306 | assert_eq!( |
| 307 | model_roster_for(&account_a).model_ids(), |
| 308 | ["z-first", "a-second"] |
| 309 | ); |
| 310 | assert!(legacy_path.exists()); |
| 311 | |
| 312 | let mut account_b = Config::default(); |
| 313 | codewhale_runtime::oauth::install_test_chatgpt_registration_for( |
| 314 | &mut account_b, |
| 315 | "account-b", |
| 316 | "oaiapp_workspace_a", |
| 317 | ) |
| 318 | .unwrap(); |
| 319 | assert_ne!(snapshot_path(&account_b).unwrap(), path_a); |
| 320 | assert_eq!( |
| 321 | model_roster_for(&account_b).freshness, |
| 322 | CodexModelCacheFreshness::Missing |
| 323 | ); |
| 324 | install_test_chatgpt_roster(&account_b, &["b-only"]).unwrap(); |
| 325 | assert_eq!(model_roster_for(&account_b).model_ids(), ["b-only"]); |
| 326 | assert_eq!( |
| 327 | model_roster_for(&account_a).model_ids(), |
| 328 | ["z-first", "a-second"] |
| 329 | ); |
| 330 | |
| 331 | let mut workspace_b = Config::default(); |
| 332 | codewhale_runtime::oauth::install_test_chatgpt_registration_for( |
| 333 | &mut workspace_b, |
| 334 | "account-a", |
| 335 | "oaiapp_workspace_b", |
| 336 | ) |
| 337 | .unwrap(); |
| 338 | assert!(model_roster_for(&workspace_b).models.is_empty()); |
| 339 | let generation = account_a |
| 340 | .provider_config_for(&account_a.test_identity_for_kind(ProviderKind::OpenaiCodex)) |
| 341 | .unwrap() |
| 342 | .oauth_credential_generation |
| 343 | .as_ref() |
| 344 | .unwrap() |
| 345 | .clone(); |
| 346 | let path = codewhale_config::chatgpt_oauth_generation_path(&generation).unwrap(); |
| 347 | std::fs::remove_file(path).unwrap(); |
| 348 | assert!(model_roster_for(&account_a).models.is_empty()); |
| 349 | assert!(path_a.exists()); |
| 350 | assert_eq!(model_roster_for(&account_b).model_ids(), ["b-only"]); |
| 351 | assert!(roster_needs_refresh(&model_roster_for(&account_b))); |
| 352 | codewhale_runtime::codex_model_roster::install_test_chatgpt_roster_with_metadata( |
| 353 | &account_b, |
| 354 | vec![CodexModelMetadata { |
| 355 | id: "gpt-6.2-sol".to_string(), |
| 356 | display_name: Some("GPT-6.2-Sol".to_string()), |
| 357 | context_window: Some(500_000), |
| 358 | reasoning: Some(true), |
| 359 | efforts: vec!["low".to_string(), "high".to_string()], |
| 360 | }], |
| 361 | ) |
| 362 | .unwrap(); |
| 363 | assert!(!roster_needs_refresh(&model_roster_for(&account_b))); |
| 364 | } |
| 365 | } |
| 366 |