Skip to main content

codewhale_config/
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; #4188):
10//!
11//! ```text
12//! bundled Models.dev snapshot       (offline/stale fallback only — not competing truth)
13//!   < live Models.dev / provider `/models` cache
14//!   < user / custom overrides        (custom endpoints, pinned models, explicit facts)
15//! ```
16//!
17//! After #4187, live Models.dev rows are preferred whenever present. The bundled
18//! asset remains so offline startup and failed refreshes still resolve defaults.
19//!
20//! Invariants preserved from #2608 / #3497:
21//! - A catalog row is **not** an executable route. Rows still compile through
22//!   `RouteResolver` into a `ReadyRouteCandidate` before execution.
23//! - `wire_model_id` is kept separate from `canonical_model`; a provider row may
24//!   not expose a canonical `base_model` join, and a prefix never proves
25//!   canonical ownership.
26//! - Unknown / custom / local rows are supported with explicit provenance and a
27//!   `None` canonical model.
28//!
29//! The on-disk cache format intentionally uses plain `String` identity fields
30//! rather than the internal route newtypes, so the persisted shape is decoupled
31//! from internal types and trivially auditable for "no secrets" (see
32//! [`ProviderCatalogCache`] tests).
33
34use std::collections::BTreeMap;
35use std::time::{SystemTime, UNIX_EPOCH};
36
37use serde::{Deserialize, Serialize};
38use serde_json::Value;
39
40use crate::models_dev::{ModelsDevCatalog, ModelsDevCost, ModelsDevLimit, ModelsDevModalities};
41use crate::route::{ModelId, ProviderId, ProviderModelOffering, RouteLimits, WireModelId};
42
43/// Provenance of a catalog row. Drives layer precedence and UI provenance.
44#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
45#[serde(tag = "kind", rename_all = "snake_case")]
46pub enum CatalogSource {
47    /// Offline/stale bundled seed (Models.dev-shaped snapshot). Not competing
48    /// truth — live Models.dev rows override this layer (#4188).
49    #[default]
50    Bundled,
51    /// A provider live `/models` row, scoped to a base-URL fingerprint and the
52    /// unix timestamp it was fetched at.
53    Live {
54        base_url_fingerprint: String,
55        fetched_at: u64,
56    },
57    /// A user / custom override (custom endpoint, pinned model, explicit facts).
58    UserOverride,
59}
60
61/// One catalog-layer offering row.
62///
63/// This carries the routing identity (provider + wire id + optional canonical
64/// model + endpoint) plus the offering-owned Models.dev facts CodeWhale wants to
65/// preserve (family, limits, cost, reasoning support/options). It is a superset
66/// of [`ProviderModelOffering`]; use [`CatalogOffering::to_offering`] to project
67/// the minimal routing identity the resolver consumes.
68#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
69pub struct CatalogOffering {
70    /// Provider id serving this offering.
71    pub provider: String,
72    /// Provider-owned wire id sent on the request (verbatim).
73    pub wire_model_id: String,
74    /// Canonical model identity, only when an explicit join exists.
75    #[serde(default, skip_serializing_if = "Option::is_none")]
76    pub canonical_model: Option<String>,
77    /// Endpoint key the offering is served on (e.g. `chat`).
78    pub endpoint_key: String,
79    /// Whether this is the provider's default offering.
80    #[serde(default)]
81    pub default_for_provider: bool,
82    /// Model family/series as exposed for this offering (e.g. `glm`, `deepseek`).
83    #[serde(default, skip_serializing_if = "Option::is_none")]
84    pub family: Option<String>,
85    /// Token limits for this offering, when known.
86    #[serde(default, skip_serializing_if = "Option::is_none")]
87    pub limit: Option<ModelsDevLimit>,
88    /// Provider-scoped pricing, when known.
89    #[serde(default, skip_serializing_if = "Option::is_none")]
90    pub cost: Option<ModelsDevCost>,
91    /// Input/output modalities for this offering, when known. Carried as the
92    /// raw Models.dev shape so a factual `text` vs `multimodal` label can be
93    /// derived without guessing; `None` means the layer did not state it (an
94    /// unknown, not "text-only").
95    #[serde(default, skip_serializing_if = "Option::is_none")]
96    pub modalities: Option<ModelsDevModalities>,
97    /// Whether this provider offering accepts attachments, when known.
98    #[serde(default, skip_serializing_if = "Option::is_none")]
99    pub attachment: Option<bool>,
100    /// Whether this offering supports reasoning, when known.
101    #[serde(default, skip_serializing_if = "Option::is_none")]
102    pub reasoning: Option<bool>,
103    /// Whether tool calling is supported, when known (#4115).
104    #[serde(default, skip_serializing_if = "Option::is_none")]
105    pub tool_call: Option<bool>,
106    /// Whether structured output is supported, when known.
107    #[serde(default, skip_serializing_if = "Option::is_none")]
108    pub structured_output: Option<bool>,
109    /// Provider-scoped reasoning controls / accepted effort metadata. Kept as
110    /// raw JSON so the same model family served through different gateways can
111    /// expose different effort vocabularies without lossy collapsing.
112    #[serde(default, skip_serializing_if = "Vec::is_empty")]
113    pub reasoning_options: Vec<Value>,
114    /// Where this row came from.
115    pub source: CatalogSource,
116}
117
118impl CatalogOffering {
119    /// The provider id as a route newtype.
120    #[must_use]
121    pub fn provider_id(&self) -> ProviderId {
122        ProviderId::from(self.provider.clone())
123    }
124
125    /// The wire model id as a route newtype.
126    #[must_use]
127    pub fn wire_id(&self) -> WireModelId {
128        WireModelId::from(self.wire_model_id.clone())
129    }
130
131    /// Project the minimal routing identity the resolver consumes.
132    ///
133    /// The catalog deliberately carries richer facts than routing needs; this
134    /// drops most of them so `RouteResolver::from_offerings` stays the single
135    /// seam. The route-facing pricing meter is the exception: it is projected
136    /// here (where the offering's sourced `cost` is in scope) via
137    /// [`crate::pricing::route_pricing_sku`] so a resolved candidate can carry
138    /// honest pricing without the route layer ever seeing raw cost (#3085).
139    #[must_use]
140    pub fn to_offering(&self) -> ProviderModelOffering {
141        ProviderModelOffering {
142            provider: self.provider_id(),
143            canonical_model: self.canonical_model.clone().map(ModelId::from),
144            wire_model_id: self.wire_id(),
145            endpoint_key: self.endpoint_key.clone(),
146            default_for_provider: self.default_for_provider,
147            limits: self
148                .limit
149                .as_ref()
150                .map(RouteLimits::from)
151                .unwrap_or_default(),
152            capabilities: crate::route::RouteCapabilities {
153                attachments: crate::route::CapabilityState::from_optional_bool(self.attachment),
154                reasoning: crate::route::CapabilityState::from_optional_bool(self.reasoning),
155                native_tool_calls: crate::route::CapabilityState::from_optional_bool(
156                    self.tool_call,
157                ),
158                structured_output: crate::route::CapabilityState::from_optional_bool(
159                    self.structured_output,
160                ),
161                server_side_web_search: crate::route::documented_server_side_web_search(
162                    &self.provider,
163                    &self.wire_model_id,
164                ),
165                ..crate::route::RouteCapabilities::default()
166            },
167            pricing: crate::pricing::route_pricing_sku(self),
168        }
169    }
170
171    /// Stable identity key for de-duplication and layer merging.
172    fn merge_key(&self) -> (String, String) {
173        (self.provider.clone(), self.wire_model_id.clone())
174    }
175}
176
177/// Committed offline/stale Models.dev-shaped catalog snapshot (#3385 / #4188).
178///
179/// This is **not** a competing curated source of truth. Preferred metadata comes
180/// from the live Models.dev catalog (#4187). The bundled asset is a compact
181/// network-free seed of verified in-repo defaults (context/output from
182/// `crates/tui/src/models.rs`, USD pricing from `crates/tui/src/pricing.rs`) so
183/// [`crate::route::RouteResolver::new`] and pickers still work offline or after
184/// a failed refresh. See the asset's `_meta.role` / `_meta.source` and the
185/// honesty rule on omitted pricing (`UnknownOrStale`, never a fabricated zero).
186pub const BUNDLED_MODELS_DEV_JSON: &str = include_str!("../assets/models_dev.bundled.json");
187
188/// Parse the committed bundled Models.dev snapshot.
189///
190/// # Panics
191/// Panics only if the committed asset is not valid Models.dev JSON. The
192/// `tests::bundled_asset_parses` guard makes that a build-time failure, so this
193/// never panics in shipped builds.
194#[must_use]
195pub fn bundled_models_dev_catalog() -> ModelsDevCatalog {
196    ModelsDevCatalog::parse_json(BUNDLED_MODELS_DEV_JSON)
197        .expect("committed bundled Models.dev asset must be valid JSON")
198}
199
200/// Bundled-layer [`CatalogOffering`] rows from the offline snapshot (#4188).
201///
202/// Lowest-precedence catalog layer: every text-chat row from
203/// [`BUNDLED_MODELS_DEV_JSON`], tagged [`CatalogSource::Bundled`]. Live Models.dev
204/// rows override these on `(provider, wire_model_id)` when available.
205#[must_use]
206pub fn bundled_catalog_offerings() -> Vec<CatalogOffering> {
207    bundled_offerings_from_models_dev(&bundled_models_dev_catalog())
208}
209
210/// Hydrate bundled [`CatalogOffering`] rows from a parsed Models.dev catalog.
211///
212/// Only text-chat offerings are emitted (TTS/audio-only rows stay in the parsed
213/// catalog but are excluded from route candidates, matching
214/// [`ModelsDevCatalog::provider_offerings`]). Each row is tagged
215/// [`CatalogSource::Bundled`]. No canonical model is inferred from a prefix; the
216/// canonical link is set only from an explicit `base_model`.
217///
218/// Provider ids are kept verbatim from the Models.dev payload (the committed
219/// bundled asset already uses CodeWhale ids). Live refresh normalizes aliases
220/// via [`live_offerings_from_models_dev`].
221#[must_use]
222pub fn bundled_offerings_from_models_dev(catalog: &ModelsDevCatalog) -> Vec<CatalogOffering> {
223    offerings_from_models_dev(catalog, CatalogSource::Bundled, false)
224}
225
226/// Hydrate live [`CatalogOffering`] rows from a fetched Models.dev catalog (#4187).
227///
228/// Same text-chat filter as [`bundled_offerings_from_models_dev`], but each row is
229/// tagged [`CatalogSource::Live`] with the Models.dev URL fingerprint and fetch
230/// timestamp. Provider keys are normalized onto CodeWhale [`crate::ProviderKind`]
231/// ids when an alias match exists (`moonshotai` → `moonshot`, `togetherai` →
232/// `together`, `zhipuai` → `zai`, …); unknown Models.dev providers keep their
233/// upstream id so they stay discoverable without becoming executable routes.
234#[must_use]
235pub fn live_offerings_from_models_dev(
236    catalog: &ModelsDevCatalog,
237    base_url_fingerprint: &str,
238    fetched_at: u64,
239) -> Vec<CatalogOffering> {
240    offerings_from_models_dev(
241        catalog,
242        CatalogSource::Live {
243            base_url_fingerprint: base_url_fingerprint.to_string(),
244            fetched_at,
245        },
246        true,
247    )
248}
249
250fn offerings_from_models_dev(
251    catalog: &ModelsDevCatalog,
252    source: CatalogSource,
253    normalize_provider_ids: bool,
254) -> Vec<CatalogOffering> {
255    let mut out = Vec::new();
256    for (provider_key, provider) in &catalog.providers {
257        let raw_id = if provider.id.trim().is_empty() {
258            provider_key.trim()
259        } else {
260            provider.id.trim()
261        };
262        if raw_id.is_empty() {
263            continue;
264        }
265        let provider_id = if normalize_provider_ids {
266            // Normalize Models.dev provider ids onto CodeWhale kinds when known
267            // (#4186). Unknown upstream ids are kept verbatim for catalog browsing.
268            crate::ProviderKind::parse(raw_id)
269                .map(|kind| kind.as_str().to_string())
270                .unwrap_or_else(|| raw_id.to_string())
271        } else {
272            raw_id.to_string()
273        };
274        for model in provider.models.values() {
275            if !model.supports_text_chat() {
276                continue;
277            }
278            out.push(CatalogOffering {
279                provider: provider_id.clone(),
280                wire_model_id: model.id.clone(),
281                canonical_model: model.base_model.clone(),
282                endpoint_key: "chat".to_string(),
283                default_for_provider: model.default_for_provider,
284                family: model.family.clone(),
285                limit: model.limit.clone(),
286                cost: model.cost.clone(),
287                modalities: model.modalities.clone(),
288                attachment: model.attachment,
289                reasoning: model.reasoning,
290                tool_call: model.tool_call,
291                structured_output: model.structured_output,
292                reasoning_options: model.reasoning_options.clone(),
293                source: source.clone(),
294            });
295        }
296    }
297    out
298}
299
300/// A provider's live `/models` refresh result, scoped to a base-URL fingerprint.
301///
302/// Returned as a delta rather than mutating any global model state directly, per
303/// the #3385 architecture contract.
304#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
305pub struct ProviderCatalogDelta {
306    /// Provider this delta belongs to.
307    pub provider: String,
308    /// Fingerprint of the base URL the rows were fetched from.
309    pub base_url_fingerprint: String,
310    /// Unix seconds the rows were fetched at.
311    pub fetched_at: u64,
312    /// Live offering rows. Sources are normalized to `Live` on ingest.
313    pub offerings: Vec<CatalogOffering>,
314}
315
316/// Why a provider live catalog refresh did not produce usable rows.
317///
318/// Every variant must leave previously cached / bundled / configured rows
319/// available; a refresh failure is never fatal to model selection.
320#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
321#[serde(rename_all = "snake_case")]
322pub enum CatalogRefreshError {
323    /// 401 — auth missing or invalid.
324    Unauthorized,
325    /// 403 — auth present but not permitted.
326    Forbidden,
327    /// 404 — provider does not expose `/models` at this base URL.
328    NotFound,
329    /// 429 — rate limited.
330    RateLimited,
331    /// Response was not parseable as a model listing.
332    InvalidResponse,
333    /// Provider returned an empty model list.
334    EmptyList,
335    /// Transport / network failure.
336    Network,
337}
338
339/// Freshness / health of a provider's cached live catalog.
340#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
341#[serde(tag = "state", rename_all = "snake_case")]
342pub enum CatalogStatus {
343    /// Cached rows are within their TTL.
344    Fresh,
345    /// Cached rows exist but are past their TTL.
346    Stale { age_secs: u64 },
347    /// The last refresh failed; any rows present are from an earlier success.
348    Failed { reason: CatalogRefreshError },
349    /// No refresh has been attempted for this provider + base URL.
350    Unknown,
351}
352
353/// A secret-free cached provider catalog for one provider + base-URL fingerprint.
354#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
355pub struct CachedProviderCatalog {
356    /// Provider id.
357    pub provider: String,
358    /// Base-URL fingerprint the rows were fetched from.
359    pub base_url_fingerprint: String,
360    /// Unix seconds of the last successful fetch (unchanged on failure).
361    pub fetched_at: u64,
362    /// Time-to-live, in seconds, after which rows are considered stale.
363    pub ttl_secs: u64,
364    /// Cached live offering rows (possibly empty after a failure with no prior).
365    pub offerings: Vec<CatalogOffering>,
366    /// Last known status of this entry.
367    pub status: CatalogStatus,
368}
369
370impl CachedProviderCatalog {
371    /// Age in seconds relative to `now_unix`, saturating at zero for clock skew.
372    #[must_use]
373    pub fn age_secs(&self, now_unix: u64) -> u64 {
374        now_unix.saturating_sub(self.fetched_at)
375    }
376
377    /// Whether the cached rows are past their TTL at `now_unix`.
378    ///
379    /// A `ttl_secs` of zero means "always stale" (never serve as fresh).
380    #[must_use]
381    pub fn is_stale(&self, now_unix: u64) -> bool {
382        self.age_secs(now_unix) >= self.ttl_secs
383    }
384
385    /// Whether this entry may contribute live offerings at `now_unix`.
386    ///
387    /// An entry is fresh only when it is within its TTL **and** its last
388    /// recorded refresh succeeded. A `Failed` entry is never fresh even inside
389    /// its TTL window — its rows survive a failed refresh for explicit fallback
390    /// display via [`ProviderCatalogCache::get`], but they are not served as
391    /// current live data.
392    #[must_use]
393    pub fn is_fresh(&self, now_unix: u64) -> bool {
394        !self.is_stale(now_unix) && !matches!(self.status, CatalogStatus::Failed { .. })
395    }
396}
397
398/// A secret-free store of cached provider catalogs, keyed by provider + base-URL
399/// fingerprint.
400///
401/// Scoping rule (#3385): the SAME provider on DIFFERENT base URLs must not share
402/// rows, and DIFFERENT providers on the same base URL must not share rows.
403#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
404pub struct ProviderCatalogCache {
405    /// Entries keyed by [`ProviderCatalogCache::cache_key`].
406    #[serde(default)]
407    pub entries: BTreeMap<String, CachedProviderCatalog>,
408}
409
410impl ProviderCatalogCache {
411    /// Construct an empty cache.
412    #[must_use]
413    pub fn new() -> Self {
414        Self::default()
415    }
416
417    /// Compute the composite cache key for a provider + base-URL fingerprint.
418    #[must_use]
419    pub fn cache_key(provider: &str, base_url_fingerprint: &str) -> String {
420        // Unit separator avoids ambiguity between provider and fingerprint.
421        format!("{}\u{1f}{}", provider.trim(), base_url_fingerprint.trim())
422    }
423
424    /// Look up a cached entry by provider + base-URL fingerprint.
425    #[must_use]
426    pub fn get(
427        &self,
428        provider: &str,
429        base_url_fingerprint: &str,
430    ) -> Option<&CachedProviderCatalog> {
431        self.entries
432            .get(&Self::cache_key(provider, base_url_fingerprint))
433    }
434
435    /// Record a successful refresh, replacing any prior entry for this scope.
436    ///
437    /// Offering sources are normalized to [`CatalogSource::Live`] with the
438    /// delta's fingerprint and `fetched_at`, so cached rows always carry honest
439    /// provenance regardless of how the delta was assembled.
440    pub fn record_success(&mut self, delta: ProviderCatalogDelta, ttl_secs: u64) {
441        let ProviderCatalogDelta {
442            provider,
443            base_url_fingerprint,
444            fetched_at,
445            offerings,
446        } = delta;
447        let offerings = offerings
448            .into_iter()
449            .map(|mut row| {
450                row.source = CatalogSource::Live {
451                    base_url_fingerprint: base_url_fingerprint.clone(),
452                    fetched_at,
453                };
454                row
455            })
456            .collect();
457        let key = Self::cache_key(&provider, &base_url_fingerprint);
458        self.entries.insert(
459            key,
460            CachedProviderCatalog {
461                provider,
462                base_url_fingerprint,
463                fetched_at,
464                ttl_secs,
465                offerings,
466                status: CatalogStatus::Fresh,
467            },
468        );
469    }
470
471    /// Record a refresh failure.
472    ///
473    /// Previously cached rows for this scope are preserved (so the UI can still
474    /// offer them with a visible "stale/failed" status); only the status is
475    /// updated. When no prior entry exists, an empty `Failed` entry is created so
476    /// the failure is observable.
477    pub fn record_failure(
478        &mut self,
479        provider: &str,
480        base_url_fingerprint: &str,
481        reason: CatalogRefreshError,
482    ) {
483        let key = Self::cache_key(provider, base_url_fingerprint);
484        match self.entries.get_mut(&key) {
485            Some(entry) => entry.status = CatalogStatus::Failed { reason },
486            None => {
487                self.entries.insert(
488                    key,
489                    CachedProviderCatalog {
490                        provider: provider.trim().to_string(),
491                        base_url_fingerprint: base_url_fingerprint.trim().to_string(),
492                        fetched_at: 0,
493                        ttl_secs: 0,
494                        offerings: Vec::new(),
495                        status: CatalogStatus::Failed { reason },
496                    },
497                );
498            }
499        }
500    }
501
502    /// The resolved status of an entry at `now_unix`.
503    ///
504    /// A `Fresh`-recorded entry that has since aged past its TTL reports
505    /// `Stale`; `Failed`/`Unknown` are returned as stored.
506    #[must_use]
507    pub fn status(
508        &self,
509        provider: &str,
510        base_url_fingerprint: &str,
511        now_unix: u64,
512    ) -> CatalogStatus {
513        match self.get(provider, base_url_fingerprint) {
514            None => CatalogStatus::Unknown,
515            Some(entry) => match &entry.status {
516                CatalogStatus::Failed { reason } => CatalogStatus::Failed { reason: *reason },
517                CatalogStatus::Unknown => CatalogStatus::Unknown,
518                CatalogStatus::Fresh | CatalogStatus::Stale { .. } => {
519                    if entry.is_stale(now_unix) {
520                        CatalogStatus::Stale {
521                            age_secs: entry.age_secs(now_unix),
522                        }
523                    } else {
524                        CatalogStatus::Fresh
525                    }
526                }
527            },
528        }
529    }
530
531    /// Fresh (within-TTL) live offerings for one provider + base URL at
532    /// `now_unix`. Stale or failed entries contribute nothing here; callers fall
533    /// back to bundled/configured rows and surface the status separately.
534    #[must_use]
535    pub fn fresh_offerings(
536        &self,
537        provider: &str,
538        base_url_fingerprint: &str,
539        now_unix: u64,
540    ) -> Vec<CatalogOffering> {
541        match self.get(provider, base_url_fingerprint) {
542            Some(entry) if entry.is_fresh(now_unix) => entry.offerings.clone(),
543            _ => Vec::new(),
544        }
545    }
546
547    /// All fresh live offerings across every cached provider + base URL.
548    #[must_use]
549    pub fn all_fresh_offerings(&self, now_unix: u64) -> Vec<CatalogOffering> {
550        self.entries
551            .values()
552            .filter(|entry| entry.is_fresh(now_unix))
553            .flat_map(|entry| entry.offerings.clone())
554            .collect()
555    }
556
557    /// Live offerings that pickers may still show: fresh rows plus stale / prior
558    /// rows that survived a failed refresh (#4139).
559    ///
560    /// Unlike [`Self::all_fresh_offerings`], this keeps past-TTL and
561    /// `Failed`-status entries as long as they still hold offering rows. Empty
562    /// entries contribute nothing; callers fall back to the bundled snapshot.
563    /// `now_unix` is accepted for API symmetry with the fresh helper (age chips
564    /// live above this layer).
565    #[must_use]
566    pub fn all_visible_offerings(&self, _now_unix: u64) -> Vec<CatalogOffering> {
567        self.entries
568            .values()
569            .filter(|entry| !entry.offerings.is_empty())
570            .flat_map(|entry| entry.offerings.clone())
571            .collect()
572    }
573}
574
575/// A compiled, layer-merged catalog snapshot.
576#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
577pub struct CatalogSnapshot {
578    /// Merged offerings, de-duplicated by (provider, wire id), in stable order.
579    pub offerings: Vec<CatalogOffering>,
580}
581
582impl CatalogSnapshot {
583    /// Project routing offerings for `RouteResolver::from_offerings`.
584    #[must_use]
585    pub fn to_offerings(&self) -> Vec<ProviderModelOffering> {
586        self.offerings
587            .iter()
588            .map(CatalogOffering::to_offering)
589            .collect()
590    }
591
592    /// All offerings for one provider id.
593    #[must_use]
594    pub fn offerings_for_provider(&self, provider: &str) -> Vec<&CatalogOffering> {
595        self.offerings
596            .iter()
597            .filter(|row| row.provider == provider)
598            .collect()
599    }
600}
601
602/// Builds a [`CatalogSnapshot`] by merging layers in precedence order:
603/// bundled < live < user overrides. Later layers override earlier rows that
604/// share a (provider, wire id) identity.
605#[derive(Debug, Clone, Default)]
606pub struct CatalogCompiler {
607    bundled: Vec<CatalogOffering>,
608    live: Vec<CatalogOffering>,
609    overrides: Vec<CatalogOffering>,
610}
611
612impl CatalogCompiler {
613    /// Start an empty compiler.
614    #[must_use]
615    pub fn new() -> Self {
616        Self::default()
617    }
618
619    /// Add bundled (lowest-precedence) rows.
620    #[must_use]
621    pub fn with_bundled(mut self, rows: Vec<CatalogOffering>) -> Self {
622        self.bundled.extend(rows);
623        self
624    }
625
626    /// Seed bundled rows from a parsed Models.dev catalog.
627    #[must_use]
628    pub fn with_models_dev(mut self, catalog: &ModelsDevCatalog) -> Self {
629        self.bundled
630            .extend(bundled_offerings_from_models_dev(catalog));
631        self
632    }
633
634    /// Add live (middle-precedence) rows.
635    #[must_use]
636    pub fn with_live(mut self, rows: Vec<CatalogOffering>) -> Self {
637        self.live.extend(rows);
638        self
639    }
640
641    /// Add user/custom override (highest-precedence) rows.
642    #[must_use]
643    pub fn with_overrides(mut self, rows: Vec<CatalogOffering>) -> Self {
644        self.overrides.extend(rows);
645        self
646    }
647
648    /// Merge all layers into a deterministic snapshot.
649    #[must_use]
650    pub fn compile(self) -> CatalogSnapshot {
651        let mut merged: BTreeMap<(String, String), CatalogOffering> = BTreeMap::new();
652        for row in self
653            .bundled
654            .into_iter()
655            .chain(self.live)
656            .chain(self.overrides)
657        {
658            merged.insert(row.merge_key(), row);
659        }
660        CatalogSnapshot {
661            offerings: merged.into_values().collect(),
662        }
663    }
664}
665
666/// Normalize a base URL and fingerprint it for cache scoping.
667///
668/// Normalization folds case in the scheme/host, trims trailing slashes, and
669/// drops a default-port suffix, so cosmetically different spellings of the same
670/// endpoint share a cache scope while genuinely different endpoints do not. The
671/// fingerprint is a dependency-free FNV-1a hex digest; it is deterministic
672/// within and across runs but is not a cryptographic hash (it identifies a
673/// cache bucket, nothing security-sensitive).
674#[must_use]
675pub fn base_url_fingerprint(base_url: &str) -> String {
676    let normalized = normalize_base_url(base_url);
677    fnv1a_hex(normalized.as_bytes())
678}
679
680fn normalize_base_url(base_url: &str) -> String {
681    let trimmed = base_url.trim().trim_end_matches('/');
682    // Lowercase only the scheme://host authority; leave the path case-sensitive.
683    if let Some(idx) = trimmed.find("://") {
684        let (scheme, rest) = trimmed.split_at(idx);
685        let scheme = scheme.to_ascii_lowercase();
686        let rest = &rest[3..];
687        let (authority, path) = match rest.find('/') {
688            Some(p) => (&rest[..p], &rest[p..]),
689            None => (rest, ""),
690        };
691        let authority = authority.to_ascii_lowercase();
692        // Strip only the scheme's own default port, so a non-default pairing
693        // such as `http://host:443` stays distinct from `http://host`.
694        let default_port = match scheme.as_str() {
695            "https" => Some(":443"),
696            "http" => Some(":80"),
697            _ => None,
698        };
699        let authority = default_port
700            .and_then(|port| authority.strip_suffix(port))
701            .unwrap_or(&authority);
702        format!("{scheme}://{authority}{path}")
703    } else {
704        trimmed.to_ascii_lowercase()
705    }
706}
707
708fn fnv1a_hex(bytes: &[u8]) -> String {
709    const OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
710    const PRIME: u64 = 0x0000_0100_0000_01b3;
711    let mut hash = OFFSET;
712    for &b in bytes {
713        hash ^= u64::from(b);
714        hash = hash.wrapping_mul(PRIME);
715    }
716    format!("{hash:016x}")
717}
718
719/// Current unix time in seconds, for callers assembling deltas / cache entries.
720///
721/// Pure cache logic takes `now_unix` explicitly so it stays deterministic in
722/// tests; this helper is the one place that reads the wall clock.
723#[must_use]
724pub fn now_unix() -> u64 {
725    SystemTime::now()
726        .duration_since(UNIX_EPOCH)
727        .map(|d| d.as_secs())
728        .unwrap_or(0)
729}
730
731#[cfg(test)]
732mod tests;