forked from Dicklesworthstone/pi_agent_rust
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodels.rs
More file actions
4810 lines (4416 loc) · 176 KB
/
models.rs
File metadata and controls
4810 lines (4416 loc) · 176 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
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Model registry: built-in + models.json overrides.
use crate::auth::{AuthStorage, SapResolvedCredentials, resolve_sap_credentials};
use crate::error::Error;
use crate::provider::{Api, InputType, Model, ModelCost};
use crate::provider_metadata::{
ProviderRoutingDefaults, canonical_provider_id, provider_routing_defaults,
};
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::OnceLock;
#[derive(Debug, Clone)]
pub struct ModelEntry {
pub model: Model,
pub api_key: Option<String>,
pub headers: HashMap<String, String>,
pub auth_header: bool,
pub compat: Option<CompatConfig>,
/// OAuth config for extension-registered providers that require browser-based auth.
pub oauth_config: Option<OAuthConfig>,
}
impl ModelEntry {
/// Whether this model supports xhigh thinking level.
pub fn supports_xhigh(&self) -> bool {
matches!(
self.model.id.as_str(),
"gpt-5.1-codex-max"
| "gpt-5.2"
| "gpt-5.5"
| "gpt-5.4"
| "gpt-5.2-codex"
| "gpt-5.3-codex"
| "gpt-5.3-codex-spark"
)
}
/// Return the thinking levels that should be exposed for this model.
pub fn available_thinking_levels(&self) -> Vec<crate::model::ThinkingLevel> {
use crate::model::ThinkingLevel;
if !self.model.reasoning {
return vec![ThinkingLevel::Off];
}
let mut levels = vec![
ThinkingLevel::Off,
ThinkingLevel::Minimal,
ThinkingLevel::Low,
ThinkingLevel::Medium,
ThinkingLevel::High,
];
if self.supports_xhigh() {
levels.push(ThinkingLevel::XHigh);
}
levels
}
/// Clamp a requested thinking level to the model's capabilities.
///
/// Non-reasoning models always return `Off`. Models without xhigh support
/// downgrade `XHigh` to `High`. All other levels pass through unchanged.
pub fn clamp_thinking_level(
&self,
thinking: crate::model::ThinkingLevel,
) -> crate::model::ThinkingLevel {
if !self.model.reasoning {
return crate::model::ThinkingLevel::Off;
}
if thinking == crate::model::ThinkingLevel::XHigh && !self.supports_xhigh() {
return crate::model::ThinkingLevel::High;
}
thinking
}
}
/// OAuth configuration for extension-registered providers.
#[derive(Debug, Clone)]
pub struct OAuthConfig {
pub auth_url: String,
pub token_url: String,
pub client_id: String,
pub scopes: Vec<String>,
pub redirect_uri: Option<String>,
}
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ModelsConfig {
pub providers: HashMap<String, ProviderConfig>,
}
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ProviderConfig {
pub base_url: Option<String>,
pub api: Option<String>,
pub api_key: Option<String>,
pub headers: Option<HashMap<String, String>>,
pub auth_header: Option<bool>,
pub compat: Option<CompatConfig>,
pub models: Option<Vec<ModelConfig>>,
}
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ModelConfig {
pub id: String,
pub name: Option<String>,
pub api: Option<String>,
pub reasoning: Option<bool>,
pub input: Option<Vec<String>>,
pub cost: Option<ModelCost>,
pub context_window: Option<u32>,
pub max_tokens: Option<u32>,
pub headers: Option<HashMap<String, String>>,
pub compat: Option<CompatConfig>,
}
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CompatConfig {
// ── Capability flags ────────────────────────────────────────────────
pub supports_store: Option<bool>,
pub supports_developer_role: Option<bool>,
pub supports_reasoning_effort: Option<bool>,
pub supports_usage_in_streaming: Option<bool>,
pub supports_tools: Option<bool>,
pub supports_streaming: Option<bool>,
pub supports_parallel_tool_calls: Option<bool>,
// ── Request field overrides ─────────────────────────────────────────
/// Override the JSON field name for `max_tokens` (e.g., `"max_completion_tokens"` for o1).
pub max_tokens_field: Option<String>,
/// Override the system message role name (e.g., `"developer"` for some providers).
pub system_role_name: Option<String>,
/// Override the stop-reason field name in responses.
pub stop_reason_field: Option<String>,
// ── Per-provider request headers ────────────────────────────────────
/// Extra HTTP headers injected into every request for this provider.
/// Applied after default headers but before per-request `StreamOptions.headers`.
pub custom_headers: Option<HashMap<String, String>>,
// ── Gateway/routing metadata ────────────────────────────────────────
pub open_router_routing: Option<serde_json::Value>,
pub vercel_gateway_routing: Option<serde_json::Value>,
}
#[derive(Debug, Clone)]
pub struct ModelRegistry {
models: Vec<ModelEntry>,
error: Option<String>,
}
#[derive(Debug, Clone)]
pub struct ModelAutocompleteCandidate {
pub slug: String,
pub description: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
struct LegacyGeneratedModel {
id: String,
name: String,
api: String,
provider: String,
#[serde(default)]
base_url: String,
#[serde(default)]
reasoning: bool,
#[serde(default)]
input: Vec<String>,
#[serde(default)]
cost: Option<ModelCost>,
#[serde(default)]
context_window: Option<u32>,
#[serde(default)]
max_tokens: Option<u32>,
#[serde(default)]
headers: HashMap<String, String>,
#[serde(default)]
compat: Option<CompatConfig>,
}
const LEGACY_MODELS_GENERATED_TS: &str =
include_str!("../legacy_pi_mono_code/pi-mono/packages/ai/src/models.generated.ts");
const UPSTREAM_PROVIDER_MODEL_IDS_JSON: &str =
include_str!("../docs/provider-upstream-model-ids-snapshot.json");
const CODEX_RESPONSES_API_URL: &str = "https://chatgpt.com/backend-api/codex/responses";
const GOOGLE_GEMINI_CLI_API_URL: &str = "https://cloudcode-pa.googleapis.com";
const GOOGLE_ANTIGRAVITY_API_URL: &str = "https://daily-cloudcode-pa.sandbox.googleapis.com";
static LEGACY_GENERATED_MODELS_CACHE: OnceLock<Vec<LegacyGeneratedModel>> = OnceLock::new();
static UPSTREAM_PROVIDER_MODEL_IDS_CACHE: OnceLock<HashMap<String, Vec<String>>> = OnceLock::new();
static MODEL_AUTOCOMPLETE_CACHE: OnceLock<Vec<ModelAutocompleteCandidate>> = OnceLock::new();
static MODEL_CATALOG_CACHE_FINGERPRINT: OnceLock<u64> = OnceLock::new();
static SATISFIES_RE: OnceLock<Regex> = OnceLock::new();
const INPUT_TEXT_ONLY: [InputType; 1] = [InputType::Text];
const INPUT_TEXT_AND_IMAGE: [InputType; 2] = [InputType::Text, InputType::Image];
fn canonicalize_openrouter_model_id(model_id: &str) -> String {
let trimmed = model_id.trim();
match trimmed.to_ascii_lowercase().as_str() {
"auto" => "openrouter/auto".to_string(),
"gpt-4o-mini" => "openai/gpt-4o-mini".to_string(),
"gpt-4o" => "openai/gpt-4o".to_string(),
"claude-3.5-sonnet" => "anthropic/claude-3.5-sonnet".to_string(),
"gemini-2.5-pro" => "google/gemini-2.5-pro".to_string(),
_ => trimmed.to_string(),
}
}
fn canonicalize_model_id_for_provider(provider: &str, model_id: &str) -> String {
if canonical_provider_id(provider).is_some_and(|canonical| canonical == "openrouter") {
return canonicalize_openrouter_model_id(model_id);
}
model_id.trim().to_string()
}
fn normalized_registry_key(provider: &str, model_id: &str) -> (String, String) {
let provider = provider.trim();
let canonical_provider = canonical_provider_id(provider).unwrap_or(provider);
let canonical_model_id = canonicalize_model_id_for_provider(canonical_provider, model_id);
(
canonical_provider.to_ascii_lowercase(),
canonical_model_id.to_ascii_lowercase(),
)
}
fn openrouter_model_lookup_ids(model_id: &str) -> Vec<String> {
let raw = model_id.trim().to_string();
let canonical = canonicalize_openrouter_model_id(model_id);
if canonical.eq_ignore_ascii_case(&raw) {
vec![canonical]
} else {
vec![raw, canonical]
}
}
fn api_fallback_base_url(api: &str) -> Option<&'static str> {
match api {
"openai-codex-responses" => Some(CODEX_RESPONSES_API_URL),
"google-gemini-cli" => Some(GOOGLE_GEMINI_CLI_API_URL),
"google-antigravity" => Some(GOOGLE_ANTIGRAVITY_API_URL),
_ => None,
}
}
fn parse_input_types(input: &[String]) -> Vec<InputType> {
input
.iter()
.filter_map(|value| match value.as_str() {
"text" => Some(InputType::Text),
"image" => Some(InputType::Image),
_ => None,
})
.collect()
}
fn legacy_generated_models_cache_path() -> Option<PathBuf> {
let checksum = crc32c::crc32c(LEGACY_MODELS_GENERATED_TS.as_bytes());
dirs::cache_dir().map(|dir| {
dir.join("pi")
.join("models-cache")
.join(format!("legacy-generated-models-{checksum:08x}.json"))
})
}
fn load_legacy_generated_models_cache() -> Option<Vec<LegacyGeneratedModel>> {
let path = legacy_generated_models_cache_path()?;
let cache = fs::read_to_string(path).ok()?;
serde_json::from_str::<Vec<LegacyGeneratedModel>>(&cache).ok()
}
fn persist_legacy_generated_models_cache(models: &[LegacyGeneratedModel]) {
let Some(path) = legacy_generated_models_cache_path() else {
return;
};
if path.exists() {
return;
}
let Some(parent) = path.parent() else {
return;
};
if fs::create_dir_all(parent).is_err() {
return;
}
let temp_path = path.with_extension(format!("tmp-{}", std::process::id()));
let Ok(file) = fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&temp_path)
else {
return;
};
let mut writer = std::io::BufWriter::new(file);
if serde_json::to_writer(&mut writer, models).is_ok() && writer.flush().is_ok() {
let _ = fs::rename(&temp_path, path);
} else {
let _ = fs::remove_file(&temp_path);
}
}
fn parse_legacy_generated_models() -> Vec<LegacyGeneratedModel> {
if let Some(cached) = load_legacy_generated_models_cache() {
return cached;
}
let Some(models_decl_start) = LEGACY_MODELS_GENERATED_TS.find("export const MODELS =") else {
tracing::warn!("Legacy model catalog missing MODELS declaration");
return Vec::new();
};
let Some(object_start_rel) = LEGACY_MODELS_GENERATED_TS[models_decl_start..].find('{') else {
tracing::warn!("Legacy model catalog missing object start after MODELS declaration");
return Vec::new();
};
let object_start = models_decl_start + object_start_rel;
let Some(end_marker_rel) = LEGACY_MODELS_GENERATED_TS[object_start..].rfind("} as const;")
else {
tracing::warn!("Legacy model catalog missing end marker");
return Vec::new();
};
let end_marker = object_start + end_marker_rel;
let mut object_source = LEGACY_MODELS_GENERATED_TS[object_start..=end_marker]
.trim_end_matches(" as const;")
.to_string();
let satisfies_re = SATISFIES_RE.get_or_init(|| {
Regex::new(r#"\s+satisfies\s+Model<"[^"]+">"#).expect("valid satisfies regex")
});
object_source = satisfies_re.replace_all(&object_source, "").into_owned();
let parsed: HashMap<String, HashMap<String, LegacyGeneratedModel>> =
match json5::from_str(&object_source) {
Ok(value) => value,
Err(err) => {
tracing::warn!(error = %err, "Failed to parse legacy model catalog");
return Vec::new();
}
};
let mut models = parsed
.into_values()
.flat_map(HashMap::into_values)
.collect::<Vec<_>>();
models.sort_by(|a, b| {
a.provider
.cmp(&b.provider)
.then_with(|| a.id.cmp(&b.id))
.then_with(|| a.api.cmp(&b.api))
});
persist_legacy_generated_models_cache(&models);
models
}
fn legacy_generated_models() -> &'static [LegacyGeneratedModel] {
LEGACY_GENERATED_MODELS_CACHE
.get_or_init(parse_legacy_generated_models)
.as_slice()
}
fn parse_upstream_provider_model_ids() -> HashMap<String, Vec<String>> {
let parsed: HashMap<String, Vec<String>> =
match serde_json::from_str(UPSTREAM_PROVIDER_MODEL_IDS_JSON) {
Ok(value) => value,
Err(err) => {
tracing::warn!(error = %err, "Failed to parse upstream provider model snapshot");
return HashMap::new();
}
};
let mut by_provider: HashMap<String, Vec<String>> = HashMap::new();
merge_provider_model_ids(&mut by_provider, parsed);
merge_provider_model_ids(&mut by_provider, parse_user_model_overrides());
for ids in by_provider.values_mut() {
ids.sort_unstable();
ids.dedup();
}
by_provider
}
fn merge_provider_model_ids(
target: &mut HashMap<String, Vec<String>>,
source: HashMap<String, Vec<String>>,
) {
for (provider, ids) in source {
let provider = provider.trim();
if provider.is_empty() {
continue;
}
let canonical_provider = canonical_provider_id(provider)
.unwrap_or(provider)
.to_string();
let entry = target.entry(canonical_provider.clone()).or_default();
for model_id in ids {
let normalized = canonicalize_model_id_for_provider(&canonical_provider, &model_id);
if !normalized.is_empty() {
entry.push(normalized);
}
}
}
}
/// Path to the user's optional model-override file.
///
/// Resolution order:
/// 1. `PI_MODELS_OVERRIDE` env var (absolute path) — primarily for tests and
/// advanced users who want to keep the override outside the standard config
/// directory.
/// 2. `<config_dir>/pi/models-override.json` — `<config_dir>` is whatever
/// `dirs::config_dir()` reports (e.g. `~/.config` on Linux,
/// `~/Library/Application Support` on macOS).
///
/// Returns `None` when no config directory can be resolved and no env override
/// is set; callers treat that as "no override available".
fn user_model_overrides_path() -> Option<PathBuf> {
if let Ok(env_path) = std::env::var("PI_MODELS_OVERRIDE") {
let trimmed = env_path.trim();
if !trimmed.is_empty() {
return Some(PathBuf::from(trimmed));
}
}
dirs::config_dir().map(|dir| dir.join("pi").join("models-override.json"))
}
/// Parse the user-supplied override file. Same shape as the bundled snapshot:
/// `{ "<provider>": ["<model-id>", ...], ... }`. Missing or unreadable files
/// are silently ignored; malformed JSON logs a warning and is treated as
/// empty so a typo in the override never breaks pi startup.
fn parse_user_model_overrides() -> HashMap<String, Vec<String>> {
user_model_overrides_path()
.map(|path| parse_user_model_overrides_at(&path))
.unwrap_or_default()
}
fn parse_user_model_overrides_at(path: &Path) -> HashMap<String, Vec<String>> {
let content = match fs::read_to_string(path) {
Ok(content) => content,
Err(err) => {
if err.kind() != std::io::ErrorKind::NotFound {
tracing::debug!(
path = %path.display(),
error = %err,
"User model override file present but unreadable; ignoring"
);
}
return HashMap::new();
}
};
if content.trim().is_empty() {
return HashMap::new();
}
match serde_json::from_str::<HashMap<String, Vec<String>>>(&content) {
Ok(value) => {
tracing::debug!(
path = %path.display(),
providers = value.len(),
"Loaded user model override file"
);
value
}
Err(err) => {
tracing::warn!(
path = %path.display(),
error = %err,
"Failed to parse pi user model override file; ignoring"
);
HashMap::new()
}
}
}
/// CRC32C of the user override file at process start, or 0 when no override
/// exists. Folded into [`model_catalog_cache_fingerprint`] so consumers that
/// memoize against the fingerprint refresh when a user changes their override.
fn user_model_overrides_fingerprint() -> u32 {
user_model_overrides_path().map_or(0, |path| user_model_overrides_fingerprint_at(&path))
}
fn user_model_overrides_fingerprint_at(path: &Path) -> u32 {
fs::read(path)
.ok()
.map_or(0, |bytes| crc32c::crc32c(&bytes))
}
fn upstream_provider_model_ids() -> &'static HashMap<String, Vec<String>> {
UPSTREAM_PROVIDER_MODEL_IDS_CACHE.get_or_init(parse_upstream_provider_model_ids)
}
pub fn model_autocomplete_candidates() -> &'static [ModelAutocompleteCandidate] {
MODEL_AUTOCOMPLETE_CACHE
.get_or_init(|| {
let mut candidates = legacy_generated_models()
.iter()
.map(|entry| ModelAutocompleteCandidate {
slug: format!("{}/{}", entry.provider, entry.id),
description: Some(entry.name.clone()).filter(|name| !name.trim().is_empty()),
})
.collect::<Vec<_>>();
for (provider, ids) in upstream_provider_model_ids() {
let provider = provider.trim();
if provider.is_empty() {
continue;
}
for id in ids {
if id.trim().is_empty() {
continue;
}
candidates.push(ModelAutocompleteCandidate {
slug: format!("{provider}/{id}"),
description: None,
});
}
}
candidates.push(ModelAutocompleteCandidate {
slug: "anthropic/claude-sonnet-4-6".to_string(),
description: Some("Claude Sonnet 4.6".to_string()),
});
candidates.push(ModelAutocompleteCandidate {
slug: "openai/gpt-5.5".to_string(),
description: Some("GPT-5.5".to_string()),
});
candidates.push(ModelAutocompleteCandidate {
slug: "openai/gpt-5.4".to_string(),
description: Some("GPT-5.4".to_string()),
});
candidates.push(ModelAutocompleteCandidate {
slug: "openai-codex/gpt-5.5".to_string(),
description: Some("GPT-5.5 Codex".to_string()),
});
candidates.push(ModelAutocompleteCandidate {
slug: "openai-codex/gpt-5.4".to_string(),
description: Some("GPT-5.4 Codex".to_string()),
});
candidates.push(ModelAutocompleteCandidate {
slug: "openai-codex/gpt-5.2-codex".to_string(),
description: Some("GPT-5.2 Codex".to_string()),
});
candidates.push(ModelAutocompleteCandidate {
slug: "google-gemini-cli/gemini-2.5-pro".to_string(),
description: Some("Gemini 2.5 Pro (CLI)".to_string()),
});
candidates.push(ModelAutocompleteCandidate {
slug: "google-antigravity/gemini-3-flash".to_string(),
description: Some("Gemini 3 Flash (Antigravity)".to_string()),
});
candidates.sort_by_key(|candidate| candidate.slug.to_ascii_lowercase());
candidates.dedup_by(|a, b| a.slug.eq_ignore_ascii_case(&b.slug));
candidates
})
.as_slice()
}
pub fn model_catalog_cache_fingerprint() -> u64 {
*MODEL_CATALOG_CACHE_FINGERPRINT.get_or_init(|| {
let legacy = u64::from(crc32c::crc32c(LEGACY_MODELS_GENERATED_TS.as_bytes()));
let upstream = u64::from(crc32c::crc32c(UPSTREAM_PROVIDER_MODEL_IDS_JSON.as_bytes()));
let user_override = u64::from(user_model_overrides_fingerprint());
// Mix the override CRC into both halves so any change forces cache
// invalidation regardless of whether the snapshot or the override
// moved.
(legacy ^ user_override) << 32 | (upstream ^ user_override)
})
}
pub(crate) fn normalize_api_key_opt(api_key: Option<String>) -> Option<String> {
api_key.and_then(|key| {
let trimmed = key.trim();
(!trimmed.is_empty()).then(|| trimmed.to_string())
})
}
pub(crate) fn model_requires_configured_credential(entry: &ModelEntry) -> bool {
let provider = entry.model.provider.as_str();
entry.auth_header
|| crate::provider_metadata::provider_metadata(provider)
.is_some_and(|meta| !meta.auth_env_keys.is_empty())
|| entry.oauth_config.is_some()
}
pub(crate) fn model_entry_is_ready(entry: &ModelEntry) -> bool {
!model_requires_configured_credential(entry)
|| entry
.api_key
.as_ref()
.is_some_and(|value| !value.trim().is_empty())
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ModelRegistryLoadMode {
Full,
ListingLite,
}
impl ModelRegistry {
#[cfg(test)]
pub(crate) fn from_entries_for_tests(entries: Vec<ModelEntry>) -> Self {
Self {
models: entries,
error: None,
}
}
pub fn load(auth: &AuthStorage, models_path: Option<PathBuf>) -> Self {
Self::load_with_mode(auth, models_path, ModelRegistryLoadMode::Full)
}
pub fn load_for_listing(auth: &AuthStorage, models_path: Option<PathBuf>) -> Self {
Self::load_with_mode(auth, models_path, ModelRegistryLoadMode::ListingLite)
}
fn load_with_mode(
auth: &AuthStorage,
models_path: Option<PathBuf>,
mode: ModelRegistryLoadMode,
) -> Self {
let mut models = built_in_models(auth, mode);
let mut error = None;
if let Some(path) = models_path {
if path.exists() {
match std::fs::read_to_string(&path)
.map_err(|e| Error::config(format!("Failed to read models.json: {e}")))
.and_then(|s| serde_json::from_str::<ModelsConfig>(&s).map_err(Error::from))
{
Ok(config) => {
apply_custom_models(auth, &mut models, &config, path.parent());
}
Err(e) => {
error = Some(format!("{e}\n\nFile: {}", path.display()));
}
}
}
}
Self { models, error }
}
pub fn models(&self) -> &[ModelEntry] {
&self.models
}
pub fn error(&self) -> Option<&str> {
self.error.as_deref()
}
pub fn available_models(&self) -> Vec<&ModelEntry> {
self.models
.iter()
.filter(|m| model_entry_is_ready(m))
.collect()
}
pub fn get_available(&self) -> Vec<ModelEntry> {
self.available_models().into_iter().cloned().collect()
}
pub fn find(&self, provider: &str, id: &str) -> Option<ModelEntry> {
let provider = provider.trim();
let canonical_provider = canonical_provider_id(provider).unwrap_or(provider);
let is_openrouter = canonical_provider.eq_ignore_ascii_case("openrouter");
// Avoid Vec + String allocation for the common (non-OpenRouter) path.
let openrouter_ids = if is_openrouter {
openrouter_model_lookup_ids(id)
} else {
Vec::new()
};
let trimmed_id = id.trim();
self.models
.iter()
.find(|m| {
let model_provider = m.model.provider.as_str();
let model_provider_canonical =
canonical_provider_id(model_provider).unwrap_or(model_provider);
let provider_matches = model_provider.eq_ignore_ascii_case(provider)
|| model_provider.eq_ignore_ascii_case(canonical_provider)
|| model_provider_canonical.eq_ignore_ascii_case(provider)
|| model_provider_canonical.eq_ignore_ascii_case(canonical_provider);
provider_matches
&& if is_openrouter {
openrouter_ids
.iter()
.any(|lookup_id| m.model.id.eq_ignore_ascii_case(lookup_id))
} else {
m.model.id.eq_ignore_ascii_case(trimmed_id)
}
})
.cloned()
}
/// Find a model by ID alone (ignoring provider), useful for extension models
/// where the provider name may be custom.
///
/// When multiple providers carry the same model ID, the canonical/primary
/// provider is preferred (e.g. `anthropic` for Claude models, `openai` for
/// GPT models). If no canonical match exists, the first alphabetical
/// provider wins, ensuring deterministic results regardless of insertion
/// order.
pub fn find_by_id(&self, id: &str) -> Option<ModelEntry> {
let id = id.trim();
let mut best: Option<&ModelEntry> = None;
for entry in &self.models {
if !entry.model.id.eq_ignore_ascii_case(id) {
continue;
}
let Some(current_best) = best else {
best = Some(entry);
continue;
};
let entry_canonical = is_canonical_provider_for_model(id, &entry.model.provider);
let best_canonical = is_canonical_provider_for_model(id, ¤t_best.model.provider);
if entry_canonical && !best_canonical {
best = Some(entry);
} else if entry_canonical == best_canonical
&& entry.model.provider < current_best.model.provider
{
// Tie-break alphabetically for determinism.
best = Some(entry);
}
}
best.cloned()
}
/// Merge extension-provided model entries into the registry.
pub fn merge_entries(&mut self, entries: Vec<ModelEntry>) {
for entry in entries {
// Skip duplicates (canonical provider + canonical model id, case-insensitive).
let entry_key = normalized_registry_key(&entry.model.provider, &entry.model.id);
let exists = self
.models
.iter()
.any(|m| normalized_registry_key(&m.model.provider, &m.model.id) == entry_key);
if !exists {
self.models.push(entry);
}
}
}
}
/// Returns `true` when `provider` is the canonical/primary source for a model
/// identified by `model_id`. Used by `find_by_id` to prefer the authoritative
/// provider when the same model ID appears under multiple resellers.
fn is_canonical_provider_for_model(model_id: &str, provider: &str) -> bool {
let id_lower = model_id.to_ascii_lowercase();
let prov_lower = provider.to_ascii_lowercase();
if id_lower.starts_with("claude") {
prov_lower == "anthropic"
} else if id_lower.starts_with("gpt-")
|| id_lower.starts_with("o1")
|| id_lower.starts_with("o3")
|| id_lower.starts_with("o4")
{
prov_lower == "openai"
} else if id_lower.starts_with("gemini") {
prov_lower == "google"
} else if id_lower.starts_with("command") {
prov_lower == "cohere"
} else if id_lower.starts_with("mistral") || id_lower.starts_with("codestral") {
prov_lower == "mistral"
} else if id_lower.starts_with("deepseek") {
prov_lower == "deepseek"
} else {
false
}
}
/// Determine per-model reasoning capability. Returns `Some(true/false)` for
/// known model ID patterns, `None` for unknown models (caller should fall back
/// to the provider-level default).
///
/// This prevents non-reasoning models like `gpt-4o` from inheriting a
/// provider-level `reasoning: true` flag from their provider (Issue #19).
fn model_is_reasoning(model_id: &str) -> Option<bool> {
let raw_id = model_id.to_ascii_lowercase();
let id = [
"claude-",
"gpt-",
"gemini-",
"command-",
"deepseek",
"qwq-",
"mistral",
"codestral",
"pixtral",
"llama",
"o1",
"o3",
"o4",
]
.iter()
.find_map(|needle| raw_id.find(needle).map(|idx| &raw_id[idx..]))
.unwrap_or(raw_id.as_str());
// OpenAI: o1/o3/o4 series and gpt-5.x are reasoning.
// All gpt-4 variants (gpt-4o, gpt-4-turbo, gpt-4-0613, etc.) and gpt-3.5 are NOT.
if id.starts_with("o1") || id.starts_with("o3") || id.starts_with("o4") {
return Some(true);
}
if id.starts_with("gpt-5") {
return Some(true);
}
if id.starts_with("gpt-4") || id.starts_with("gpt-3.5") {
return Some(false);
}
// Anthropic: Claude 3.5 Sonnet and Claude 4+ support extended thinking.
// Claude 3 (Haiku/Sonnet/Opus) and Claude 3.5 Haiku do NOT.
if id.starts_with("claude-3-5-haiku")
|| id.starts_with("claude-3-haiku")
|| id.starts_with("claude-3-sonnet")
|| id.starts_with("claude-3-opus")
{
return Some(false);
}
if id.starts_with("claude") {
// Claude 3.5 Sonnet, Claude 4.x, Claude Opus 4+, Claude Sonnet 4+ etc.
return Some(true);
}
// Google: gemini-2.5+ and gemini-2.0-flash-thinking are reasoning.
// All other gemini models (2.0-flash, 2.0-flash-lite, 1.x, etc.) are NOT.
if id.starts_with("gemini-2.5")
|| id.starts_with("gemini-3")
|| id.starts_with("gemini-2.0-flash-thinking")
{
return Some(true);
}
if id.starts_with("gemini") {
return Some(false);
}
// Cohere: command-a is reasoning; command-r is not.
if id.starts_with("command-a") {
return Some(true);
}
if id.starts_with("command-r") {
return Some(false);
}
// DeepSeek: deepseek-reasoner (R1) is reasoning; deepseek-chat (V3) and others are not.
if id.starts_with("deepseek-reasoner") || id.starts_with("deepseek-r") {
return Some(true);
}
if id.starts_with("deepseek") {
return Some(false);
}
// Qwen: qwq- series are reasoning.
if id.starts_with("qwq-") {
return Some(true);
}
// Mistral/Codestral: no reasoning support currently.
if id.starts_with("mistral") || id.starts_with("codestral") || id.starts_with("pixtral") {
return Some(false);
}
// Meta Llama: no reasoning support.
if id.starts_with("llama") {
return Some(false);
}
// Groq-hosted models: groq model IDs typically include the upstream model name
// (e.g., "llama-3.3-70b-versatile"), so the upstream checks above should catch them.
None
}
/// Resolve the effective reasoning flag for a model, preferring per-model
/// detection over the provider-level default.
fn effective_reasoning(model_id: &str, provider_default: bool) -> bool {
model_is_reasoning(model_id).unwrap_or(provider_default)
}
fn native_adapter_seed_defaults(provider: &str) -> Option<AdHocProviderDefaults> {
match provider {
"openai-codex" => Some(AdHocProviderDefaults {
api: "openai-codex-responses",
base_url: CODEX_RESPONSES_API_URL,
auth_header: true,
reasoning: true,
input: &INPUT_TEXT_AND_IMAGE,
context_window: 272_000,
max_tokens: 128_000,
}),
"google-gemini-cli" => Some(AdHocProviderDefaults {
api: "google-gemini-cli",
base_url: GOOGLE_GEMINI_CLI_API_URL,
auth_header: true,
reasoning: true,
input: &INPUT_TEXT_AND_IMAGE,
context_window: 128_000,
max_tokens: 8192,
}),
"google-antigravity" => Some(AdHocProviderDefaults {
api: "google-gemini-cli",
base_url: GOOGLE_ANTIGRAVITY_API_URL,
auth_header: true,
reasoning: true,
input: &INPUT_TEXT_AND_IMAGE,
context_window: 128_000,
max_tokens: 8192,
}),
"azure-openai" => Some(AdHocProviderDefaults {
api: "openai-completions",
base_url: "",
auth_header: false,
reasoning: true,
input: &INPUT_TEXT_AND_IMAGE,
context_window: 128_000,
max_tokens: 16_384,
}),
"github-copilot" | "sap-ai-core" => Some(AdHocProviderDefaults {
api: "openai-completions",
base_url: "",
auth_header: true,
reasoning: true,
input: &INPUT_TEXT_ONLY,
context_window: 128_000,
max_tokens: 16_384,
}),
"gitlab" => Some(AdHocProviderDefaults {
api: "gitlab-chat",
base_url: "",
auth_header: true,
reasoning: true,
input: &INPUT_TEXT_ONLY,
context_window: 128_000,
max_tokens: 16_384,
}),
_ => None,
}
}
fn custom_provider_defaults(provider: &str) -> Option<AdHocProviderDefaults> {
let canonical_provider = canonical_provider_id(provider).unwrap_or(provider);
ad_hoc_provider_defaults(canonical_provider)
.or_else(|| native_adapter_seed_defaults(canonical_provider))
}
fn legacy_provider_ids() -> HashSet<String> {
legacy_generated_models()
.iter()
.map(|model| {
let provider = model.provider.trim();
canonical_provider_id(provider)
.unwrap_or(provider)
.to_ascii_lowercase()
})
.collect()
}
fn resolve_provider_api_key_cached(
auth: &AuthStorage,
canonical_provider: &str,
provider: &str,
canonical_cache: &mut HashMap<String, Option<String>>,
provider_cache: &mut HashMap<String, Option<String>>,
) -> Option<String> {
let canonical_key = canonical_provider.to_ascii_lowercase();
let canonical_result = canonical_cache
.entry(canonical_key)
.or_insert_with(|| auth.resolve_api_key(canonical_provider, None))
.clone();
if canonical_result.is_some() || canonical_provider.eq_ignore_ascii_case(provider) {
return canonical_result;
}
provider_cache
.entry(provider.to_ascii_lowercase())
.or_insert_with(|| auth.resolve_api_key(provider, None))
.clone()
}
fn append_upstream_nonlegacy_models(
auth: &AuthStorage,
models: &mut Vec<ModelEntry>,
seen: &mut HashSet<String>,
canonical_api_key_cache: &mut HashMap<String, Option<String>>,
provider_api_key_cache: &mut HashMap<String, Option<String>>,
) {
let legacy_providers = legacy_provider_ids();
for (provider, ids) in upstream_provider_model_ids() {
let provider = provider.trim();
if provider.is_empty() {
continue;
}
let canonical_provider = canonical_provider_id(provider).unwrap_or(provider);
if legacy_providers.contains(&canonical_provider.to_ascii_lowercase()) {
continue;