Repository navigation
Expand file tree
/
Copy pathmanager.rs
More file actions
923 lines (846 loc) · 32.8 KB
/
Copy pathmanager.rs
File metadata and controls
923 lines (846 loc) · 32.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
use super::cache::FileModelsCache;
use crate::cache::ModelsCache;
use crate::cache::ModelsCacheEntry;
use crate::collaboration_mode_presets::builtin_collaboration_mode_presets;
use crate::config::ModelsManagerConfig;
use crate::model_info;
use chrono::DateTime;
use chrono::Utc;
use codex_http_client::HttpClientFactory;
use codex_login::AuthManager;
use codex_protocol::auth::AuthMode;
use codex_protocol::config_types::CollaborationModeMask;
use codex_protocol::error::Result as CoreResult;
use codex_protocol::openai_models::ModelInfo;
use codex_protocol::openai_models::ModelPreset;
use codex_protocol::openai_models::ModelVisibility;
use codex_protocol::openai_models::ModelsResponse;
use std::fmt;
use std::future::Future;
use std::path::PathBuf;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use std::time::Duration;
use tokio::sync::Mutex;
use tokio::sync::MutexGuard;
use tokio::sync::RwLock;
use tokio::sync::TryLockError;
use tracing::Instrument as _;
use tracing::error;
use tracing::info;
const MODEL_CACHE_FILE: &str = "models_cache.json";
const DEFAULT_MODEL_CACHE_TTL: Duration = Duration::from_secs(300);
/// Remote endpoint used by the OpenAI-compatible model manager.
///
/// Implementations own provider-specific auth and transport details. The model
/// manager owns refresh policy, cache behavior, and catalog merging; it calls
/// this endpoint only when it decides a remote refresh should happen.
pub trait ModelsEndpointClient: fmt::Debug + Send + Sync {
/// Opaque identity of the current provider and credentials, without resolving auth.
///
/// Must change when account, email, plan, provider, or API credentials change.
/// Return `None` when identity is unavailable; cached catalog reuse is then disabled.
fn identity(&self) -> Option<String>;
/// Returns whether this provider can authenticate command-scoped requests.
fn has_command_auth(&self) -> bool;
/// Returns whether the currently resolved auth can use Codex backend-only models.
fn uses_codex_backend(&self) -> ModelsEndpointFuture<'_, bool>;
/// Returns whether this provider supports an authoritative catalog with OpenAI API keys.
fn supports_api_key_models(&self) -> bool {
false
}
/// Returns whether explicit provider configuration supplies API-key authentication.
/// This takes precedence over any unrelated first-party login used by the picker.
fn has_provider_api_key(&self) -> bool {
false
}
/// Fetches the latest remote model catalog and optional ETag.
fn list_models<'a>(
&'a self,
client_version: &'a str,
http_client_factory: HttpClientFactory,
) -> ModelsEndpointFuture<'a, CoreResult<ModelsEndpointResponse>>;
}
/// Catalog and validation metadata captured using the credentials for one request.
#[derive(Debug)]
pub struct ModelsEndpointResponse {
pub models: Vec<ModelInfo>,
pub etag: Option<String>,
/// Identity of the credentials actually used to fetch this catalog.
/// Successful responses must always identify their provider and authentication scope.
pub identity: String,
}
pub type ModelsEndpointFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
/// Strategy for refreshing available models.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RefreshStrategy {
/// Always fetch from the network, ignoring cache.
Online,
/// Only use cached data, never fetch from the network.
Offline,
/// Use cache if available and fresh, otherwise fetch from the network.
OnlineIfUncached,
}
impl RefreshStrategy {
const fn as_str(self) -> &'static str {
match self {
Self::Online => "online",
Self::Offline => "offline",
Self::OnlineIfUncached => "online_if_uncached",
}
}
}
impl fmt::Display for RefreshStrategy {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
type SharedModelsEndpointClient = Arc<dyn ModelsEndpointClient>;
/// Coordinates model discovery plus cached metadata on disk.
pub trait ModelsManager: fmt::Debug + Send + Sync {
/// Supply startup API-key discovery policy; live changes require a new session.
/// Static catalogs ignore this setting.
fn set_api_key_model_discovery_enabled(&self, _enabled: bool) {}
/// List all available models, refreshing according to the specified strategy.
///
/// Returns model presets sorted by priority and filtered by auth mode and visibility.
fn list_models(
&self,
refresh_strategy: RefreshStrategy,
http_client_factory: HttpClientFactory,
) -> ModelsManagerFuture<'_, Vec<ModelPreset>> {
Box::pin(
async move {
let catalog = self
.raw_model_catalog(refresh_strategy, http_client_factory)
.await;
self.build_available_models(catalog.models)
}
.instrument(tracing::info_span!(
"list_models",
refresh_strategy = %refresh_strategy
)),
)
}
/// Return the active raw model catalog, refreshing according to the specified strategy.
fn raw_model_catalog(
&self,
refresh_strategy: RefreshStrategy,
http_client_factory: HttpClientFactory,
) -> ModelsManagerFuture<'_, ModelsResponse>;
/// Best-effort refresh when the in-memory catalog belongs to different credentials.
/// Static catalogs need no refresh. Failures follow the catalog's fallback policy.
fn refresh_after_auth_change(
&self,
_http_client_factory: HttpClientFactory,
) -> ModelsManagerFuture<'_, ()> {
Box::pin(std::future::ready(()))
}
/// Return the current in-memory remote model catalog without refreshing or loading cache state.
fn get_remote_models(&self) -> ModelsManagerFuture<'_, Vec<ModelInfo>>;
/// Attempt to return the current in-memory remote model catalog without blocking.
///
/// Returns an error if the internal lock cannot be acquired.
fn try_get_remote_models(&self) -> Result<Vec<ModelInfo>, TryLockError>;
/// Return the auth manager used for picker filtering.
fn auth_manager(&self) -> Option<&AuthManager>;
/// 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);
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);
presets = ModelPreset::filter_by_auth(presets, uses_codex_backend);
ModelPreset::mark_default_by_picker_visibility(&mut presets);
presets
}
/// List collaboration mode presets.
///
/// Returns a static set of presets seeded with the configured model.
fn list_collaboration_modes(&self) -> Vec<CollaborationModeMask>;
/// Attempt to list models without blocking, using the current cached state.
///
/// Returns an error if the internal lock cannot be acquired.
fn try_list_models(&self) -> Result<Vec<ModelPreset>, TryLockError> {
let remote_models = self.try_get_remote_models()?;
Ok(self.build_available_models(remote_models))
}
// todo(aibrahim): should be visible to core only and sent on session_configured event
/// Get the model identifier to use, refreshing according to the specified strategy.
///
/// If `model` is provided, preserves it unless the implementation supports and the policy
/// allows provider fallback. Otherwise selects the default based on auth mode and available
/// models.
fn get_default_model<'a>(
&'a self,
model: &'a Option<String>,
allow_provider_model_fallback: bool,
refresh_strategy: RefreshStrategy,
http_client_factory: HttpClientFactory,
) -> ModelsManagerFuture<'a, String> {
Box::pin(
async move {
if let Some(model) = model.as_ref() {
return model.to_string();
}
default_model_from_available(
self.list_models(refresh_strategy, http_client_factory)
.await,
)
}
.instrument(tracing::info_span!(
"get_default_model",
model.provided = model.is_some(),
allow_provider_model_fallback,
refresh_strategy = %refresh_strategy
)),
)
}
// todo(aibrahim): look if we can tighten it to pub(crate)
/// Look up model metadata, applying remote overrides and config adjustments.
fn get_model_info<'a>(
&'a self,
model: &'a str,
config: &'a ModelsManagerConfig,
) -> ModelsManagerFuture<'a, ModelInfo> {
Box::pin(
async move {
let remote_models = self.get_remote_models().await;
construct_model_info_from_candidates(model, &remote_models, config)
}
.instrument(tracing::info_span!("get_model_info", model = model)),
)
}
/// Refresh models if the provided ETag differs from the cached ETag.
///
/// Uses `Online` strategy to fetch latest models when ETags differ.
fn refresh_if_new_etag(
&self,
etag: String,
http_client_factory: HttpClientFactory,
) -> ModelsManagerFuture<'_, ()>;
}
pub type ModelsManagerFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
/// Shared model manager handle used across runtime services.
pub type SharedModelsManager = Arc<dyn ModelsManager>;
/// Only explicit catalogs serialize refresh and suppress bundled fallback. Auth and discovery
/// settings are still evaluated when models are requested.
#[derive(Debug)]
enum CatalogSource {
Default,
ExplicitProvider(Mutex<()>),
}
impl CatalogSource {
fn fallback_models(&self) -> Option<Vec<ModelInfo>> {
match self {
Self::Default => Some(load_remote_models_from_file().unwrap_or_default()),
Self::ExplicitProvider(_) => None,
}
}
async fn refresh_lock(&self) -> Option<MutexGuard<'_, ()>> {
match self {
Self::Default => None,
Self::ExplicitProvider(lock) => Some(lock.lock().await),
}
}
}
/// OpenAI-compatible model manager backed by bundled models, cache, and `/models`.
#[derive(Debug)]
pub struct OpenAiModelsManager {
remote_models: RwLock<ModelsCacheEntry>,
cache: Option<Arc<dyn ModelsCache>>,
endpoint_client: SharedModelsEndpointClient,
catalog_source: CatalogSource,
api_key_model_discovery_enabled: AtomicBool,
auth_manager: Option<Arc<AuthManager>>,
}
/// Static model manager backed by an authoritative in-process catalog.
#[derive(Debug)]
pub struct StaticModelsManager {
remote_models: Vec<ModelInfo>,
auth_manager: Option<Arc<AuthManager>>,
}
impl OpenAiModelsManager {
/// Construct an OpenAI-compatible remote model manager.
pub fn new(
codex_home: PathBuf,
endpoint_client: Arc<dyn ModelsEndpointClient>,
auth_manager: Option<Arc<AuthManager>>,
) -> Self {
let cache_path = codex_home.join(MODEL_CACHE_FILE);
Self::new_with_optional_cache(
Some(Arc::new(FileModelsCache::new(
cache_path,
DEFAULT_MODEL_CACHE_TTL,
))),
endpoint_client,
auth_manager,
)
}
/// Construct an OpenAI-compatible model manager with caching disabled.
pub fn new_without_cache(
endpoint_client: Arc<dyn ModelsEndpointClient>,
auth_manager: Option<Arc<AuthManager>>,
) -> Self {
Self::new_with_optional_cache(/*cache*/ None, endpoint_client, auth_manager)
}
/// Constructs an OpenAI-compatible model manager with a caller-provided cache.
///
/// The cache is consulted by cache-aware refresh strategies. Cache misses and backend errors
/// fall back to the models endpoint, and cache write failures do not fail model discovery.
pub fn new_with_cache(
cache: Arc<dyn ModelsCache>,
endpoint_client: Arc<dyn ModelsEndpointClient>,
auth_manager: Option<Arc<AuthManager>>,
) -> Self {
Self::new_with_optional_cache(Some(cache), endpoint_client, auth_manager)
}
fn new_with_optional_cache(
cache: Option<Arc<dyn ModelsCache>>,
endpoint_client: Arc<dyn ModelsEndpointClient>,
auth_manager: Option<Arc<AuthManager>>,
) -> Self {
Self {
remote_models: RwLock::new(ModelsCacheEntry {
fetched_at: Utc::now(),
etag: None,
client_version: Some(crate::client_version_to_whole()),
identity: endpoint_client.identity(),
models: load_remote_models_from_file().unwrap_or_default(),
}),
cache,
api_key_model_discovery_enabled: AtomicBool::new(false),
endpoint_client,
catalog_source: CatalogSource::Default,
auth_manager,
}
}
/// Configure a newly constructed manager to use only the provider's explicit catalog.
/// Clear the bundled seed before sharing it; the existing auth identity must be retained.
pub fn with_provider_catalog(mut self) -> Self {
self.catalog_source = CatalogSource::ExplicitProvider(Mutex::new(()));
self.remote_models.get_mut().models.clear();
self
}
}
impl StaticModelsManager {
/// Construct a static model manager from an authoritative catalog.
pub fn new(auth_manager: Option<Arc<AuthManager>>, model_catalog: ModelsResponse) -> Self {
Self {
remote_models: model_catalog.models,
auth_manager,
}
}
}
impl ModelsManager for OpenAiModelsManager {
fn set_api_key_model_discovery_enabled(&self, enabled: bool) {
self.api_key_model_discovery_enabled
.store(enabled, Ordering::SeqCst);
}
fn raw_model_catalog(
&self,
refresh_strategy: RefreshStrategy,
http_client_factory: HttpClientFactory,
) -> ModelsManagerFuture<'_, ModelsResponse> {
Box::pin(OpenAiModelsManager::raw_model_catalog(
self,
refresh_strategy,
http_client_factory,
))
}
fn refresh_after_auth_change(
&self,
http_client_factory: HttpClientFactory,
) -> ModelsManagerFuture<'_, ()> {
Box::pin(async move {
let refresh = async {
// Resolve lazy command credentials before comparing catalog identities.
if !self.should_refresh_models().await {
return Ok(());
}
let identity = self.endpoint_client.identity();
if identity.is_some() && self.remote_models.read().await.identity == identity {
return Ok(());
}
self.refresh_available_models(
RefreshStrategy::OnlineIfUncached,
&http_client_factory,
)
.await
};
// Include auth resolution and cache access in the best-effort deadline.
if !matches!(
tokio::time::timeout(Duration::from_secs(/*secs*/ 5), refresh).await,
Ok(Ok(()))
) {
tracing::warn!("model catalog refresh after auth change failed or timed out");
}
})
}
fn get_remote_models(&self) -> ModelsManagerFuture<'_, Vec<ModelInfo>> {
Box::pin(async move {
let entry = self.remote_models.read().await;
if entry.identity.is_some() && entry.identity == self.endpoint_client.identity() {
entry.models.clone()
} else {
self.catalog_source.fallback_models().unwrap_or_default()
}
})
}
fn try_get_remote_models(&self) -> Result<Vec<ModelInfo>, TryLockError> {
let entry = self.remote_models.try_read()?;
Ok(
if entry.identity.is_some() && entry.identity == self.endpoint_client.identity() {
entry.models.clone()
} else {
self.catalog_source.fallback_models().unwrap_or_default()
},
)
}
fn auth_manager(&self) -> Option<&AuthManager> {
self.auth_manager.as_deref()
}
#[tracing::instrument(skip_all, fields(model))]
fn get_model_info<'a>(
&'a self,
model: &'a str,
config: &'a ModelsManagerConfig,
) -> ModelsManagerFuture<'a, ModelInfo> {
Box::pin(async move {
let models = self.get_remote_models().await;
match &self.catalog_source {
CatalogSource::Default => {
construct_model_info_from_candidates(model, &models, config)
}
CatalogSource::ExplicitProvider(_) => construct_model_info(
model,
models.into_iter().find(|candidate| candidate.slug == model),
config,
),
}
})
}
fn list_collaboration_modes(&self) -> Vec<CollaborationModeMask> {
builtin_collaboration_mode_presets()
}
fn refresh_if_new_etag(
&self,
etag: String,
http_client_factory: HttpClientFactory,
) -> ModelsManagerFuture<'_, ()> {
Box::pin(OpenAiModelsManager::refresh_if_new_etag(
self,
etag,
http_client_factory,
))
}
}
impl OpenAiModelsManager {
async fn raw_model_catalog(
&self,
refresh_strategy: RefreshStrategy,
http_client_factory: HttpClientFactory,
) -> ModelsResponse {
if let Err(err) = self
.refresh_available_models(refresh_strategy, &http_client_factory)
.await
{
error!("failed to refresh available models: {err}");
}
ModelsResponse {
models: self.get_remote_models().await,
}
}
async fn refresh_if_new_etag(&self, etag: String, http_client_factory: HttpClientFactory) {
let refresh_guard = self.catalog_source.refresh_lock().await;
let (identity, current_etag) = {
let entry = self.remote_models.read().await;
(entry.identity.clone(), entry.etag.clone())
};
if let Some(identity) = identity
&& Some(&identity) == self.endpoint_client.identity().as_ref()
&& current_etag.as_deref() == Some(etag.as_str())
{
if let Some(cache) = self.cache.as_ref()
&& let Err(err) = cache
.refresh_ttl(&crate::client_version_to_whole(), &identity, &etag)
.await
{
error!("failed to renew cache TTL: {err}");
}
return;
}
drop(refresh_guard);
if let Err(err) = self
.refresh_available_models(RefreshStrategy::Online, &http_client_factory)
.await
{
error!("failed to refresh available models: {err}");
}
}
/// Refresh available models according to the specified strategy.
async fn refresh_available_models(
&self,
refresh_strategy: RefreshStrategy,
http_client_factory: &HttpClientFactory,
) -> CoreResult<()> {
let _refresh_guard = self.catalog_source.refresh_lock().await;
// API-key discovery must be enabled and supported before reusing a remote catalog.
// Otherwise even a matching cache from an earlier run would bypass bundled-only behavior.
// Command-auth providers retain their existing discovery behavior.
if self.uses_api_key_auth()
&& !self.endpoint_client.has_command_auth()
&& (!self.endpoint_client.supports_api_key_models()
|| !self.api_key_model_discovery_enabled.load(Ordering::SeqCst))
{
return Ok(());
}
if !self.should_refresh_models().await {
if matches!(
refresh_strategy,
RefreshStrategy::Offline | RefreshStrategy::OnlineIfUncached
) {
self.try_load_cache().await;
}
return Ok(());
}
match refresh_strategy {
RefreshStrategy::Offline => {
self.try_load_cache().await;
Ok(())
}
RefreshStrategy::OnlineIfUncached => {
if self.try_load_cache().await {
return Ok(());
}
self.fetch_and_update_models(http_client_factory).await
}
RefreshStrategy::Online => self.fetch_and_update_models(http_client_factory).await,
}
}
async fn fetch_and_update_models(
&self,
http_client_factory: &HttpClientFactory,
) -> CoreResult<()> {
let client_version = crate::client_version_to_whole();
let request_identity = self.endpoint_client.identity();
let ModelsEndpointResponse {
models,
etag,
identity,
} = match self
.endpoint_client
.list_models(&client_version, http_client_factory.clone())
.await
{
Ok(response) => response,
Err(error) => {
if matches!(&self.catalog_source, CatalogSource::ExplicitProvider(_)) {
{
let mut current = self.remote_models.write().await;
if request_identity != self.endpoint_client.identity() {
return Err(error);
}
// Keep this failure in memory even if persistent invalidation fails.
current.fetched_at = DateTime::<Utc>::MIN_UTC;
current.models.clear();
current.etag = None;
current.identity.clone_from(&request_identity);
}
if let Some(identity) = request_identity
&& let Some(cache) = self.cache.as_ref()
{
let invalidation = async {
if let Some(mut entry) = cache.load(&client_version).await?
&& entry.identity.as_deref() == Some(&identity)
&& entry.client_version.as_deref() == Some(&client_version)
{
// Preserve backend lookup keys, but force a cache miss after restart.
entry.fetched_at = DateTime::<Utc>::MIN_UTC;
entry.etag = None;
entry.models.clear();
cache.store(&entry).await?;
}
Ok::<_, crate::cache::ModelsCacheError>(())
};
if let Err(err) = invalidation.await {
error!("failed to invalidate models cache: {err}");
}
}
}
return Err(error);
}
};
if Some(&identity) != self.endpoint_client.identity().as_ref() {
return Ok(());
}
let entry = ModelsCacheEntry {
fetched_at: Utc::now(),
etag,
client_version: Some(client_version),
identity: Some(identity),
models,
};
if let Some(cache) = self.cache.as_ref()
&& let Err(err) = cache.store(&entry).await
{
error!("failed to write models cache: {err}");
}
self.apply_remote_models(entry).await;
Ok(())
}
fn supports_api_key_discovery(&self) -> bool {
self.endpoint_client.supports_api_key_models()
&& !self.endpoint_client.has_command_auth()
&& self.uses_api_key_auth()
}
fn uses_api_key_auth(&self) -> bool {
self.endpoint_client.has_provider_api_key()
|| self
.auth_manager
.as_ref()
.is_some_and(|auth_manager| auth_manager.auth_mode() == Some(AuthMode::ApiKey))
}
async fn should_refresh_models(&self) -> bool {
self.endpoint_client.uses_codex_backend().await
|| self.endpoint_client.has_command_auth()
|| self.supports_api_key_discovery()
}
/// Publish only while the request identity still matches, including after async storage.
async fn apply_remote_models(&self, mut entry: ModelsCacheEntry) -> bool {
let mut current = self.remote_models.write().await;
if entry.identity != self.endpoint_client.identity() {
return false;
}
let remote_only = entry
.models
.iter()
.any(|model| model.visibility == ModelVisibility::List)
&& (self.supports_api_key_discovery()
|| self.auth_manager.as_ref().is_some_and(|auth_manager| {
auth_manager
.auth_mode()
.is_some_and(AuthMode::has_chatgpt_account)
}));
if !remote_only && let Some(mut models) = self.catalog_source.fallback_models() {
for model in entry.models {
if let Some(index) = models
.iter()
.position(|existing| existing.slug == model.slug)
{
models[index] = model;
} else {
models.push(model);
}
}
entry.models = models;
}
*current = entry;
true
}
/// Attempt to satisfy the refresh from the cache when it matches the provider and TTL.
async fn try_load_cache(&self) -> bool {
let Some(cache) = self.cache.as_ref() else {
return false;
};
let _timer =
codex_otel::start_global_timer("codex.remote_models.load_cache.duration_ms", &[]);
let client_version = crate::client_version_to_whole();
info!(client_version, "models cache: evaluating cache eligibility");
let Some(identity) = self.endpoint_client.identity() else {
return false;
};
{
let current = self.remote_models.read().await;
// A failed fetch must not be replaced by stale cache data even if invalidation failed.
if current.fetched_at == DateTime::<Utc>::MIN_UTC
&& current.identity.as_ref() == Some(&identity)
{
return false;
}
}
let cache_entry = match cache.load(&client_version).await {
Ok(Some(cache_entry)) => cache_entry,
Ok(None) => {
info!("models cache: no usable cache entry");
return false;
}
Err(err) => {
error!("failed to load models cache: {err}");
return false;
}
};
if cache_entry.fetched_at == DateTime::<Utc>::MIN_UTC {
return false;
}
if cache_entry.client_version.as_deref() != Some(client_version.as_str()) {
info!(
expected_version = client_version,
cached_version = ?cache_entry.client_version,
"models cache: cache version mismatch"
);
return false;
}
if cache_entry.identity.as_ref() != Some(&identity)
|| self.endpoint_client.identity().as_ref() != Some(&identity)
{
info!("models cache: provider or auth identity mismatch");
return false;
}
self.apply_remote_models(cache_entry).await
}
}
impl ModelsManager for StaticModelsManager {
fn get_default_model<'a>(
&'a self,
model: &'a Option<String>,
allow_provider_model_fallback: bool,
refresh_strategy: RefreshStrategy,
http_client_factory: HttpClientFactory,
) -> ModelsManagerFuture<'a, String> {
Box::pin(
async move {
let available_models = self
.list_models(refresh_strategy, http_client_factory)
.await;
let requested_model = model.as_deref();
if allow_provider_model_fallback {
if requested_model_is_available(requested_model, &available_models)
&& let Some(requested_model) = requested_model
{
return requested_model.to_string();
}
return default_model_from_available(available_models);
}
model
.clone()
.unwrap_or_else(|| default_model_from_available(available_models))
}
.instrument(tracing::info_span!(
"get_default_model",
model.provided = model.is_some(),
allow_provider_model_fallback,
refresh_strategy = %refresh_strategy
)),
)
}
fn raw_model_catalog(
&self,
_refresh_strategy: RefreshStrategy,
_http_client_factory: HttpClientFactory,
) -> ModelsManagerFuture<'_, ModelsResponse> {
Box::pin(async move {
ModelsResponse {
models: self.get_remote_models().await,
}
})
}
fn get_remote_models(&self) -> ModelsManagerFuture<'_, Vec<ModelInfo>> {
Box::pin(async { self.remote_models.clone() })
}
fn try_get_remote_models(&self) -> Result<Vec<ModelInfo>, TryLockError> {
Ok(self.remote_models.clone())
}
fn auth_manager(&self) -> Option<&AuthManager> {
self.auth_manager.as_deref()
}
fn list_collaboration_modes(&self) -> Vec<CollaborationModeMask> {
builtin_collaboration_mode_presets()
}
fn refresh_if_new_etag(
&self,
_etag: String,
_http_client_factory: HttpClientFactory,
) -> ModelsManagerFuture<'_, ()> {
Box::pin(async {})
}
}
fn load_remote_models_from_file() -> Result<Vec<ModelInfo>, std::io::Error> {
Ok(crate::bundled_models_response()?.models)
}
fn default_model_from_available(available: Vec<ModelPreset>) -> String {
available
.iter()
.find(|model| model.is_default)
.or_else(|| available.first())
.map(|model| model.model.clone())
.unwrap_or_default()
}
fn requested_model_is_available(
requested_model: Option<&str>,
available_models: &[ModelPreset],
) -> bool {
requested_model.is_some_and(|requested_model| {
available_models
.iter()
.any(|available_model| available_model.model == requested_model)
})
}
fn find_model_by_longest_prefix(model: &str, candidates: &[ModelInfo]) -> Option<ModelInfo> {
let mut best: Option<ModelInfo> = None;
for candidate in candidates {
if !model.starts_with(&candidate.slug) {
continue;
}
let is_better_match = if let Some(current) = best.as_ref() {
candidate.slug.len() > current.slug.len()
} else {
true
};
if is_better_match {
best = Some(candidate.clone());
}
}
best
}
fn find_model_by_namespaced_suffix(model: &str, candidates: &[ModelInfo]) -> Option<ModelInfo> {
// Retry metadata lookup for a single namespaced slug like `namespace/model-name`.
//
// This only strips one leading namespace segment and only when the namespace looks
// like a simple provider id to avoid broadly matching arbitrary aliases.
let (namespace, suffix) = model.split_once('/')?;
if suffix.contains('/') {
return None;
}
if namespace.is_empty()
|| !namespace
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
{
return None;
}
find_model_by_longest_prefix(suffix, candidates)
}
pub(crate) fn construct_model_info_from_candidates(
model: &str,
candidates: &[ModelInfo],
config: &ModelsManagerConfig,
) -> ModelInfo {
// First use the normal longest-prefix match. If that misses, allow a narrowly scoped
// retry for namespaced slugs like `custom/gpt-5.3-codex`.
let remote = find_model_by_longest_prefix(model, candidates)
.or_else(|| find_model_by_namespaced_suffix(model, candidates));
construct_model_info(model, remote, config)
}
fn construct_model_info(
model: &str,
remote: Option<ModelInfo>,
config: &ModelsManagerConfig,
) -> ModelInfo {
let model_info = if let Some(remote) = remote {
ModelInfo {
slug: model.to_string(),
used_fallback_model_metadata: false,
..remote
}
} else {
model_info::model_info_from_slug(model)
};
model_info::with_config_overrides(model_info, config)
}
#[cfg(test)]
#[path = "manager_tests.rs"]
mod tests;