返回 CodeWhale
catalog.rs
根目录 / crates / config / src / catalog.rs
1 //! Models.dev-backed provider catalog snapshots and a secret-free live cache
2 //! (#3385, feeding EPIC #2608 and #3383).
3 //!
4 //! This module is **network-free** by construction. Callers supply parsed
5 //! [`crate::models_dev::ModelsDevCatalog`] JSON (bundled snapshot or live
6 //! refresh) and live [`ProviderCatalogDelta`]s; the HTTP `/models` fetch layer
7 //! lives above this module. Nothing here performs I/O or reads credentials.
8 //!
9 //! Layering (lowest precedence first):
10 //!
11 //! ```text
12 //! bundled Models.dev snapshot (legacy seed, not competing truth)
13 //! < live Models.dev (public catalog, external enrichment)
14 //! < Codewhale corrections (bundled field patches, see [`corrections`])
15 //! < signed cloud facts (curated correction, off by default)
16 //! < live provider `/v1/models` (credential-scoped workspace list)
17 //! < config.toml / user overrides
18 //! ```
19 //!
20 //! The two live layers are not the same kind of claim. A provider roster is a
21 //! fact about an endpoint the caller authenticated to; models.dev is a public
22 //! third-party catalog that is merely fresher than the bundled copy of itself.
23 //! Only the first outranks a signed correction — see
24 //! [`CatalogSource::ModelsDevLive`].
25 //!
26 //! After #4187, live Models.dev rows are preferred over the bundled seed. The
27 //! bundled asset remains so offline startup and failed refreshes still resolve
28 //! defaults.
29 //!
30 //! Invariants preserved from #2608 / #3497:
31 //! - A catalog row is **not** an executable route. Rows still compile through
32 //! `RouteResolver` into a `ReadyRouteCandidate` before execution.
33 //! - `wire_model_id` is kept separate from `canonical_model`; a provider row may
34 //! not expose a canonical `base_model` join, and a prefix never proves
35 //! canonical ownership.
36 //! - Unknown / custom / local rows are supported with explicit provenance and a
37 //! `None` canonical model.
38 //!
39 //! The on-disk cache format intentionally uses plain `String` identity fields
40 //! rather than the internal route newtypes, so the persisted shape is decoupled
41 //! from internal types and trivially auditable for "no secrets" (see
42 //! [`ProviderCatalogCache`] tests).
43
44 use std::collections::{BTreeMap, BTreeSet};
45 use std::sync::OnceLock;
46 use std::time::{SystemTime, UNIX_EPOCH};
47
48 use serde::{Deserialize, Serialize};
49 use serde_json::Value;
50
51 use crate::models_dev::{
52 ModelsDevCatalog, ModelsDevCost, ModelsDevInterleaved, ModelsDevLimit, ModelsDevModalities,
53 ModelsDevModelTransport,
54 };
55 use crate::route::{ModelId, ProviderId, ProviderModelOffering, RouteLimits, WireModelId};
56
57 pub mod configured;
58 pub mod corrections;
59 pub mod reviewed;
60
61 /// Provenance of a catalog row. Drives layer precedence and UI provenance.
62 #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
63 #[serde(tag = "kind", rename_all = "snake_case")]
64 pub enum CatalogSource {
65 /// Offline/stale bundled seed (Models.dev-shaped snapshot). Not competing
66 /// truth — live Models.dev rows override this layer (#4188).
67 #[default]
68 Bundled,
69 /// A provider live `/models` row, scoped to a base-URL fingerprint and the
70 /// unix timestamp it was fetched at.
71 ///
72 /// This is a **provider fact**: the row exists because that endpoint, asked
73 /// under the caller's own credential, said so. It therefore outranks the
74 /// signed cloud layer and is never patched by it, and its fingerprint names
75 /// the billing surface the row prices. A third-party catalog describing the
76 /// same model is [`Self::ModelsDevLive`], whatever URL it was fetched from.
77 Live {
78 base_url_fingerprint: String,
79 fetched_at: u64,
80 },
81 /// A user / custom override (custom endpoint, pinned model, explicit facts).
82 UserOverride,
83 /// Live models.dev refresh (layer 10). Distinct from provider `/v1/models`.
84 ///
85 /// **External enrichment, not a provider fact.** Models.dev is a public
86 /// catalog nobody authenticates to, so these rows sit *below* the signed
87 /// cloud layer and a fresh signed correction may replace their limits and
88 /// prices. Carrying no endpoint fingerprint is deliberate: like the bundled
89 /// seed this layer refreshes, the row describes a model, not an endpoint.
90 ModelsDevLive { fetched_at: u64 },
91 /// `config.toml` `[providers.*]` override (layer 30).
92 ConfigOverride,
93 /// A Codewhale correction ([`corrections`]) owns this price (set or
94 /// withheld). Corrections rank above both Models.dev layers, bundled and
95 /// live, and below signed cloud facts, which may still correct them. Used
96 /// as a `cost_source`: a corrected row keeps its own `source`.
97 CodewhaleBundled { revision: String },
98 /// Signed field patch, below provider-owned rows and explicit overrides.
99 ///
100 /// This is the only online catalog authority in the client. A second one
101 /// (`CodewhaleLive`, a layer-25 "signed CWC catalog" declared in #5783 and
102 /// never given a fetcher) was removed once signed cloud facts shipped as
103 /// the implemented signed layer: two signed catalogs on opposite sides of
104 /// the provider roster is exactly the split this product exists not to be.
105 CloudFacts {
106 facts_version: u64,
107 key_id: String,
108 fetched_at: u64,
109 #[serde(default, skip_serializing_if = "Option::is_none")]
110 valid_until: Option<u64>,
111 },
112 }
113
114 /// One catalog-layer offering row.
115 ///
116 /// This carries the routing identity (provider + wire id + optional canonical
117 /// model + endpoint) plus the offering-owned Models.dev facts CodeWhale wants to
118 /// preserve (family, limits, cost, reasoning support/options). It is a superset
119 /// of [`ProviderModelOffering`]; use [`CatalogOffering::to_offering`] to project
120 /// the minimal routing identity the resolver consumes.
121 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
122 pub struct CatalogOffering {
123 /// Provider id serving this offering.
124 pub provider: String,
125 /// Provider-owned wire id sent on the request (verbatim).
126 pub wire_model_id: String,
127 /// Canonical model identity, only when an explicit join exists.
128 #[serde(default, skip_serializing_if = "Option::is_none")]
129 pub canonical_model: Option<String>,
130 /// Endpoint key the offering is served on (e.g. `chat`).
131 pub endpoint_key: String,
132 /// Whether this is the provider's default offering.
133 #[serde(default)]
134 pub default_for_provider: bool,
135 /// Model family/series as exposed for this offering (e.g. `glm`, `deepseek`).
136 #[serde(default, skip_serializing_if = "Option::is_none")]
137 pub family: Option<String>,
138 #[serde(default, skip_serializing_if = "Option::is_none")]
139 pub name: Option<String>,
140 #[serde(default, skip_serializing_if = "Option::is_none")]
141 pub description: Option<String>,
142 #[serde(default, skip_serializing_if = "Option::is_none", rename = "type")]
143 pub model_type: Option<String>,
144 #[serde(default, skip_serializing_if = "Option::is_none")]
145 pub knowledge: Option<String>,
146 #[serde(default, skip_serializing_if = "Option::is_none")]
147 pub release_date: Option<String>,
148 #[serde(default, skip_serializing_if = "Option::is_none")]
149 pub last_updated: Option<String>,
150 #[serde(default, skip_serializing_if = "Option::is_none")]
151 pub temperature: Option<bool>,
152 #[serde(default, skip_serializing_if = "Option::is_none")]
153 pub open_weights: Option<bool>,
154 #[serde(default, skip_serializing_if = "Option::is_none")]
155 pub interleaved: Option<ModelsDevInterleaved>,
156 #[serde(default, skip_serializing_if = "Option::is_none")]
157 pub transport: Option<ModelsDevModelTransport>,
158 #[serde(default, skip_serializing_if = "Option::is_none")]
159 pub provider_api: Option<String>,
160 #[serde(default, skip_serializing_if = "Option::is_none")]
161 pub provider_npm: Option<String>,
162 #[serde(default, skip_serializing_if = "Option::is_none")]
163 pub status: Option<String>,
164 #[serde(default, skip_serializing_if = "Option::is_none")]
165 pub experimental: Option<Value>,
166 #[serde(default, skip_serializing_if = "Option::is_none")]
167 pub license: Option<String>,
168 #[serde(default, skip_serializing_if = "Option::is_none")]
169 pub links: Option<Vec<Value>>,
170 #[serde(default, skip_serializing_if = "Option::is_none")]
171 pub weights: Option<Vec<Value>>,
172 #[serde(default, skip_serializing_if = "Option::is_none")]
173 pub benchmarks: Option<Vec<Value>>,
174 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
175 pub fact_sources: BTreeMap<String, CatalogSource>,
176 /// Token limits for this offering, when known.
177 #[serde(default, skip_serializing_if = "Option::is_none")]
178 pub limit: Option<ModelsDevLimit>,
179 /// Provider-scoped pricing, when known.
180 #[serde(default, skip_serializing_if = "Option::is_none")]
181 pub cost: Option<ModelsDevCost>,
182 /// Price authority stays separate when a layer changes only capabilities.
183 #[serde(default, skip_serializing_if = "Option::is_none")]
184 pub cost_source: Option<CatalogSource>,
185 /// Who stated [`Self::modalities`], when a higher layer re-sourced the row
186 /// without restating them (a signed patch, a correction, or a provider
187 /// roster enriched from the seed). `None` means [`Self::source`] did.
188 #[serde(default, skip_serializing_if = "Option::is_none")]
189 pub modalities_source: Option<CatalogSource>,
190 /// Input/output modalities for this offering, when known. Carried as the
191 /// raw Models.dev shape so a factual `text` vs `multimodal` label can be
192 /// derived without guessing; `None` means the layer did not state it (an
193 /// unknown, not "text-only").
194 #[serde(default, skip_serializing_if = "Option::is_none")]
195 pub modalities: Option<ModelsDevModalities>,
196 /// Whether this provider offering accepts attachments, when known.
197 #[serde(default, skip_serializing_if = "Option::is_none")]
198 pub attachment: Option<bool>,
199 /// Whether this offering supports reasoning, when known.
200 #[serde(default, skip_serializing_if = "Option::is_none")]
201 pub reasoning: Option<bool>,
202 /// Whether tool calling is supported, when known (#4115).
203 #[serde(default, skip_serializing_if = "Option::is_none")]
204 pub tool_call: Option<bool>,
205 /// Whether structured output is supported, when known.
206 #[serde(default, skip_serializing_if = "Option::is_none")]
207 pub structured_output: Option<bool>,
208 /// Provider-scoped reasoning controls / accepted effort metadata. Kept as
209 /// raw JSON so the same model family served through different gateways can
210 /// expose different effort vocabularies without lossy collapsing.
211 #[serde(default, skip_serializing_if = "Vec::is_empty")]
212 pub reasoning_options: Vec<Value>,
213 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
214 pub reasoning_options_present: bool,
215 /// Where this row came from.
216 pub source: CatalogSource,
217 }
218
219 impl CatalogOffering {
220 #[must_use]
221 pub fn fact_source(&self, field: &str) -> &CatalogSource {
222 match field {
223 "cost" => self.pricing_source(),
224 "modalities" => self.modalities_source(),
225 _ => self.fact_sources.get(field).unwrap_or(&self.source),
226 }
227 }
228
229 pub fn retain_fact_sources(&mut self) {
230 macro_rules! retain {
231 ($field:ident) => {
232 if self.$field.is_some() {
233 self.fact_sources
234 .entry(stringify!($field).to_string())
235 .or_insert_with(|| self.source.clone());
236 }
237 };
238 }
239 retain!(canonical_model);
240 retain!(family);
241 retain!(name);
242 retain!(description);
243 retain!(model_type);
244 retain!(knowledge);
245 retain!(release_date);
246 retain!(last_updated);
247 retain!(temperature);
248 retain!(open_weights);
249 retain!(interleaved);
250 retain!(transport);
251 retain!(provider_api);
252 retain!(provider_npm);
253 retain!(status);
254 retain!(experimental);
255 retain!(license);
256 retain!(links);
257 retain!(weights);
258 retain!(benchmarks);
259 retain!(attachment);
260 retain!(reasoning);
261 retain!(tool_call);
262 retain!(structured_output);
263 if let Some(limit) = &self.limit {
264 for (field, value) in [
265 ("limit.context", limit.context),
266 ("limit.input", limit.input),
267 ("limit.output", limit.output),
268 ] {
269 if value.is_some() {
270 self.fact_sources
271 .entry(field.to_string())
272 .or_insert_with(|| self.source.clone());
273 }
274 }
275 }
276 if self.reasoning_options_present || !self.reasoning_options.is_empty() {
277 self.fact_sources
278 .entry("reasoning_options".to_string())
279 .or_insert_with(|| self.source.clone());
280 }
281 }
282
283 pub fn complete_from(&mut self, lower: &Self, base_url: Option<&str>) -> bool {
284 let normalize = |id: &str| {
285 crate::descriptors::compatibility_for_id(id)
286 .or_else(|| crate::descriptors::compatibility_for_selector(id))
287 .map(|provider| provider.catalog_id.to_string())
288 .unwrap_or_else(|| id.to_string())
289 };
290 if normalize(&self.provider) != normalize(&lower.provider)
291 || self.wire_model_id != lower.wire_model_id
292 || self.endpoint_key != lower.endpoint_key
293 || self
294 .canonical_model
295 .as_ref()
296 .zip(lower.canonical_model.as_ref())
297 .is_some_and(|(current, prior)| current != prior)
298 || matches!(
299 self.source,
300 CatalogSource::Bundled | CatalogSource::ModelsDevLive { .. }
301 )
302 {
303 return false;
304 }
305 let published_base = lower
306 .transport
307 .as_ref()
308 .and_then(|transport| transport.api.as_deref())
309 .or(lower.provider_api.as_deref())
310 .or_else(|| {
311 crate::ProviderKind::parse(&lower.provider)
312 .filter(|provider| *provider != crate::ProviderKind::Custom)
313 .map(|provider| provider.provider().default_base_url())
314 });
315 let endpoint_facts = match (&self.source, &lower.source) {
316 (
317 CatalogSource::Live {
318 base_url_fingerprint: current,
319 ..
320 },
321 CatalogSource::Live {
322 base_url_fingerprint: prior,
323 ..
324 },
325 ) if current == prior
326 && base_url.is_none_or(|url| base_url_fingerprint(url) == *current) =>
327 {
328 true
329 }
330 (
331 CatalogSource::Live {
332 base_url_fingerprint: current,
333 ..
334 },
335 CatalogSource::Bundled
336 | CatalogSource::ModelsDevLive { .. }
337 | CatalogSource::CloudFacts { .. }
338 | CatalogSource::CodewhaleBundled { .. },
339 ) if base_url.is_none_or(|url| base_url_fingerprint(url) == *current) => {
340 published_base.is_some_and(|url| base_url_fingerprint(url) == *current)
341 }
342 (
343 CatalogSource::ConfigOverride | CatalogSource::UserOverride,
344 CatalogSource::Bundled
345 | CatalogSource::ModelsDevLive { .. }
346 | CatalogSource::CloudFacts { .. }
347 | CatalogSource::CodewhaleBundled { .. },
348 ) if base_url
349 .zip(published_base)
350 .is_some_and(|(current, prior)| {
351 base_url_fingerprint(current) == base_url_fingerprint(prior)
352 }) =>
353 {
354 true
355 }
356 _ => return false,
357 };
358 self.complete_facts(lower, endpoint_facts)
359 }
360
361 pub(crate) fn complete_facts_from(&mut self, lower: &Self) -> bool {
362 self.complete_facts(lower, true)
363 }
364
365 fn complete_facts(&mut self, lower: &Self, endpoint_facts: bool) -> bool {
366 let mut changed = false;
367 macro_rules! fill {
368 ($field:ident) => {
369 if self.$field.is_none() && lower.$field.is_some() {
370 self.$field.clone_from(&lower.$field);
371 self.fact_sources.insert(
372 stringify!($field).to_string(),
373 lower.fact_source(stringify!($field)).clone(),
374 );
375 changed = true;
376 }
377 };
378 }
379 fill!(canonical_model);
380 fill!(family);
381 fill!(name);
382 fill!(description);
383 fill!(model_type);
384 fill!(knowledge);
385 fill!(release_date);
386 fill!(last_updated);
387 fill!(temperature);
388 fill!(open_weights);
389 fill!(interleaved);
390 if endpoint_facts {
391 fill!(transport);
392 fill!(provider_api);
393 fill!(provider_npm);
394 fill!(status);
395 }
396 fill!(experimental);
397 fill!(license);
398 fill!(links);
399 fill!(weights);
400 fill!(benchmarks);
401 fill!(attachment);
402 fill!(reasoning);
403 fill!(tool_call);
404 fill!(structured_output);
405 if let Some(lower_limit) = &lower.limit {
406 let mut limit = self.limit.clone().unwrap_or_default();
407 for (field, target, value) in [
408 ("limit.context", &mut limit.context, lower_limit.context),
409 ("limit.input", &mut limit.input, lower_limit.input),
410 ("limit.output", &mut limit.output, lower_limit.output),
411 ] {
412 if target.is_none() && value.is_some() {
413 *target = value;
414 self.fact_sources
415 .insert(field.to_string(), lower.fact_source(field).clone());
416 changed = true;
417 }
418 }
419 if self.limit.is_some() || limit != ModelsDevLimit::default() {
420 self.limit = Some(limit);
421 }
422 }
423 if endpoint_facts
424 && self.cost.is_none()
425 && self.cost_source.is_none()
426 && (lower.cost.is_some() || lower.cost_source.is_some())
427 {
428 self.cost.clone_from(&lower.cost);
429 self.cost_source = Some(lower.pricing_source().clone());
430 changed = true;
431 }
432 if self.modalities.is_none() && lower.modalities.is_some() {
433 self.modalities.clone_from(&lower.modalities);
434 self.modalities_source = Some(lower.modalities_source().clone());
435 changed = true;
436 }
437 if !self.reasoning_options_present
438 && self.reasoning_options.is_empty()
439 && (lower.reasoning_options_present || !lower.reasoning_options.is_empty())
440 && self.reasoning != Some(false)
441 {
442 self.reasoning_options.clone_from(&lower.reasoning_options);
443 self.reasoning_options_present = true;
444 self.fact_sources.insert(
445 "reasoning_options".to_string(),
446 lower.fact_source("reasoning_options").clone(),
447 );
448 changed = true;
449 }
450 changed
451 }
452
453 #[must_use]
454 pub fn pricing_source(&self) -> &CatalogSource {
455 self.cost_source.as_ref().unwrap_or(&self.source)
456 }
457
458 /// The layer that stated this row's modalities.
459 #[must_use]
460 pub fn modalities_source(&self) -> &CatalogSource {
461 self.modalities_source.as_ref().unwrap_or(&self.source)
462 }
463
464 /// The provider id as a route newtype.
465 #[must_use]
466 pub fn provider_id(&self) -> ProviderId {
467 ProviderId::from(self.provider.clone())
468 }
469
470 /// The wire model id as a route newtype.
471 #[must_use]
472 pub fn wire_id(&self) -> WireModelId {
473 WireModelId::from(self.wire_model_id.clone())
474 }
475
476 /// Project the minimal routing identity the resolver consumes.
477 ///
478 /// The catalog deliberately carries richer facts than routing needs; this
479 /// drops most of them so `RouteResolver::from_offerings` stays the single
480 /// seam. The route-facing pricing meter is the exception: it is projected
481 /// here (where the offering's sourced `cost` is in scope) via
482 /// [`crate::pricing::route_pricing_sku`] so a resolved candidate can carry
483 /// honest pricing without the route layer ever seeing raw cost (#3085).
484 #[must_use]
485 pub fn to_offering(&self) -> ProviderModelOffering {
486 ProviderModelOffering {
487 provider: self.provider_id(),
488 canonical_model: self.canonical_model.clone().map(ModelId::from),
489 wire_model_id: self.wire_id(),
490 endpoint_key: self.endpoint_key.clone(),
491 default_for_provider: self.default_for_provider,
492 limits: self
493 .limit
494 .as_ref()
495 .map(RouteLimits::from)
496 .unwrap_or_default(),
497 capabilities: crate::route::RouteCapabilities {
498 attachments: crate::route::CapabilityState::from_optional_bool(self.attachment),
499 // The offline seed is stale by nature, so it may say an image
500 // is accepted but never that it is refused: a wrong refusal
501 // strips the user's images before sending, while a wrong
502 // `Unknown` costs one rejected request that the turn loop
503 // recovers from and reports (#6396).
504 image_input: crate::models_dev::image_input_support_for(
505 self.modalities.as_ref(),
506 matches!(self.modalities_source(), CatalogSource::Bundled),
507 ),
508 reasoning: crate::route::CapabilityState::from_optional_bool(self.reasoning),
509 native_tool_calls: crate::route::CapabilityState::from_optional_bool(
510 self.tool_call,
511 ),
512 structured_output: crate::route::CapabilityState::from_optional_bool(
513 self.structured_output,
514 ),
515 server_side_web_search: crate::route::documented_server_side_web_search(
516 &self.provider,
517 &self.wire_model_id,
518 ),
519 ..crate::route::RouteCapabilities::default()
520 },
521 pricing: crate::pricing::route_pricing_sku(self),
522 }
523 }
524
525 /// Stable identity key for de-duplication and layer merging.
526 fn merge_key(&self) -> (String, String) {
527 (self.provider.clone(), self.wire_model_id.clone())
528 }
529 }
530
531 /// Committed offline/stale Models.dev-shaped catalog snapshot (#3385 / #4188).
532 ///
533 /// This is **not** a competing curated source of truth. Preferred metadata comes
534 /// from the live Models.dev catalog (#4187). The bundled asset is a compact
535 /// network-free projection of the Models.dev rows Codewhale ships, generated
536 /// by `scripts/catalog/catalog_models_dev.py seed render` from a reviewed spec and a
537 /// pinned lock (#6396), so [`crate::route::RouteResolver::new`] and pickers
538 /// still work offline or after a failed refresh. Deliberate holds (withheld
539 /// prices, clamped limits) are not in the asset: [`corrections`] applies them
540 /// to it and to live rows alike.
541 pub const BUNDLED_MODELS_DEV_JSON: &str = include_str!("../assets/models_dev.bundled.json");
542
543 /// Parse-once cache for the committed bundled Models.dev snapshot.
544 ///
545 /// The bundled asset is compile-time constant (`include_str!`), so its parsed
546 /// form is immutable and safe to share process-wide. Before this cache, every
547 /// call site parsed the full snapshot independently — the client route path,
548 /// pickers, provider lake, and fleet identity each paid a full serde parse of
549 /// ~50KB on their own first use (perf-attributed during the 0.9.x perf
550 /// gauntlet: `ModelsDevCost` serde frames in startup profiles).
551 static BUNDLED_MODELS_DEV_CATALOG: OnceLock<ModelsDevCatalog> = OnceLock::new();
552
553 /// Parse the committed bundled Models.dev snapshot.
554 ///
555 /// The first call parses; later calls return the shared parsed catalog.
556 ///
557 /// # Panics
558 /// Panics only if the committed asset is not valid Models.dev JSON. The
559 /// `tests::bundled_asset_parses` guard makes that a build-time failure, so this
560 /// never panics in shipped builds.
561 #[must_use]
562 pub fn bundled_models_dev_catalog() -> &'static ModelsDevCatalog {
563 BUNDLED_MODELS_DEV_CATALOG.get_or_init(|| {
564 let mut catalog = ModelsDevCatalog::parse_json(BUNDLED_MODELS_DEV_JSON)
565 .expect("committed bundled Models.dev asset must be valid JSON");
566 catalog.reviewed =
567 corrections::CatalogCorrections::parse(corrections::CATALOG_CORRECTIONS_JSON)
568 .expect("committed catalog corrections must be valid")
569 .reviewed;
570 catalog
571 })
572 }
573
574 /// Bundled-layer [`CatalogOffering`] rows from the offline snapshot (#4188).
575 ///
576 /// Lowest-precedence catalog layer: every text-chat row from
577 /// [`BUNDLED_MODELS_DEV_JSON`], tagged [`CatalogSource::Bundled`], with
578 /// Codewhale's [`corrections`] applied. Live Models.dev rows override these on
579 /// `(provider, wire_model_id)` when available.
580 static SEED_CATALOG_OFFERINGS: OnceLock<Vec<CatalogOffering>> = OnceLock::new();
581
582 pub(crate) fn seed_catalog_offerings() -> &'static [CatalogOffering] {
583 SEED_CATALOG_OFFERINGS
584 .get_or_init(|| {
585 let mut rows = bundled_offerings_from_models_dev(bundled_models_dev_catalog());
586 corrections::bundled_corrections().apply_to(&mut rows);
587 rows
588 })
589 .as_slice()
590 }
591
592 #[must_use]
593 pub fn bundled_catalog_offerings() -> Vec<CatalogOffering> {
594 if let Some(reg) = crate::cloud_facts::overlay::pulled_registry() {
595 return reg.compiled.catalog_offerings.clone();
596 }
597 seed_catalog_offerings().to_vec()
598 }
599
600 /// The bundled list's own default for `provider`, when a row is flagged.
601 #[must_use]
602 pub fn bundled_listed_default(provider: &str) -> Option<String> {
603 bundled_catalog_offerings().into_iter().find_map(|row| {
604 (row.provider == provider && row.default_for_provider).then_some(row.wire_model_id)
605 })
606 }
607
608 /// Default id implied by one provider's own model list.
609 ///
610 /// The pin is the fallback. A replacement must be `stem-major.minor` on the
611 /// same stem and major, with a higher minor, and must not be a variant or a
612 /// regression of tool calling or a published context/output limit. A different
613 /// product line is not a successor. Same rule as
614 /// `identify_listed_default` in `scripts/catalog/catalog_models_dev.py`.
615 #[must_use]
616 pub fn identify_listed_default(provider: &str, pinned: &str, listed: &[&str]) -> String {
617 let Some((stem, major, _)) = version_id(pinned) else {
618 return pinned.to_string();
619 };
620 let facts: Vec<CatalogOffering> = bundled_catalog_offerings()
621 .into_iter()
622 .filter(|row| row.provider == provider)
623 .collect();
624 let pin_row = facts.iter().find(|row| row.wire_model_id == pinned);
625 let mut best: Option<(&str, Vec<u32>)> = None;
626 for id in listed {
627 if variant_id(id) {
628 continue;
629 }
630 let Some((id_stem, id_major, rest)) = version_id(id) else {
631 continue;
632 };
633 if id_stem != stem || id_major != major {
634 continue;
635 }
636 if let (Some(pin_row), Some(next)) =
637 (pin_row, facts.iter().find(|row| row.wire_model_id == *id))
638 && offering_regresses(pin_row, next)
639 {
640 continue;
641 }
642 if best.as_ref().is_none_or(|(_, best_rest)| rest > *best_rest) {
643 best = Some((id, rest));
644 }
645 }
646 best.map(|(id, _)| id.to_string())
647 .unwrap_or_else(|| pinned.to_string())
648 }
649
650 fn version_id(model_id: &str) -> Option<(String, u32, Vec<u32>)> {
651 let (stem, version) = model_id.rsplit_once('-')?;
652 if stem.is_empty() {
653 return None;
654 }
655 let mut parts = version.split('.');
656 let major = parts.next()?.parse().ok()?;
657 let rest = parts
658 .map(str::parse)
659 .collect::<Result<Vec<u32>, _>>()
660 .ok()?;
661 if rest.is_empty() {
662 return None;
663 }
664 Some((stem.to_ascii_lowercase(), major, rest))
665 }
666
667 fn variant_id(model_id: &str) -> bool {
668 const TOKENS: &[&str] = &[
669 "audio",
670 "beta",
671 "coder",
672 "distill",
673 "distilled",
674 "embed",
675 "embedding",
676 "experimental",
677 "fast",
678 "haiku",
679 "image",
680 "lite",
681 "max",
682 "micro",
683 "mini",
684 "nano",
685 "preview",
686 "reranker",
687 "small",
688 "tiny",
689 "tts",
690 "turbo",
691 "vision",
692 ];
693 model_id
694 .split(|ch: char| !ch.is_ascii_alphanumeric())
695 .any(|token| {
696 let token = token.to_ascii_lowercase();
697 TOKENS.contains(&token.as_str()) || token.starts_with("flash")
698 })
699 }
700
701 /// One current id per `stem-major` line. Older snapshots of that line drop out.
702 ///
703 /// `anthropic/claude-opus-4.6` and `anthropic/claude-opus-4.8` are one line;
704 /// the newer minor stays. A different line (`claude-sonnet-…`, `claude-haiku-…`)
705 /// stays. Ids that are not `stem-major.minor` stay as themselves.
706 #[must_use]
707 pub fn current_listed_models(ids: &[String]) -> Vec<String> {
708 let mut best: std::collections::BTreeMap<String, (Vec<u32>, String)> =
709 std::collections::BTreeMap::new();
710 let mut plain = Vec::new();
711 for id in ids {
712 if variant_id(id) {
713 plain.push(id.clone());
714 continue;
715 }
716 if let Some((stem, major, rest)) = version_id(id) {
717 let key = format!("{stem}\0{major}");
718 let replace = best.get(&key).is_none_or(|(prev, _)| rest > *prev);
719 if replace {
720 best.insert(key, (rest, id.clone()));
721 }
722 } else {
723 plain.push(id.clone());
724 }
725 }
726 let mut out: Vec<String> = best.into_values().map(|(_, id)| id).chain(plain).collect();
727 out.sort();
728 out.dedup();
729 out
730 }
731
732 fn offering_regresses(pin: &CatalogOffering, next: &CatalogOffering) -> bool {
733 if pin.tool_call == Some(true) && next.tool_call == Some(false) {
734 return true;
735 }
736 let Some(pin_limit) = pin.limit.as_ref() else {
737 return false;
738 };
739 let Some(next_limit) = next.limit.as_ref() else {
740 return false;
741 };
742 matches!(
743 (pin_limit.context, next_limit.context),
744 (Some(old), Some(new)) if new < old
745 ) || matches!(
746 (pin_limit.output, next_limit.output),
747 (Some(old), Some(new)) if new < old
748 )
749 }
750
751 /// Hydrate bundled [`CatalogOffering`] rows from a parsed Models.dev catalog.
752 ///
753 /// Only text-chat offerings are emitted (TTS/audio-only rows stay in the parsed
754 /// catalog but are excluded from route candidates, matching
755 /// [`ModelsDevCatalog::provider_offerings`]). Each row is tagged
756 /// [`CatalogSource::Bundled`]. Provider rows link canonical models only through
757 /// an explicit `canonical_model_id` or legacy `base_model`. Namespaced entries in the canonical `models` map
758 /// fill missing offerings, retaining their map key as the canonical identity.
759 ///
760 /// Provider-row ids are kept verbatim from the Models.dev payload (the
761 /// committed bundled asset already uses CodeWhale ids). Namespaced canonical
762 /// keys (`xiaomi/mimo-v2.6-pro`) name an upstream vendor, so their namespace is
763 /// normalized onto the CodeWhale provider id here too (#6396). Live refresh
764 /// also normalizes provider-row aliases via [`live_offerings_from_models_dev`].
765 #[must_use]
766 pub fn bundled_offerings_from_models_dev(catalog: &ModelsDevCatalog) -> Vec<CatalogOffering> {
767 offerings_from_models_dev(catalog, CatalogSource::Bundled, false)
768 }
769
770 /// Hydrate live [`CatalogOffering`] rows from a fetched Models.dev catalog (#4187).
771 ///
772 /// Same text-chat filter as [`bundled_offerings_from_models_dev`], but each row
773 /// is tagged [`CatalogSource::ModelsDevLive`] with the fetch timestamp, so a
774 /// refresh lands on layer 10: above the bundled seed it supersedes, below the
775 /// signed cloud layer that may correct it, and far below a provider roster.
776 /// Codewhale's [`corrections`] are applied here as they are to the seed, so a
777 /// refresh cannot undo one.
778 /// Provider keys are normalized onto CodeWhale [`crate::ProviderKind`] ids when
779 /// an alias match exists (`moonshotai` → `moonshot`, `togetherai` → `together`,
780 /// `zhipuai` → `zai`, …); unknown Models.dev providers keep their upstream id so
781 /// they stay discoverable without becoming executable routes.
782 ///
783 /// These rows deliberately carry no base-URL fingerprint. This function used to
784 /// stamp [`CatalogSource::Live`] with the models.dev URL's fingerprint, which
785 /// made every enriched row claim to be a provider-owned roster fetched from an
786 /// endpoint nobody bills against: signed patches were skipped as "from a higher
787 /// layer", the price was labelled `ProviderLive` and then failed its endpoint
788 /// check, and route lookup dropped the row for the same mismatch. Models.dev is
789 /// a public catalog scoped to a model, exactly like the layer-0 seed.
790 #[must_use]
791 pub fn live_offerings_from_models_dev(
792 catalog: &ModelsDevCatalog,
793 fetched_at: u64,
794 ) -> Vec<CatalogOffering> {
795 let mut rows =
796 offerings_from_models_dev(catalog, CatalogSource::ModelsDevLive { fetched_at }, true);
797 corrections::bundled_corrections().apply_to(&mut rows);
798 rows
799 }
800
801 fn offerings_from_models_dev(
802 catalog: &ModelsDevCatalog,
803 source: CatalogSource,
804 normalize_provider_ids: bool,
805 ) -> Vec<CatalogOffering> {
806 let mut out = Vec::new();
807 let mut provider_rows = BTreeSet::new();
808 // Unknown upstream ids remain discoverable catalog rows, not routes.
809 let normalized = |raw_id: &str| {
810 crate::ProviderKind::parse(raw_id)
811 .map(|kind| kind.as_str().to_string())
812 .unwrap_or_else(|| raw_id.to_string())
813 };
814 let provider_id = |raw_id: &str| {
815 if normalize_provider_ids {
816 normalized(raw_id)
817 } else {
818 raw_id.to_string()
819 }
820 };
821 for (provider_key, provider) in &catalog.providers {
822 let raw_id = if provider.id.trim().is_empty() {
823 provider_key.trim()
824 } else {
825 provider.id.trim()
826 };
827 if raw_id.is_empty() {
828 continue;
829 }
830 let provider_id = provider_id(raw_id);
831 // Gap-filling compares on the normalized identity, so a verbatim
832 // bundled `moonshotai` row still shadows `moonshotai/<model>`.
833 let route_id = normalized(raw_id);
834 for (model_key, model) in &provider.models {
835 let wire_model_id = if model.id.trim().is_empty() {
836 model_key.trim()
837 } else {
838 model.id.trim()
839 };
840 if wire_model_id.is_empty() {
841 continue;
842 }
843 provider_rows.insert((route_id.clone(), wire_model_id.to_string()));
844 if !model.supports_text_chat() {
845 continue;
846 }
847 // OpenCode Zen is model-aware: its catalog names each model's AI
848 // SDK package, which is the wire (#6705). Every other provider's
849 // endpoint key stays the Chat placeholder its fixed policy ignores.
850 // A deprecated Zen row stays visible but is not a route: Zen no
851 // longer serves it, so sending it would be a guaranteed upstream
852 // failure instead of a local refusal that names the reason.
853 let endpoint_key = if route_id != crate::ProviderKind::OpencodeZen.as_str() {
854 "chat"
855 } else if model.is_deprecated() {
856 crate::route::OPENCODE_ZEN_DEPRECATED_ENDPOINT_KEY
857 } else {
858 crate::route::opencode_zen_endpoint_key_for_npm(
859 model
860 .provider
861 .as_ref()
862 .and_then(|transport| transport.npm.as_deref())
863 .or(provider.npm.as_deref()),
864 )
865 };
866 out.push(CatalogOffering {
867 provider: provider_id.clone(),
868 wire_model_id: wire_model_id.to_string(),
869 canonical_model: model.canonical_id().map(str::to_string),
870 endpoint_key: endpoint_key.to_string(),
871 default_for_provider: model.default_for_provider,
872 family: model.family.clone(),
873 name: model.name.clone(),
874 description: model.description.clone(),
875 model_type: model.model_type.clone(),
876 knowledge: model.knowledge.clone(),
877 release_date: model.release_date.clone(),
878 last_updated: model.last_updated.clone(),
879 temperature: model.temperature,
880 open_weights: model.open_weights,
881 interleaved: model.interleaved.clone(),
882 transport: model.provider.clone(),
883 provider_api: provider.api.clone(),
884 provider_npm: provider.npm.clone(),
885 status: model.status.clone(),
886 experimental: model.experimental.clone(),
887 limit: model.limit.clone(),
888 cost: model.cost.clone(),
889 modalities: model.modalities.clone(),
890 attachment: model.attachment,
891 reasoning: model.reasoning,
892 tool_call: model.tool_call,
893 structured_output: model.structured_output,
894 reasoning_options: model.reasoning_options.clone().unwrap_or_default(),
895 reasoning_options_present: model.reasoning_options.is_some(),
896 source: source.clone(),
897 cost_source: None,
898 modalities_source: None,
899 ..Default::default()
900 });
901 }
902 }
903
904 // Namespaced model facts fill gaps without overriding provider-owned rows,
905 // including their non-chat exclusions. The namespace is always the
906 // upstream vendor id (`xiaomi`, `moonshotai`), never a CodeWhale provider
907 // id, so it is normalized in both modes: that is what lets an
908 // upstream-shaped offline seed land on the same route as live refresh
909 // (#6396). Bare keys cannot name a provider and are skipped.
910 for (canonical_id, model) in &catalog.models {
911 let Some((provider_key, wire_model_id)) = canonical_id.trim().split_once('/') else {
912 continue;
913 };
914 let provider_key = provider_key.trim();
915 let wire_model_id = wire_model_id.trim();
916 if provider_key.is_empty() || wire_model_id.is_empty() || !model.supports_text_chat() {
917 continue;
918 }
919 let provider = normalized(provider_key);
920 // A canonical fact names no transport, and Zen's wire is per model.
921 if provider == crate::ProviderKind::OpencodeZen.as_str() {
922 continue;
923 }
924 if !provider_rows.insert((provider.clone(), wire_model_id.to_string())) {
925 continue;
926 }
927 out.push(CatalogOffering {
928 provider,
929 wire_model_id: wire_model_id.to_string(),
930 canonical_model: Some(canonical_id.trim().to_string()),
931 endpoint_key: "chat".to_string(),
932 family: model.family.clone(),
933 name: model.name.clone(),
934 description: model.description.clone(),
935 model_type: model.model_type.clone(),
936 knowledge: model.knowledge.clone(),
937 release_date: model.release_date.clone(),
938 last_updated: model.last_updated.clone(),
939 temperature: model.temperature,
940 open_weights: model.open_weights,
941 license: model.license.clone(),
942 links: model.links.clone(),
943 weights: model.weights.clone(),
944 benchmarks: model.benchmarks.clone(),
945 limit: model.limit.clone(),
946 modalities: model.modalities.clone(),
947 attachment: model.attachment,
948 reasoning: model.reasoning,
949 tool_call: model.tool_call,
950 structured_output: model.structured_output,
951 source: source.clone(),
952 ..Default::default()
953 });
954 }
955 out
956 }
957
958 /// A provider's live `/models` refresh result, scoped to a base-URL fingerprint.
959 ///
960 /// Returned as a delta rather than mutating any global model state directly, per
961 /// the #3385 architecture contract.
962 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
963 pub struct ProviderCatalogDelta {
964 /// Provider this delta belongs to.
965 pub provider: String,
966 /// Fingerprint of the base URL the rows were fetched from.
967 pub base_url_fingerprint: String,
968 /// Unix seconds the rows were fetched at.
969 pub fetched_at: u64,
970 /// Live offering rows. Sources are normalized to `Live` on ingest.
971 pub offerings: Vec<CatalogOffering>,
972 }
973
974 /// Why a provider live catalog refresh did not produce usable rows.
975 ///
976 /// Every variant must leave previously cached / bundled / configured rows
977 /// available; a refresh failure is never fatal to model selection.
978 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
979 #[serde(rename_all = "snake_case")]
980 pub enum CatalogRefreshError {
981 /// 401 — auth missing or invalid.
982 Unauthorized,
983 /// 403 — auth present but not permitted.
984 Forbidden,
985 /// 404 — provider does not expose `/models` at this base URL.
986 NotFound,
987 /// 429 — rate limited.
988 RateLimited,
989 /// Response was not parseable as a model listing.
990 InvalidResponse,
991 /// Provider returned an empty model list.
992 EmptyList,
993 /// Transport / network failure.
994 Network,
995 }
996
997 impl CatalogRefreshError {
998 #[must_use]
999 pub fn label(self) -> &'static str {
1000 match self {
1001 Self::Unauthorized => "unauthorized",
1002 Self::Forbidden => "forbidden",
1003 Self::NotFound => "not found",
1004 Self::RateLimited => "rate limited",
1005 Self::InvalidResponse => "invalid response",
1006 Self::EmptyList => "empty list",
1007 Self::Network => "network error",
1008 }
1009 }
1010 }
1011
1012 /// Freshness / health of a provider's cached live catalog.
1013 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1014 #[serde(tag = "state", rename_all = "snake_case")]
1015 pub enum CatalogStatus {
1016 /// Cached rows are within their TTL.
1017 Fresh,
1018 /// Cached rows exist but are past their TTL.
1019 Stale { age_secs: u64 },
1020 /// The last refresh failed; any rows present are from an earlier success.
1021 Failed { reason: CatalogRefreshError },
1022 /// No refresh has been attempted for this provider + base URL.
1023 Unknown,
1024 }
1025
1026 /// A secret-free cached provider catalog for one provider + base-URL fingerprint.
1027 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1028 pub struct CachedProviderCatalog {
1029 /// Provider id.
1030 pub provider: String,
1031 /// Base-URL fingerprint the rows were fetched from.
1032 pub base_url_fingerprint: String,
1033 /// Unix seconds of the last successful fetch (unchanged on failure).
1034 pub fetched_at: u64,
1035 /// Time-to-live, in seconds, after which rows are considered stale.
1036 pub ttl_secs: u64,
1037 /// Cached live offering rows (possibly empty after a failure with no prior).
1038 pub offerings: Vec<CatalogOffering>,
1039 /// Last known status of this entry.
1040 pub status: CatalogStatus,
1041 }
1042
1043 impl CachedProviderCatalog {
1044 /// Age in seconds relative to `now_unix`, saturating at zero for clock skew.
1045 #[must_use]
1046 pub fn age_secs(&self, now_unix: u64) -> u64 {
1047 now_unix.saturating_sub(self.fetched_at)
1048 }
1049
1050 /// Whether the cached rows are past their TTL at `now_unix`.
1051 ///
1052 /// A `ttl_secs` of zero means "always stale" (never serve as fresh).
1053 #[must_use]
1054 pub fn is_stale(&self, now_unix: u64) -> bool {
1055 self.fetched_at.saturating_sub(now_unix) > 300 || self.age_secs(now_unix) >= self.ttl_secs
1056 }
1057
1058 /// Whether this entry may contribute live offerings at `now_unix`.
1059 ///
1060 /// An entry is fresh only when it is within its TTL **and** its last
1061 /// recorded refresh succeeded. A `Failed` entry is never fresh even inside
1062 /// its TTL window — its rows survive a failed refresh for explicit fallback
1063 /// display via [`ProviderCatalogCache::get`], but they are not served as
1064 /// current live data.
1065 #[must_use]
1066 pub fn is_fresh(&self, now_unix: u64) -> bool {
1067 !self.is_stale(now_unix) && !matches!(self.status, CatalogStatus::Failed { .. })
1068 }
1069 }
1070
1071 /// A secret-free store of cached provider catalogs, keyed by provider + base-URL
1072 /// fingerprint.
1073 ///
1074 /// Scoping rule (#3385): the SAME provider on DIFFERENT base URLs must not share
1075 /// rows, and DIFFERENT providers on the same base URL must not share rows.
1076 #[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
1077 pub struct ProviderCatalogCache {
1078 /// Entries keyed by [`ProviderCatalogCache::cache_key`].
1079 #[serde(default)]
1080 pub entries: BTreeMap<String, CachedProviderCatalog>,
1081 }
1082
1083 impl ProviderCatalogCache {
1084 /// Construct an empty cache.
1085 #[must_use]
1086 pub fn new() -> Self {
1087 Self::default()
1088 }
1089
1090 /// Compute the composite cache key for a provider + base-URL fingerprint.
1091 #[must_use]
1092 pub fn cache_key(provider: &str, base_url_fingerprint: &str) -> String {
1093 // Unit separator avoids ambiguity between provider and fingerprint.
1094 format!("{}\u{1f}{}", provider.trim(), base_url_fingerprint.trim())
1095 }
1096
1097 /// Look up a cached entry by provider + base-URL fingerprint.
1098 #[must_use]
1099 pub fn get(
1100 &self,
1101 provider: &str,
1102 base_url_fingerprint: &str,
1103 ) -> Option<&CachedProviderCatalog> {
1104 self.entries
1105 .get(&Self::cache_key(provider, base_url_fingerprint))
1106 }
1107
1108 /// Record a successful refresh, replacing any prior entry for this scope.
1109 ///
1110 /// Offering sources are normalized to [`CatalogSource::Live`] with the
1111 /// delta's fingerprint and `fetched_at`, so cached rows always carry honest
1112 /// provenance regardless of how the delta was assembled.
1113 pub fn record_success(&mut self, delta: ProviderCatalogDelta, ttl_secs: u64) {
1114 let ProviderCatalogDelta {
1115 provider,
1116 base_url_fingerprint,
1117 fetched_at,
1118 offerings,
1119 } = delta;
1120 let offerings = offerings
1121 .into_iter()
1122 .map(|mut row| {
1123 row.source = CatalogSource::Live {
1124 base_url_fingerprint: base_url_fingerprint.clone(),
1125 fetched_at,
1126 };
1127 row
1128 })
1129 .collect();
1130 let key = Self::cache_key(&provider, &base_url_fingerprint);
1131 self.entries.insert(
1132 key,
1133 CachedProviderCatalog {
1134 provider,
1135 base_url_fingerprint,
1136 fetched_at,
1137 ttl_secs,
1138 offerings,
1139 status: CatalogStatus::Fresh,
1140 },
1141 );
1142 }
1143
1144 /// Record a refresh failure.
1145 ///
1146 /// Previously cached rows for this scope are preserved (so the UI can still
1147 /// offer them with a visible "stale/failed" status); only the status is
1148 /// updated. When no prior entry exists, an empty `Failed` entry is created so
1149 /// the failure is observable.
1150 pub fn record_failure(
1151 &mut self,
1152 provider: &str,
1153 base_url_fingerprint: &str,
1154 reason: CatalogRefreshError,
1155 ) {
1156 let key = Self::cache_key(provider, base_url_fingerprint);
1157 match self.entries.get_mut(&key) {
1158 Some(entry) => entry.status = CatalogStatus::Failed { reason },
1159 None => {
1160 self.entries.insert(
1161 key,
1162 CachedProviderCatalog {
1163 provider: provider.trim().to_string(),
1164 base_url_fingerprint: base_url_fingerprint.trim().to_string(),
1165 fetched_at: 0,
1166 ttl_secs: 0,
1167 offerings: Vec::new(),
1168 status: CatalogStatus::Failed { reason },
1169 },
1170 );
1171 }
1172 }
1173 }
1174
1175 /// The resolved status of an entry at `now_unix`.
1176 ///
1177 /// A `Fresh`-recorded entry that has since aged past its TTL reports
1178 /// `Stale`; `Failed`/`Unknown` are returned as stored.
1179 #[must_use]
1180 pub fn status(
1181 &self,
1182 provider: &str,
1183 base_url_fingerprint: &str,
1184 now_unix: u64,
1185 ) -> CatalogStatus {
1186 match self.get(provider, base_url_fingerprint) {
1187 None => CatalogStatus::Unknown,
1188 Some(entry) => match &entry.status {
1189 CatalogStatus::Failed { reason } => CatalogStatus::Failed { reason: *reason },
1190 CatalogStatus::Unknown => CatalogStatus::Unknown,
1191 CatalogStatus::Fresh | CatalogStatus::Stale { .. } => {
1192 if entry.is_stale(now_unix) {
1193 CatalogStatus::Stale {
1194 age_secs: entry.age_secs(now_unix),
1195 }
1196 } else {
1197 CatalogStatus::Fresh
1198 }
1199 }
1200 },
1201 }
1202 }
1203
1204 /// Fresh (within-TTL) live offerings for one provider + base URL at
1205 /// `now_unix`. Stale or failed entries contribute nothing here; callers fall
1206 /// back to bundled/configured rows and surface the status separately.
1207 #[must_use]
1208 pub fn fresh_offerings(
1209 &self,
1210 provider: &str,
1211 base_url_fingerprint: &str,
1212 now_unix: u64,
1213 ) -> Vec<CatalogOffering> {
1214 match self.get(provider, base_url_fingerprint) {
1215 Some(entry) if entry.is_fresh(now_unix) => entry.offerings.clone(),
1216 _ => Vec::new(),
1217 }
1218 }
1219
1220 /// All fresh live offerings across every cached provider + base URL.
1221 #[must_use]
1222 pub fn all_fresh_offerings(&self, now_unix: u64) -> Vec<CatalogOffering> {
1223 self.entries
1224 .values()
1225 .filter(|entry| entry.is_fresh(now_unix))
1226 .flat_map(|entry| entry.offerings.clone())
1227 .collect()
1228 }
1229
1230 /// Live offerings that pickers may still show: fresh rows plus stale / prior
1231 /// rows that survived a failed refresh (#4139).
1232 ///
1233 /// Unlike [`Self::all_fresh_offerings`], this keeps past-TTL and
1234 /// `Failed`-status entries as long as they still hold offering rows. Empty
1235 /// entries contribute nothing; callers fall back to the bundled snapshot.
1236 /// `now_unix` is accepted for API symmetry with the fresh helper (age chips
1237 /// live above this layer).
1238 #[must_use]
1239 pub fn all_visible_offerings(&self, _now_unix: u64) -> Vec<CatalogOffering> {
1240 self.entries
1241 .values()
1242 .filter(|entry| !entry.offerings.is_empty())
1243 .flat_map(|entry| entry.offerings.clone())
1244 .collect()
1245 }
1246 }
1247
1248 /// A compiled, layer-merged catalog snapshot.
1249 #[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
1250 pub struct CatalogSnapshot {
1251 /// Merged offerings, de-duplicated by (provider, wire id), in stable order.
1252 pub offerings: Vec<CatalogOffering>,
1253 }
1254
1255 impl CatalogSnapshot {
1256 /// Project routing offerings for `RouteResolver::from_offerings`.
1257 #[must_use]
1258 pub fn to_offerings(&self) -> Vec<ProviderModelOffering> {
1259 self.offerings
1260 .iter()
1261 .map(CatalogOffering::to_offering)
1262 .collect()
1263 }
1264
1265 /// All offerings for one provider id.
1266 #[must_use]
1267 pub fn offerings_for_provider(&self, provider: &str) -> Vec<&CatalogOffering> {
1268 self.offerings
1269 .iter()
1270 .filter(|row| row.provider == provider)
1271 .collect()
1272 }
1273 }
1274
1275 /// Builds a [`CatalogSnapshot`] by merging layers in precedence order.
1276 ///
1277 /// Last writer wins per `(provider, wire id)` field. Policy DENY is applied
1278 /// after every layer and is never overridden:
1279 ///
1280 /// ```text
1281 /// 0 bundled committed models.dev-shaped snapshot
1282 /// 10 live models.dev models.dev refresh
1283 /// 12 codewhale bundled corrections, applied as rows 0 and 10
1284 /// are hydrated (see [`corrections`])
1285 /// 15 cloud facts verified field patches (default off)
1286 /// 20 provider per-provider /v1/models refresh
1287 /// 30 config config.toml [providers.*] overrides
1288 /// 40 user user approved set
1289 /// policy DENY last, never overridden
1290 /// ```
1291 ///
1292 /// Layer 25 in `docs/CATALOG_REFRESH.md` — the Codewhale account roster — is
1293 /// deliberately absent here: an account-scoped roster is entitlement, not a
1294 /// public catalog layer, so it is enforced where the credential is known
1295 /// (`provider_lake`'s endpoint-authoritative path) and never compiled into a
1296 /// shared snapshot.
1297 ///
1298 /// [`Self::with_live`] remains the combined live bucket so existing callers
1299 /// keep working; prefer [`Self::with_models_dev_live`] / [`Self::with_provider_live`]
1300 /// for the split.
1301 #[derive(Debug, Clone, Default)]
1302 pub struct CatalogCompiler {
1303 bundled: Vec<CatalogOffering>,
1304 models_dev_live: Vec<CatalogOffering>,
1305 cloud_facts: Option<(crate::cloud_facts::ScopedFacts, u64)>,
1306 provider_live: Vec<CatalogOffering>,
1307 config: Vec<CatalogOffering>,
1308 overrides: Vec<CatalogOffering>,
1309 policy: crate::route::CatalogPolicy,
1310 }
1311
1312 impl CatalogCompiler {
1313 /// Start an empty compiler.
1314 #[must_use]
1315 pub fn new() -> Self {
1316 Self::default()
1317 }
1318
1319 /// Add bundled (lowest-precedence) rows.
1320 #[must_use]
1321 pub fn with_bundled(mut self, rows: Vec<CatalogOffering>) -> Self {
1322 self.bundled.extend(rows);
1323 self
1324 }
1325
1326 /// Seed bundled rows from a parsed Models.dev catalog.
1327 #[must_use]
1328 pub fn with_models_dev(mut self, catalog: &ModelsDevCatalog) -> Self {
1329 self.bundled
1330 .extend(bundled_offerings_from_models_dev(catalog));
1331 self
1332 }
1333
1334 /// Add live models.dev refresh rows (layer 10).
1335 #[must_use]
1336 pub fn with_models_dev_live(mut self, rows: Vec<CatalogOffering>) -> Self {
1337 self.models_dev_live.extend(rows);
1338 self
1339 }
1340
1341 /// Add live (combined models.dev + provider) rows.
1342 ///
1343 /// Prefer [`Self::with_models_dev_live`] / [`Self::with_provider_live`].
1344 /// Source ownership places each row on the corresponding side of the
1345 /// signed cloud layer; a legacy provider row never becomes a lower layer.
1346 #[must_use]
1347 pub fn with_live(mut self, rows: Vec<CatalogOffering>) -> Self {
1348 for row in rows {
1349 if matches!(row.source, CatalogSource::ModelsDevLive { .. }) {
1350 self.models_dev_live.push(row);
1351 } else {
1352 self.provider_live.push(row);
1353 }
1354 }
1355 self
1356 }
1357
1358 /// Apply signed facts between generic catalogs and provider-owned rows.
1359 #[must_use]
1360 pub fn with_cloud_facts(
1361 mut self,
1362 facts: &crate::cloud_facts::ScopedFacts,
1363 fetched_at: u64,
1364 ) -> Self {
1365 self.cloud_facts = Some((facts.clone(), fetched_at));
1366 self
1367 }
1368
1369 /// Add per-provider `/v1/models` refresh rows (layer 20).
1370 #[must_use]
1371 pub fn with_provider_live(mut self, rows: Vec<CatalogOffering>) -> Self {
1372 self.provider_live.extend(rows);
1373 self
1374 }
1375
1376 /// Add `config.toml` `[providers.*]` override rows (layer 30).
1377 #[must_use]
1378 pub fn with_config(mut self, rows: Vec<CatalogOffering>) -> Self {
1379 self.config.extend(rows);
1380 self
1381 }
1382
1383 /// Add user/custom override (highest catalog-layer precedence) rows.
1384 #[must_use]
1385 pub fn with_overrides(mut self, rows: Vec<CatalogOffering>) -> Self {
1386 self.overrides.extend(rows);
1387 self
1388 }
1389
1390 /// Attach policy evaluated after every layer. DENY is never overridden.
1391 #[must_use]
1392 pub fn with_policy(mut self, policy: crate::route::CatalogPolicy) -> Self {
1393 self.policy = policy;
1394 self
1395 }
1396
1397 /// Merge all layers into a deterministic snapshot, then apply policy DENY.
1398 #[must_use]
1399 pub fn compile(self) -> CatalogSnapshot {
1400 let mut merged: BTreeMap<(String, String), CatalogOffering> = BTreeMap::new();
1401 for row in self.bundled.into_iter().chain(self.models_dev_live) {
1402 merged.insert(row.merge_key(), row);
1403 }
1404 if let Some((facts, fetched_at)) = self.cloud_facts {
1405 crate::cloud_facts::catalog_patch::apply_model_patches(&mut merged, &facts, fetched_at);
1406 }
1407 for mut row in self
1408 .provider_live
1409 .into_iter()
1410 .chain(self.config)
1411 .chain(self.overrides)
1412 {
1413 if let Some(lower) = merged.get(&row.merge_key()) {
1414 let base_url = row.provider_api.clone();
1415 row.complete_from(lower, base_url.as_deref());
1416 }
1417 merged.insert(row.merge_key(), row);
1418 }
1419 let offerings = merged
1420 .into_values()
1421 .filter(|row| self.policy.allows(&row.provider, &row.wire_model_id))
1422 .collect();
1423 CatalogSnapshot { offerings }
1424 }
1425 }
1426
1427 /// Normalize a base URL and fingerprint it for cache scoping.
1428 ///
1429 /// Normalization folds case in the scheme/host, trims trailing slashes, and
1430 /// drops a default-port suffix, so cosmetically different spellings of the same
1431 /// endpoint share a cache scope while genuinely different endpoints do not. The
1432 /// fingerprint is a SHA-256 digest. Secret-bearing URLs are mapped to one
1433 /// constant redacted input before hashing, so userinfo, query credentials, and
1434 /// fragments never enter the digest function at all.
1435 #[must_use]
1436 pub fn base_url_fingerprint(base_url: &str) -> String {
1437 use sha2::Digest as _;
1438
1439 let normalized = secret_free_fingerprint_input(base_url);
1440 let digest = sha2::Sha256::digest(normalized.as_bytes());
1441 let mut out = String::with_capacity(digest.len() * 2);
1442 for byte in digest {
1443 use std::fmt::Write as _;
1444 let _ = write!(&mut out, "{byte:02x}");
1445 }
1446 out
1447 }
1448
1449 /// The conventional provider-table id for the Baseten known-good host.
1450 ///
1451 /// Baseten is an ordinary named `[providers.baseten]` row (#6289); this
1452 /// string is the identity the live-catalog path serves, not a wire-fact
1453 /// switch — every runtime behavior keys off [`endpoint_is_baseten`].
1454 pub const BASETEN_PROVIDER_ID: &str = "baseten";
1455
1456 /// Baseten Model APIs endpoint: the one hosted Chat Completions host whose
1457 /// wire facts differ from the generic shape (#6289).
1458 ///
1459 /// Baseten's `/models` uses its own response schema and returns an
1460 /// account-scoped roster, so response parsing, account-scoped cache
1461 /// isolation, and the reviewed per-token billing contract all key off this
1462 /// endpoint. Recognition is by endpoint fingerprint — never by what the user
1463 /// named the `[providers.<name>]` table — so renames and aliases cannot
1464 /// change wire handling.
1465 pub const BASETEN_BASE_URL: &str = "https://inference.baseten.co/v1";
1466
1467 /// The documented default model for the Baseten known-good host
1468 /// (`docs/PROVIDERS.md`). The live-catalog offering builder marks a
1469 /// discovered row with this wire id as the provider default.
1470 pub const BASETEN_DEFAULT_MODEL: &str = "deepseek-ai/DeepSeek-V4-Pro";
1471
1472 /// Whether `base_url` is Baseten's Model APIs endpoint.
1473 ///
1474 /// Compares fingerprints, not spellings, so a trailing slash or case
1475 /// difference in a user-configured URL still recognizes the host.
1476 #[must_use]
1477 pub fn endpoint_is_baseten(base_url: &str) -> bool {
1478 base_url_fingerprint(base_url) == base_url_fingerprint(BASETEN_BASE_URL)
1479 }
1480
1481 pub const PRIME_INTELLECT_BASE_URL: &str = "https://api.pinference.ai/api/v1";
1482
1483 pub const PRIME_INTELLECT_DEFAULT_MODEL: &str = "thinkingmachines/inkling-2-small";
1484
1485 #[must_use]
1486 pub fn endpoint_is_prime_intellect(base_url: &str) -> bool {
1487 base_url_fingerprint(base_url) == base_url_fingerprint(PRIME_INTELLECT_BASE_URL)
1488 }
1489
1490 fn secret_free_fingerprint_input(base_url: &str) -> String {
1491 const REDACTED: &str = "invalid-or-secret-bearing-url";
1492 let trimmed = base_url.trim();
1493 if let Some((scheme, rest)) = trimmed.split_once("://") {
1494 let scheme = scheme.to_ascii_lowercase();
1495 if !matches!(scheme.as_str(), "http" | "https") {
1496 return REDACTED.to_string();
1497 }
1498 let authority_end = rest.find('/').unwrap_or(rest.len());
1499 let authority_with_userinfo = &rest[..authority_end];
1500 if authority_with_userinfo.contains(['?', '#']) {
1501 return REDACTED.to_string();
1502 }
1503 let authority = authority_with_userinfo
1504 .rsplit_once('@')
1505 .map_or(authority_with_userinfo, |(_, host)| host);
1506 if authority.is_empty() {
1507 return REDACTED.to_string();
1508 }
1509 let path = rest[authority_end..]
1510 .split(['?', '#'])
1511 .next()
1512 .unwrap_or_default();
1513 return normalize_base_url(&format!("{scheme}://{authority}{path}"));
1514 }
1515 // Scheme-less input still has an authority, and it can still carry
1516 // `user:pass@` userinfo. Strip it exactly as the scheme branch does, so the
1517 // digest input never contains a credential.
1518 let without_query = trimmed.split(['?', '#']).next().unwrap_or_default();
1519 let authority_end = without_query.find('/').unwrap_or(without_query.len());
1520 let authority = &without_query[..authority_end];
1521 let authority = authority
1522 .rsplit_once('@')
1523 .map_or(authority, |(_, host)| host);
1524 if authority.is_empty() {
1525 return REDACTED.to_string();
1526 }
1527 normalize_base_url(&format!("{authority}{}", &without_query[authority_end..]))
1528 }
1529
1530 fn normalize_base_url(base_url: &str) -> String {
1531 let trimmed = base_url.trim().trim_end_matches('/');
1532 // Lowercase only the scheme://host authority; leave the path case-sensitive.
1533 if let Some(idx) = trimmed.find("://") {
1534 let (scheme, rest) = trimmed.split_at(idx);
1535 let scheme = scheme.to_ascii_lowercase();
1536 let rest = &rest[3..];
1537 let (authority, path) = match rest.find('/') {
1538 Some(p) => (&rest[..p], &rest[p..]),
1539 None => (rest, ""),
1540 };
1541 let authority = authority.to_ascii_lowercase();
1542 // Strip only the scheme's own default port, so a non-default pairing
1543 // such as `http://host:443` stays distinct from `http://host`.
1544 let default_port = match scheme.as_str() {
1545 "https" => Some(":443"),
1546 "http" => Some(":80"),
1547 _ => None,
1548 };
1549 let authority = default_port
1550 .and_then(|port| authority.strip_suffix(port))
1551 .unwrap_or(&authority);
1552 format!("{scheme}://{authority}{path}")
1553 } else {
1554 trimmed.to_ascii_lowercase()
1555 }
1556 }
1557
1558 /// Current unix time in seconds, for callers assembling deltas / cache entries.
1559 ///
1560 /// Pure cache logic takes `now_unix` explicitly so it stays deterministic in
1561 /// tests; this helper is the one place that reads the wall clock.
1562 #[must_use]
1563 pub fn now_unix() -> u64 {
1564 SystemTime::now()
1565 .duration_since(UNIX_EPOCH)
1566 .map(|d| d.as_secs())
1567 .unwrap_or(0)
1568 }
1569
1570 #[cfg(test)]
1571 mod tests;
1572
1572 lines RUST