-
Notifications
You must be signed in to change notification settings - Fork 204
Expand file tree
/
Copy pathmodels.rs
More file actions
10468 lines (9720 loc) · 402 KB
/
Copy pathmodels.rs
File metadata and controls
10468 lines (9720 loc) · 402 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::de::{MapAccess, SeqAccess, Visitor};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::cell::RefCell;
use std::collections::{BTreeMap, HashMap, HashSet};
use std::fs;
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::sync::OnceLock;
/// Routable model roles (bd-cv653.3.1, port of omp's model-roles concept).
///
/// Roles let work be routed by intent: the main conversation runs on
/// `Default`, cheap fan-out on `Smol`, deep reasoning on `Slow`, plan mode on
/// `Plan`, and so on. Every role falls back to `Default` when unconfigured.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum ModelRole {
Default,
Smol,
Slow,
Plan,
Commit,
Vision,
Designer,
Task,
Advisor,
Tiny,
}
impl ModelRole {
/// All roles in stable declaration order.
pub const ALL: [Self; 10] = [
Self::Default,
Self::Smol,
Self::Slow,
Self::Plan,
Self::Commit,
Self::Vision,
Self::Designer,
Self::Task,
Self::Advisor,
Self::Tiny,
];
/// Canonical lowercase name (as used in settings.json and /model).
pub const fn as_str(self) -> &'static str {
match self {
Self::Default => "default",
Self::Smol => "smol",
Self::Slow => "slow",
Self::Plan => "plan",
Self::Commit => "commit",
Self::Vision => "vision",
Self::Designer => "designer",
Self::Task => "task",
Self::Advisor => "advisor",
Self::Tiny => "tiny",
}
}
/// Parse a role name (case-insensitive). Returns `None` for unknown names.
pub fn from_name(name: &str) -> Option<Self> {
let lowered = name.trim().to_ascii_lowercase();
Self::ALL.into_iter().find(|role| role.as_str() == lowered)
}
/// The role a subagent child should use when its agent definition does not
/// pin a model: `task` when configured, else `smol`, else `default`.
pub const fn subagent_fallback() -> Self {
Self::Task
}
}
impl std::fmt::Display for ModelRole {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
#[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 {
/// Explicit tool-call dialect selected by the catalog. Absence is
/// fail-closed Native behavior; model-name heuristics are informational
/// only and never enable response repair at runtime.
pub fn tool_call_dialect(&self) -> crate::dialects::Dialect {
self.compat
.as_ref()
.and_then(|compat| compat.tool_call_dialect)
.unwrap_or_default()
}
/// 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.6"
| "gpt-5.6-sol"
| "gpt-5.6-terra"
| "gpt-5.6-luna"
| "gpt-5.4"
| "gpt-5.2-codex"
| "gpt-5.3-codex"
| "gpt-5.3-codex-spark"
) || self.is_deepseek_reasoning_model()
|| self.is_openrouter_reasoning_model()
|| self.is_anthropic_xhigh_effort_model()
|| self.thinking_level_map_declares("xhigh")
}
/// Whether this model's thinking level is forwarded as OpenRouter's
/// normalized `reasoning: {effort}` object (gh #220).
///
/// The gateway accepts every pi level name as an `effort` value and
/// translates it for models that take a token budget, so `xhigh`/`max`
/// must not be clamped away before `OpenAIProvider::build_request` runs.
/// Mirrors `OpenAIProvider::reasoning_style` on the `openai-completions`
/// transport: the OpenRouter gateway (canonical provider id or an
/// `openrouter.ai` base URL) with either no declared
/// `compat.thinkingFormat` or an explicit `"openrouter"`, or any other
/// provider that explicitly declares `"openrouter"`.
fn is_openrouter_reasoning_model(&self) -> bool {
// Only the chat-completions transport implements the dialect.
if !self.model.reasoning || self.model.api != "openai-completions" {
return false;
}
let declared = self
.compat
.as_ref()
.and_then(|compat| compat.thinking_format.as_deref())
.map(str::trim)
.filter(|format| !format.is_empty());
let transport_is_openrouter = canonical_provider_id(&self.model.provider)
.is_some_and(|canonical| canonical == "openrouter")
|| self.model.provider.eq_ignore_ascii_case("openrouter")
|| self
.model
.base_url
.to_ascii_lowercase()
.contains("openrouter.ai");
declared.map_or(transport_is_openrouter, |format| {
format.eq_ignore_ascii_case("openrouter")
})
}
/// Whether the catalog's per-model `thinkingLevelMap` declares a mapping
/// for the given lowercase thinking-level name. A declared entry is the
/// catalog author asserting the model accepts that tier (possibly under a
/// different provider vocabulary), so the registry must not clamp it away
/// for custom models that hard-coded model-id detection cannot know about
/// (gh #165).
fn thinking_level_map_declares(&self, level: &str) -> bool {
self.compat
.as_ref()
.and_then(|compat| compat.thinking_level_map.as_ref())
.is_some_and(|map| map.contains_key(level))
}
/// Whether this is an Anthropic adaptive-thinking model whose modern
/// `output_config.effort` accepts the `xhigh` tier.
///
/// xhigh effort is supported on Claude Opus 4.7/4.8 and the Claude
/// Fable/Mythos (5.x) families; Opus 4.6 and Sonnet 4.6 support adaptive
/// thinking + effort but NOT the xhigh tier (so they correctly clamp
/// `XHigh -> High`). Scoped to the `anthropic-messages` transport (native
/// Anthropic and Anthropic-compatible providers that route through
/// `AnthropicProvider`); the `claude-` id check additionally excludes
/// Anthropic-compatible non-Claude models on that transport (e.g. MiniMax).
///
/// Without this, the registry clamps `XHigh -> High` before
/// `AnthropicProvider::build_request` runs and the transport's `"xhigh"`
/// effort arm is dead at runtime (the same reasoning as the DeepSeek
/// `is_deepseek_reasoning_model` path; gh #116).
/// Ref: https://platform.claude.com/docs/en/build-with-claude/effort
fn is_anthropic_xhigh_effort_model(&self) -> bool {
if !self.model.reasoning || self.model.api != "anthropic-messages" {
return false;
}
let id = self.model.id.to_ascii_lowercase();
let Some(pos) = id.find("claude-") else {
return false;
};
let id = &id[pos..];
id.starts_with("claude-opus-4-7")
|| id.starts_with("claude-opus-4-8")
|| id.starts_with("claude-opus-5")
|| id.starts_with("claude-sonnet-5")
|| id.starts_with("claude-fable-")
|| id.starts_with("claude-mythos-")
}
/// Whether this model supports the `max` thinking level (gh #139).
///
/// `max` is the top effort tier, above `xhigh`:
/// - Anthropic adaptive-thinking models accept `output_config.effort:
/// "max"` on every effort-capable family — including Opus 4.6 and
/// Sonnet 4.6, which support `max` but NOT `xhigh` (the `xhigh` tier
/// arrived with Opus 4.7).
/// Ref: https://platform.claude.com/docs/en/build-with-claude/effort
/// - DeepSeek reasoning models document `reasoning_effort: "max"` as
/// their top thinking tier (previously reachable only by pi's `xhigh`).
///
/// OpenAI-family models are excluded unless their API metadata explicitly
/// advertises a distinct `max` effort tier. GPT-5.6 is the first such
/// family; older OpenAI models continue to clamp `Max` down to `XHigh`.
/// A catalog `thinkingLevelMap` override can still re-map levels per model.
pub fn supports_max(&self) -> bool {
matches!(
self.model.id.as_str(),
"gpt-5.6" | "gpt-5.6-sol" | "gpt-5.6-terra" | "gpt-5.6-luna"
) || self.is_deepseek_reasoning_model()
|| self.is_openrouter_reasoning_model()
|| self.is_anthropic_max_effort_model()
|| self.thinking_level_map_declares("max")
}
/// Whether this is an Anthropic adaptive-thinking model whose
/// `output_config.effort` accepts the `max` tier.
///
/// Same transport/id scoping rationale as
/// [`is_anthropic_xhigh_effort_model`](Self::is_anthropic_xhigh_effort_model),
/// plus the Opus 4.6 / Sonnet 4.6 families (which accept `max` without
/// `xhigh`).
fn is_anthropic_max_effort_model(&self) -> bool {
if self.is_anthropic_xhigh_effort_model() {
return true;
}
if !self.model.reasoning || self.model.api != "anthropic-messages" {
return false;
}
let id = self.model.id.to_ascii_lowercase();
let Some(pos) = id.find("claude-") else {
return false;
};
let id = &id[pos..];
id.starts_with("claude-opus-4-6") || id.starts_with("claude-sonnet-4-6")
}
/// Whether this is a DeepSeek reasoning model whose thinking-mode API accepts
/// `reasoning_effort: "max"`.
///
/// DeepSeek reasoning models route through the DeepSeek thinking format on
/// the chat-completions transport (see `OpenAIProvider::reasoning_style`), and
/// DeepSeek maps the `xhigh` thinking level to `reasoning_effort: "max"` in
/// thinking mode (gh #114; https://api-docs.deepseek.com/guides/thinking_mode).
/// They therefore genuinely support xhigh — without this the registry clamps
/// `XHigh -> High` before `build_request()` runs and the serializer's `"max"`
/// arm is dead at runtime.
///
/// Detected the same way the transport detects DeepSeek (provider id
/// `deepseek`, or a `deepseek.com` base URL) AND restricted to reasoning
/// models, so the non-thinking `deepseek-chat` / V3 family is never enabled
/// (those are additionally excluded upstream, since `available_thinking_levels`
/// and `clamp_thinking_level` short-circuit on non-reasoning models).
fn is_deepseek_reasoning_model(&self) -> bool {
if !self.model.reasoning {
return false;
}
// gh #166: an explicit catalog `compat.thinkingFormat` declaration is
// authoritative, mirroring `OpenAIProvider::reasoning_style`.
// `"deepseek"` opts a custom provider into the dialect, so the
// registry must not clamp `XHigh`/`Max` away before `build_request`
// runs (otherwise the serializer's `reasoning_effort: "max"` arm is
// dead at runtime — the same rationale as the id/URL heuristic
// below). Any other declared format opts a DeepSeek-looking provider
// out, so its level list stays coherent with a transport that emits
// no DeepSeek thinking controls.
if let Some(format) = self
.compat
.as_ref()
.and_then(|compat| compat.thinking_format.as_deref())
.map(str::trim)
.filter(|format| !format.is_empty())
{
return format.eq_ignore_ascii_case("deepseek");
}
let provider_is_deepseek = canonical_provider_id(&self.model.provider)
.is_some_and(|canonical| canonical == "deepseek")
|| self.model.provider.eq_ignore_ascii_case("deepseek");
let base_is_deepseek = self
.model
.base_url
.to_ascii_lowercase()
.contains("deepseek.com");
provider_is_deepseek || base_is_deepseek
}
/// 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);
}
if self.supports_max() {
levels.push(ThinkingLevel::Max);
}
levels
}
/// Clamp a requested thinking level to the model's capabilities.
///
/// Non-reasoning models always return `Off`. Models without max support
/// downgrade `Max` to `XHigh` (or `High` if xhigh is also unsupported);
/// 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;
}
let mut thinking = thinking;
if thinking == crate::model::ThinkingLevel::Max && !self.supports_max() {
thinking = if self.supports_xhigh() {
crate::model::ThinkingLevel::XHigh
} else {
crate::model::ThinkingLevel::High
};
}
if thinking == crate::model::ThinkingLevel::XHigh && !self.supports_xhigh() {
return crate::model::ThinkingLevel::High;
}
thinking
}
}
/// OAuth configuration for extension-registered providers.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OAuthConfig {
pub auth_url: String,
pub token_url: String,
pub client_id: String,
pub scopes: Vec<String>,
pub redirect_uri: Option<String>,
}
/// Provider-level runtime metadata registered by an extension independently
/// of how many model rows that provider declares.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExtensionProviderBinding {
pub provider: String,
pub oauth_config: Option<OAuthConfig>,
}
/// Extract exact extension-provider identities and OAuth metadata from the
/// manager's authoritative provider snapshot.
///
/// # Errors
/// Returns a configuration error when a provider snapshot has no usable ID,
/// contains duplicate normalized extension identities, or attempts to attach
/// declarative OAuth to a built-in provider identity.
pub fn extension_provider_bindings(
provider_specs: &[serde_json::Value],
) -> crate::error::Result<Vec<ExtensionProviderBinding>> {
let bindings = provider_specs
.iter()
.map(|provider_spec| {
let provider = provider_spec
.get("id")
.and_then(serde_json::Value::as_str)
.unwrap_or_default()
.trim();
if provider.is_empty() {
return Err(Error::config(
"extension provider identity must not be blank",
));
}
let oauth_config = provider_spec
.get("oauth")
.and_then(serde_json::Value::as_object)
.and_then(|oauth| {
let auth_url = oauth.get("authUrl")?.as_str()?.to_string();
let token_url = oauth.get("tokenUrl")?.as_str()?.to_string();
let client_id = oauth.get("clientId")?.as_str()?.to_string();
let scopes = oauth
.get("scopes")
.and_then(serde_json::Value::as_array)
.map(|scopes| {
scopes
.iter()
.filter_map(serde_json::Value::as_str)
.map(ToString::to_string)
.collect()
})
.unwrap_or_default();
let redirect_uri = oauth
.get("redirectUri")
.and_then(serde_json::Value::as_str)
.map(ToString::to_string);
Some(OAuthConfig {
auth_url,
token_url,
client_id,
scopes,
redirect_uri,
})
});
Ok(ExtensionProviderBinding {
provider: provider.to_string(),
oauth_config,
})
})
.collect::<crate::error::Result<Vec<_>>>()?;
let mut providers = HashMap::new();
for binding in &bindings {
validate_extension_oauth_identity(binding)?;
let provider_key = extension_provider_key(&binding.provider);
if let Some((first_provider, oauth_config)) = providers.get(&provider_key) {
if first_provider != &binding.provider {
return Err(Error::config(format!(
"extension providers {first_provider:?} and {:?} resolve to the same normalized extension provider identity {provider_key:?}",
binding.provider
)));
}
if oauth_config != &binding.oauth_config {
return Err(Error::config(format!(
"extension provider {:?} contains conflicting OAuth metadata",
binding.provider
)));
}
return Err(Error::config(format!(
"extension provider {:?} is registered more than once",
binding.provider
)));
}
providers.insert(
provider_key,
(binding.provider.clone(), binding.oauth_config.clone()),
);
}
Ok(bindings)
}
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ModelsConfig {
#[serde(deserialize_with = "deserialize_model_providers")]
pub providers: HashMap<String, ProviderConfig>,
}
fn deserialize_model_providers<'de, D>(
deserializer: D,
) -> std::result::Result<HashMap<String, ProviderConfig>, D::Error>
where
D: serde::Deserializer<'de>,
{
struct ProvidersVisitor;
impl<'de> Visitor<'de> for ProvidersVisitor {
type Value = HashMap<String, ProviderConfig>;
fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str("a map of model-provider configurations with unique keys")
}
fn visit_map<A>(self, mut entries: A) -> std::result::Result<Self::Value, A::Error>
where
A: MapAccess<'de>,
{
let mut providers = HashMap::with_capacity(
entries
.size_hint()
.unwrap_or_default()
.min(MAX_FETCHED_PROVIDERS),
);
// Reject ambiguity while JSON document order is still available;
// a randomized HashMap must never decide which route wins.
let mut original_provider_sources = HashSet::new();
let mut canonical_provider_sources = HashMap::<String, String>::new();
while let Some(provider) = entries.next_key::<String>()? {
if !original_provider_sources.insert(provider.clone()) {
return Err(serde::de::Error::custom(format!(
"duplicate JSON object key {provider:?} in models.json providers"
)));
}
let canonical_provider = canonical_provider_key(&provider);
if canonical_provider.is_empty() {
return Err(serde::de::Error::custom(
"models.json provider identity must not be blank",
));
}
if let Some(first_provider) =
canonical_provider_sources.insert(canonical_provider.clone(), provider.clone())
{
return Err(serde::de::Error::custom(format!(
"models.json providers {first_provider:?} and {provider:?} resolve to the same canonical provider identity {canonical_provider:?}"
)));
}
let config = entries.next_value::<ProviderConfig>()?;
// Lookup is case-insensitive and trims IDs, with additional
// OpenRouter alias folding. Enforce that same identity here.
let mut canonical_model_sources = HashMap::new();
for model in config.models.as_deref().unwrap_or_default() {
let canonical_identity =
normalized_registry_key(&canonical_provider, &model.id);
if let Some(first_model_id) =
canonical_model_sources.insert(canonical_identity.clone(), model.id.clone())
{
return Err(serde::de::Error::custom(format!(
"models.json provider {provider:?} contains model IDs {first_model_id:?} and {:?} with duplicate canonical model identity {canonical_identity:?}",
model.id
)));
}
}
// Preserve the provider's configured spelling after trimming.
// Extension stream handlers index their runtime registration
// by this source identity; canonicalization remains the
// comparison key used above and throughout registry lookup.
providers.insert(provider.trim().to_string(), config);
}
Ok(providers)
}
}
deserializer.deserialize_map(ProvidersVisitor)
}
pub(crate) const FETCHED_MODELS_SCHEMA: &str = "pi.models.fetched.v2";
pub(crate) const MAX_FETCHED_CATALOG_BYTES: usize = 4 * 1024 * 1024;
pub(crate) const MAX_FETCHED_PROVIDERS: usize = 128;
pub(crate) const MAX_FETCHED_PROVIDER_ID_BYTES: usize = 256;
pub(crate) const MAX_FETCHED_MODELS_PER_PROVIDER: usize = 4_096;
pub(crate) const MAX_FETCHED_MODEL_ID_BYTES: usize = 512;
pub(crate) const MAX_FETCHED_MODEL_BYTES_PER_PROVIDER: usize = 2 * 1024 * 1024;
pub(crate) fn is_safe_model_catalog_identifier(value: &str, max_bytes: usize) -> bool {
!value.is_empty()
&& value.len() <= max_bytes
&& value.bytes().all(|byte| byte.is_ascii_graphic())
}
/// Strict on-disk shape for the generated catalog.
///
/// Keeping this separate from [`ModelsConfig`] prevents a generated file from
/// silently acquiring routing, credential, or compatibility fields that only
/// belong in user-authored `models.json`.
#[derive(Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct PersistedFetchedCatalog {
pub(crate) schema: String,
#[serde(deserialize_with = "deserialize_fetched_providers")]
pub(crate) providers: BTreeMap<String, PersistedFetchedProvider>,
}
impl Default for PersistedFetchedCatalog {
fn default() -> Self {
Self {
schema: FETCHED_MODELS_SCHEMA.to_string(),
providers: BTreeMap::new(),
}
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct PersistedFetchedProvider {
#[serde(rename = "routeFingerprint")]
pub(crate) route_fingerprint: String,
#[serde(rename = "fetchedAtUnixMs")]
pub(crate) fetched_at_unix_ms: u64,
#[serde(deserialize_with = "deserialize_fetched_models")]
pub(crate) models: Vec<PersistedFetchedModel>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct PersistedFetchedModel {
pub(crate) id: String,
}
fn deserialize_fetched_providers<'de, D>(
deserializer: D,
) -> std::result::Result<BTreeMap<String, PersistedFetchedProvider>, D::Error>
where
D: serde::Deserializer<'de>,
{
struct ProvidersVisitor;
impl<'de> Visitor<'de> for ProvidersVisitor {
type Value = BTreeMap<String, PersistedFetchedProvider>;
fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str("a bounded map of generated model providers")
}
fn visit_map<A>(self, mut entries: A) -> std::result::Result<Self::Value, A::Error>
where
A: MapAccess<'de>,
{
let mut providers = BTreeMap::new();
let mut canonical_providers = HashSet::new();
while let Some(provider) = entries.next_key::<String>()? {
if providers.len() >= MAX_FETCHED_PROVIDERS {
return Err(serde::de::Error::custom(format!(
"generated model catalog exceeds {MAX_FETCHED_PROVIDERS} providers"
)));
}
if !is_safe_model_catalog_identifier(&provider, MAX_FETCHED_PROVIDER_ID_BYTES) {
return Err(serde::de::Error::custom(
"generated model catalog contains an invalid provider ID",
));
}
if providers.contains_key(&provider) {
return Err(serde::de::Error::custom(format!(
"duplicate JSON object key {provider:?}"
)));
}
let canonical = canonical_provider_key(&provider);
if !canonical_providers.insert(canonical.clone()) {
return Err(serde::de::Error::custom(format!(
"generated model catalog contains duplicate aliases for provider {canonical:?}"
)));
}
let config = entries.next_value::<PersistedFetchedProvider>()?;
providers.insert(provider, config);
}
Ok(providers)
}
}
deserializer.deserialize_map(ProvidersVisitor)
}
fn deserialize_fetched_models<'de, D>(
deserializer: D,
) -> std::result::Result<Vec<PersistedFetchedModel>, D::Error>
where
D: serde::Deserializer<'de>,
{
struct ModelsVisitor;
impl<'de> Visitor<'de> for ModelsVisitor {
type Value = Vec<PersistedFetchedModel>;
fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str("a bounded sequence of generated model IDs")
}
fn visit_seq<A>(self, mut rows: A) -> std::result::Result<Self::Value, A::Error>
where
A: SeqAccess<'de>,
{
let mut models = Vec::with_capacity(
rows.size_hint()
.unwrap_or_default()
.min(MAX_FETCHED_MODELS_PER_PROVIDER),
);
let mut total_bytes = 0usize;
while let Some(model) = rows.next_element::<PersistedFetchedModel>()? {
if models.len() >= MAX_FETCHED_MODELS_PER_PROVIDER {
return Err(serde::de::Error::custom(format!(
"generated provider exceeds {MAX_FETCHED_MODELS_PER_PROVIDER} models"
)));
}
if !is_safe_model_catalog_identifier(&model.id, MAX_FETCHED_MODEL_ID_BYTES) {
return Err(serde::de::Error::custom(
"generated model catalog contains an invalid model ID",
));
}
total_bytes = total_bytes.checked_add(model.id.len()).ok_or_else(|| {
serde::de::Error::custom("generated model catalog model-ID size overflow")
})?;
if total_bytes > MAX_FETCHED_MODEL_BYTES_PER_PROVIDER {
return Err(serde::de::Error::custom(format!(
"generated provider exceeds {MAX_FETCHED_MODEL_BYTES_PER_PROVIDER} model-ID bytes"
)));
}
models.push(model);
}
Ok(models)
}
}
deserializer.deserialize_seq(ModelsVisitor)
}
/// Effective provider settings used by OpenAI-compatible model discovery.
///
/// This mirrors the provider-level merge performed for normal inference so a
/// `models.json` endpoint, credential, header, or auth-header override cannot
/// silently diverge from `--fetch-models`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ModelCatalogProviderConfig {
pub(crate) base_url: String,
pub(crate) api: String,
pub(crate) api_key: Option<String>,
pub(crate) headers: HashMap<String, String>,
pub(crate) auth_header: bool,
}
#[derive(Debug)]
pub(crate) struct PreparedModelCatalogProviderConfig {
route: ModelCatalogProviderConfig,
fallback_api_key: Option<String>,
deferred_headers: HashMap<String, String>,
base_dir: Option<PathBuf>,
}
impl PreparedModelCatalogProviderConfig {
pub(crate) fn requires_runtime_api_key(&self) -> bool {
self.route.auth_header && !has_complete_custom_authorization_header(&self.route.headers)
}
pub(crate) fn into_route(
mut self,
resolve_fallback_api_key: bool,
) -> ModelCatalogProviderConfig {
self.route.headers.extend(resolve_headers_with_base(
Some(&self.deferred_headers),
self.base_dir.as_deref(),
));
if resolve_fallback_api_key && self.requires_runtime_api_key() {
self.route.api_key = self
.fallback_api_key
.as_deref()
.and_then(|value| resolve_value_with_base(value, self.base_dir.as_deref()));
}
self.route
}
}
/// Resolve the credential that a model-catalog request actually uses.
///
/// The caller-supplied credential represents normal runtime resolution
/// (explicit override, ambient/provider auth, and stored auth). A models.json
/// `apiKey` is only the fallback when that runtime credential is empty and the
/// route needs Pi to generate an Authorization header.
pub(crate) fn effective_model_catalog_api_key(
caller_api_key: &str,
route: &ModelCatalogProviderConfig,
) -> String {
let caller_api_key = caller_api_key.trim();
if caller_api_key.is_empty() {
route
.api_key
.as_deref()
.map(str::trim)
.filter(|api_key| !api_key.is_empty())
.unwrap_or_default()
.to_string()
} else {
caller_api_key.to_string()
}
}
fn update_catalog_fingerprint_component(hasher: &mut Sha256, label: &str, value: &[u8]) {
hasher.update((label.len() as u64).to_le_bytes());
hasher.update(label.as_bytes());
hasher.update((value.len() as u64).to_le_bytes());
hasher.update(value);
}
fn model_catalog_credential_query_name(name: &str) -> bool {
matches!(
name.trim().to_ascii_lowercase().as_str(),
"access-token" | "access_token" | "api-key" | "api_key" | "apikey" | "key" | "token"
)
}
fn model_catalog_credential_header_name(name: &str) -> bool {
matches!(
name.trim().to_ascii_lowercase().as_str(),
"api-key"
| "apikey"
| "authorization"
| "ocp-apim-subscription-key"
| "proxy-authorization"
| "x-api-key"
| "x-auth-token"
| "x-goog-api-key"
)
}
fn parsed_model_catalog_route_url(base_url: &str) -> Option<url::Url> {
let parsed = url::Url::parse(base_url.trim()).ok()?;
if !matches!(parsed.scheme(), "http" | "https")
|| !parsed.username().is_empty()
|| parsed.password().is_some()
{
return None;
}
Some(parsed)
}
/// Whether persisted membership can be rebound without storing or hashing secret values.
///
/// Known credential query/header channels are rotation-tolerant: query names are classified
/// case-insensitively, but their exact decoded spelling, order, multiplicity, and empty/non-empty
/// shape are bound, while their values remain excluded. Header names remain case-insensitive by
/// HTTP semantics. Any non-empty value in an unclassified query/header channel may be tenant or
/// deployment routing, so persistence fails closed rather than reusing membership across an
/// unverifiable route.
pub(crate) fn model_catalog_route_is_persistable(route: &ModelCatalogProviderConfig) -> bool {
let Some(parsed) = parsed_model_catalog_route_url(&route.base_url) else {
return false;
};
let query_is_bindable = parsed.query_pairs().all(|(name, value)| {
value.is_empty() || model_catalog_credential_query_name(name.as_ref())
});
query_is_bindable
&& route.headers.iter().all(|(name, value)| {
value.trim().is_empty() || model_catalog_credential_header_name(name)
})
}
/// Produce the non-secret endpoint/transport binding stored with fetched model
/// membership.
///
/// Credential values, URL query values, fragments, and header values are deliberately excluded.
/// Known credential query names and their ordered, case-sensitive multiplicity/presence shape are
/// bound alongside case-insensitive header names/presence. A plain SHA-256 digest of a credential
/// would still be an offline credential verifier, not harmless provenance. The process-local
/// fetch cache uses a separate credential-sensitive key.
pub(crate) fn model_catalog_route_fingerprint(
provider: &str,
route: &ModelCatalogProviderConfig,
) -> String {
let mut hasher = Sha256::new();
update_catalog_fingerprint_component(
&mut hasher,
"domain",
b"pi.models.fetched.route-binding.v1",
);
update_catalog_fingerprint_component(
&mut hasher,
"provider",
canonical_provider_key(provider).as_bytes(),
);
update_catalog_fingerprint_component(&mut hasher, "api", route.api.as_bytes());
let parsed_route = parsed_model_catalog_route_url(&route.base_url);
let normalized_base_url = parsed_route.clone().map_or_else(
|| "invalid-route-url".to_string(),
|mut parsed| {
parsed.set_query(None);
parsed.set_fragment(None);
parsed.to_string()
},
);
update_catalog_fingerprint_component(&mut hasher, "base-url", normalized_base_url.as_bytes());
if let Some(parsed) = parsed_route {
for (name, value) in parsed.query_pairs() {
update_catalog_fingerprint_component(&mut hasher, "query-name", name.as_bytes());
update_catalog_fingerprint_component(
&mut hasher,
"query-value-present",
&[u8::from(!value.is_empty())],
);
}
}
update_catalog_fingerprint_component(
&mut hasher,
"auth-header",
&[u8::from(route.auth_header)],
);
let mut headers = route.headers.iter().collect::<Vec<_>>();
headers.sort_unstable_by(|(left_name, _), (right_name, _)| {
left_name
.to_ascii_lowercase()
.cmp(&right_name.to_ascii_lowercase())
.then_with(|| left_name.cmp(right_name))
});
for (name, value) in headers {
update_catalog_fingerprint_component(
&mut hasher,
"header-name",
name.to_ascii_lowercase().as_bytes(),
);
update_catalog_fingerprint_component(
&mut hasher,
"header-present",
&[u8::from(!value.trim().is_empty())],
);
}
format!(
"sha256:{}",
crate::package_manager::hex_encode(&hasher.finalize())
)
}
fn is_valid_model_catalog_route_fingerprint(value: &str) -> bool {
value.len() == "sha256:".len() + 64
&& value.starts_with("sha256:")
&& value["sha256:".len()..]
.bytes()
.all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase())
}
#[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>>,
/// Per-model patches keyed by model id (gh #220), upstream pi's
/// `modelOverrides`. Unlike `models`, they never replace the provider's
/// catalog: a known id is patched in place, an unknown id under a
/// bundled provider is added from the provider's ad-hoc defaults. This
/// is how a built-in gateway model gets `compat.openRouterRouting` (or a
/// larger `maxTokens`) without redefining the whole provider.
pub model_overrides: Option<HashMap<String, ModelOverrideConfig>>,
}
/// One `modelOverrides` entry: every [`ModelConfig`] field except `id`, all
/// optional; only the fields present are applied.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ModelOverrideConfig {
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>,
pub dialect: Option<crate::dialects::Dialect>,
pub thinking_level_map: Option<HashMap<String, String>>,
}
#[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>,
/// Opt-in tool-call repair dialect. Omitted models remain Native.
pub dialect: Option<crate::dialects::Dialect>,
/// Model-level `thinkingLevelMap` (gh #165). Equivalent to — and
/// authoritative over — `compat.thinkingLevelMap` for this model: it is
/// folded into the entry's merged [`CompatConfig`] at registry build time.
/// Declaring a mapping for `xhigh`/`max` also marks the level as supported,
/// so the registry does not clamp it away for custom models.
pub thinking_level_map: Option<HashMap<String, String>>,
}
#[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>,
/// Explicit opt-in tool-call repair dialect, folded from a model-level
/// `dialect` declaration. Absence means Native/fail-closed.
#[serde(rename = "dialect")]