| 1 | //! The sole producer of [`ReadyRouteCandidate`] (#3384). |
| 2 | //! |
| 3 | //! [`RouteResolver::resolve`] is the ONLY caller of |
| 4 | //! `ReadyRouteCandidate::new`. It resolves a [`RouteRequest`] into an |
| 5 | //! executable route using: |
| 6 | //! |
| 7 | //! 1. provider from `explicit_provider` ONLY (no base-URL / prefix sniffing); |
| 8 | //! when absent, the workspace default provider scope is used. The provider |
| 9 | //! is NEVER inferred from a model prefix. |
| 10 | //! 2. the model selector, interpreted STRICTLY within that provider's scope |
| 11 | //! against resolver-provided offerings plus the provider default. The default |
| 12 | //! resolver uses [`bundled_offerings`], while tests or snapshot loaders can |
| 13 | //! inject Models.dev-derived rows. Prefixed selectors are preserved verbatim |
| 14 | //! as the [`WireModelId`]. |
| 15 | //! 3. `auto` => the [`LogicalModelRef::is_auto`] sentinel, never a literal |
| 16 | //! model. |
| 17 | //! |
| 18 | //! There is deliberately no prompt-text / freeform field on [`RouteRequest`], |
| 19 | //! which structurally bars prompt-content routing. |
| 20 | |
| 21 | use std::sync::OnceLock; |
| 22 | |
| 23 | use super::candidate::{ |
| 24 | LimitField, PricingSku, ReadyRouteCandidate, ResolvedAuthSource, ResolvedEndpoint, |
| 25 | SourcedLimitOverride, ValidationReport, |
| 26 | }; |
| 27 | use super::capabilities::{ |
| 28 | RouteCapabilities, documented_deepseek_files_api_for_route, |
| 29 | documented_deepseek_image_input_for_route, documented_deepseek_web_search_for_route, |
| 30 | documented_moonshot_web_search_for_route, documented_zai_web_search_for_route, |
| 31 | }; |
| 32 | use super::descriptor::ProviderDescriptor; |
| 33 | use super::errors::RouteError; |
| 34 | use super::ids::{AUTO_SENTINEL, LogicalModelRef, ModelId, ProviderId, WireModelId}; |
| 35 | use super::offering::{ProviderModelOffering, RouteLimits, bundled_offerings}; |
| 36 | use super::policy::wildcard_match; |
| 37 | use crate::catalog::{CatalogOffering, seed_catalog_offerings}; |
| 38 | use crate::cloud_facts::CompiledNamingRules; |
| 39 | use crate::descriptors::{ModelIdsPolicy, model_rules_for, normalize_model_lookup_key}; |
| 40 | use crate::provider::{WireFormat, WirePolicy}; |
| 41 | use crate::{ProviderKind, provider_preserves_custom_base_url_model}; |
| 42 | |
| 43 | #[derive(Debug, Clone, PartialEq)] |
| 44 | pub struct ResolvedModel { |
| 45 | pub logical: String, |
| 46 | pub wire_id: String, |
| 47 | pub offering: Option<ProviderModelOffering>, |
| 48 | pub model: Option<ModelId>, |
| 49 | pub alias_matched: bool, |
| 50 | pub is_auto: bool, |
| 51 | } |
| 52 | |
| 53 | static DEFAULT_OFFERINGS: OnceLock<Vec<ProviderModelOffering>> = OnceLock::new(); |
| 54 | |
| 55 | fn default_offerings_slice() -> &'static [ProviderModelOffering] { |
| 56 | DEFAULT_OFFERINGS.get_or_init(build_default_offerings) |
| 57 | } |
| 58 | |
| 59 | pub(crate) fn seed_route_offerings() -> &'static [ProviderModelOffering] { |
| 60 | default_offerings_slice() |
| 61 | } |
| 62 | |
| 63 | #[must_use] |
| 64 | pub fn bundled_offering_wire_id(provider: ProviderKind, id: &str) -> Option<&'static str> { |
| 65 | find_offering( |
| 66 | default_offerings_slice(), |
| 67 | &ProviderId::from(provider.as_str()), |
| 68 | id, |
| 69 | true, |
| 70 | false, |
| 71 | ) |
| 72 | .map(|offering| offering.wire_model_id.as_str()) |
| 73 | } |
| 74 | |
| 75 | pub fn resolve_model( |
| 76 | provider: ProviderKind, |
| 77 | raw: &str, |
| 78 | base_url: Option<&str>, |
| 79 | ) -> Result<ResolvedModel, RouteError> { |
| 80 | let pulled = crate::cloud_facts::overlay::pulled_registry(); |
| 81 | let offerings: &[ProviderModelOffering] = match pulled.as_deref() { |
| 82 | Some(reg) => reg.compiled.route_offerings.as_slice(), |
| 83 | None => default_offerings_slice(), |
| 84 | }; |
| 85 | let naming = pulled |
| 86 | .as_deref() |
| 87 | .and_then(|reg| reg.compiled.naming.get(provider.as_str())); |
| 88 | resolve_model_against_offerings(provider, raw, base_url, offerings, &[], naming) |
| 89 | } |
| 90 | |
| 91 | #[must_use] |
| 92 | pub fn aliases_for_wire_model(provider: ProviderKind, wire_id: &str) -> Vec<String> { |
| 93 | model_rules_for(provider) |
| 94 | .aliases |
| 95 | .iter() |
| 96 | .filter_map(|(alias, _)| { |
| 97 | let resolved = resolve_model(provider, alias, None).ok()?; |
| 98 | (resolved.wire_id == wire_id && *alias != wire_id).then(|| (*alias).to_string()) |
| 99 | }) |
| 100 | .collect() |
| 101 | } |
| 102 | |
| 103 | fn find_offering<'a>( |
| 104 | offerings: &'a [ProviderModelOffering], |
| 105 | provider_id: &ProviderId, |
| 106 | candidate: &str, |
| 107 | allow_casefold: bool, |
| 108 | allow_aggregator_tail: bool, |
| 109 | ) -> Option<&'a ProviderModelOffering> { |
| 110 | let mut casefold_match: Option<&'a ProviderModelOffering> = None; |
| 111 | let mut casefold_ambiguous = false; |
| 112 | let mut suffix_match: Option<&'a ProviderModelOffering> = None; |
| 113 | let mut suffix_ambiguous = false; |
| 114 | |
| 115 | for offering in offerings { |
| 116 | if offering.provider != *provider_id { |
| 117 | continue; |
| 118 | } |
| 119 | let exact_wire = offering.wire_model_id.as_str() == candidate; |
| 120 | let exact_canonical = offering |
| 121 | .canonical_model |
| 122 | .as_ref() |
| 123 | .is_some_and(|m| m.as_str() == candidate); |
| 124 | if exact_wire || exact_canonical { |
| 125 | return Some(offering); |
| 126 | } |
| 127 | if allow_casefold |
| 128 | && (offering |
| 129 | .wire_model_id |
| 130 | .as_str() |
| 131 | .eq_ignore_ascii_case(candidate) |
| 132 | || offering |
| 133 | .canonical_model |
| 134 | .as_ref() |
| 135 | .is_some_and(|m| m.as_str().eq_ignore_ascii_case(candidate))) |
| 136 | { |
| 137 | match casefold_match { |
| 138 | None => casefold_match = Some(offering), |
| 139 | Some(first) if first.wire_model_id != offering.wire_model_id => { |
| 140 | casefold_ambiguous = true; |
| 141 | } |
| 142 | Some(_) => {} |
| 143 | } |
| 144 | } |
| 145 | if allow_aggregator_tail && !candidate.contains('/') { |
| 146 | let wire_tail = offering |
| 147 | .wire_model_id |
| 148 | .as_str() |
| 149 | .rsplit('/') |
| 150 | .next() |
| 151 | .unwrap_or_default(); |
| 152 | let canonical_tail = offering |
| 153 | .canonical_model |
| 154 | .as_ref() |
| 155 | .map(|m| m.as_str().rsplit('/').next().unwrap_or_default()); |
| 156 | if wire_tail.eq_ignore_ascii_case(candidate) |
| 157 | || canonical_tail.is_some_and(|tail| tail.eq_ignore_ascii_case(candidate)) |
| 158 | { |
| 159 | match suffix_match { |
| 160 | None => suffix_match = Some(offering), |
| 161 | Some(first) if first.wire_model_id != offering.wire_model_id => { |
| 162 | suffix_ambiguous = true; |
| 163 | } |
| 164 | Some(_) => {} |
| 165 | } |
| 166 | } |
| 167 | } |
| 168 | } |
| 169 | |
| 170 | if !casefold_ambiguous && let Some(offering) = casefold_match { |
| 171 | return Some(offering); |
| 172 | } |
| 173 | if !suffix_ambiguous && let Some(offering) = suffix_match { |
| 174 | return Some(offering); |
| 175 | } |
| 176 | None |
| 177 | } |
| 178 | |
| 179 | fn resolve_model_against_offerings( |
| 180 | provider: ProviderKind, |
| 181 | raw: &str, |
| 182 | base_url: Option<&str>, |
| 183 | offerings: &[ProviderModelOffering], |
| 184 | configured_offerings: &[(String, ProviderModelOffering)], |
| 185 | pulled_naming: Option<&CompiledNamingRules>, |
| 186 | ) -> Result<ResolvedModel, RouteError> { |
| 187 | let trimmed = raw.trim(); |
| 188 | if trimmed.is_empty() || trimmed.chars().any(char::is_control) { |
| 189 | return Err(RouteError::EmptyModel); |
| 190 | } |
| 191 | if trimmed.eq_ignore_ascii_case(AUTO_SENTINEL) { |
| 192 | return Ok(ResolvedModel { |
| 193 | logical: AUTO_SENTINEL.to_string(), |
| 194 | wire_id: AUTO_SENTINEL.to_string(), |
| 195 | offering: None, |
| 196 | model: None, |
| 197 | alias_matched: false, |
| 198 | is_auto: true, |
| 199 | }); |
| 200 | } |
| 201 | |
| 202 | let rules = model_rules_for(provider); |
| 203 | let provider_id = ProviderId::from(provider.as_str()); |
| 204 | |
| 205 | if rules.ids != ModelIdsPolicy::Roster { |
| 206 | if let Some((_, offering)) = configured_offerings.iter().find(|(_, offering)| { |
| 207 | offering.provider == provider_id && offering.wire_model_id.as_str() == trimmed |
| 208 | }) { |
| 209 | return Ok(ResolvedModel { |
| 210 | logical: offering |
| 211 | .canonical_model |
| 212 | .as_ref() |
| 213 | .map_or_else(|| trimmed.to_string(), |m| m.as_str().to_string()), |
| 214 | wire_id: offering.wire_model_id.as_str().to_string(), |
| 215 | model: offering.canonical_model.clone(), |
| 216 | offering: Some(offering.clone()), |
| 217 | alias_matched: false, |
| 218 | is_auto: false, |
| 219 | }); |
| 220 | } |
| 221 | if base_url.is_some_and(|url| provider_preserves_custom_base_url_model(provider, url)) { |
| 222 | let offering = find_offering(offerings, &provider_id, trimmed, false, false); |
| 223 | return Ok(ResolvedModel { |
| 224 | logical: trimmed.to_string(), |
| 225 | wire_id: trimmed.to_string(), |
| 226 | model: offering.as_ref().and_then(|o| o.canonical_model.clone()), |
| 227 | offering: offering.cloned(), |
| 228 | alias_matched: false, |
| 229 | is_auto: false, |
| 230 | }); |
| 231 | } |
| 232 | } |
| 233 | |
| 234 | let mut stripped = trimmed; |
| 235 | for prefix in pulled_naming |
| 236 | .into_iter() |
| 237 | .flat_map(|n| n.strip_prefixes.iter().map(String::as_str)) |
| 238 | .chain(rules.strip_prefixes.iter().copied()) |
| 239 | { |
| 240 | if stripped.len() >= prefix.len() |
| 241 | && stripped.as_bytes()[..prefix.len()].eq_ignore_ascii_case(prefix.as_bytes()) |
| 242 | { |
| 243 | stripped = &stripped[prefix.len()..]; |
| 244 | break; |
| 245 | } |
| 246 | } |
| 247 | let stripped = stripped.trim(); |
| 248 | if stripped.is_empty() { |
| 249 | return Err(RouteError::EmptyModel); |
| 250 | } |
| 251 | if rules.ids == ModelIdsPolicy::Verbatim { |
| 252 | let offering = find_offering(offerings, &provider_id, stripped, false, false); |
| 253 | return Ok(ResolvedModel { |
| 254 | logical: stripped.to_string(), |
| 255 | wire_id: stripped.to_string(), |
| 256 | model: offering.and_then(|o| o.canonical_model.clone()), |
| 257 | offering: offering.cloned(), |
| 258 | alias_matched: false, |
| 259 | is_auto: false, |
| 260 | }); |
| 261 | } |
| 262 | |
| 263 | let key = normalize_model_lookup_key(stripped); |
| 264 | let (alias_matched, candidate) = |
| 265 | if let Some(target) = pulled_naming.and_then(|n| n.aliases.get(&key).map(String::as_str)) { |
| 266 | (true, target) |
| 267 | } else if let Some((_, target)) = rules.aliases.iter().find(|(k, _)| *k == key) { |
| 268 | (true, *target) |
| 269 | } else { |
| 270 | (false, stripped) |
| 271 | }; |
| 272 | |
| 273 | if let Some((_, offering)) = configured_offerings.iter().find(|(_, offering)| { |
| 274 | offering.provider == provider_id && offering.wire_model_id.as_str() == candidate |
| 275 | }) { |
| 276 | return Ok(ResolvedModel { |
| 277 | logical: candidate.to_string(), |
| 278 | wire_id: offering.wire_model_id.as_str().to_string(), |
| 279 | model: offering.canonical_model.clone(), |
| 280 | offering: Some(offering.clone()), |
| 281 | alias_matched, |
| 282 | is_auto: false, |
| 283 | }); |
| 284 | } |
| 285 | |
| 286 | let allow_tail = rules.ids == ModelIdsPolicy::Catalog && provider != ProviderKind::Zai; |
| 287 | let matched_offering = find_offering(offerings, &provider_id, candidate, true, allow_tail); |
| 288 | |
| 289 | let slug_key = normalize_model_lookup_key(candidate); |
| 290 | let wire_slug = pulled_naming |
| 291 | .and_then(|n| n.wire_slugs.get(&slug_key).map(String::as_str)) |
| 292 | .or_else(|| { |
| 293 | rules |
| 294 | .wire_slugs |
| 295 | .iter() |
| 296 | .find(|(k, _)| *k == slug_key) |
| 297 | .map(|(_, v)| *v) |
| 298 | }); |
| 299 | |
| 300 | if let Some(slug) = wire_slug { |
| 301 | let slug_offering = find_offering(offerings, &provider_id, slug, true, false); |
| 302 | let logical = candidate.to_string(); |
| 303 | return Ok(ResolvedModel { |
| 304 | logical, |
| 305 | wire_id: slug.to_string(), |
| 306 | model: slug_offering |
| 307 | .as_ref() |
| 308 | .and_then(|o| o.canonical_model.clone()), |
| 309 | offering: slug_offering.cloned(), |
| 310 | alias_matched, |
| 311 | is_auto: false, |
| 312 | }); |
| 313 | } |
| 314 | |
| 315 | match rules.ids { |
| 316 | ModelIdsPolicy::Roster if matched_offering.is_none() => { |
| 317 | return Err(RouteError::UnsupportedModelProtocol { |
| 318 | provider: provider_id, |
| 319 | model: candidate.to_string(), |
| 320 | endpoint_key: "unproven".to_string(), |
| 321 | }); |
| 322 | } |
| 323 | ModelIdsPolicy::Strict if !alias_matched && matched_offering.is_none() => { |
| 324 | let lower = candidate.to_ascii_lowercase(); |
| 325 | let accepted = rules.accept.iter().any(|pat| wildcard_match(pat, &lower)) |
| 326 | || pulled_naming |
| 327 | .is_some_and(|n| n.accept.iter().any(|pat| wildcard_match(pat, &lower))); |
| 328 | if !accepted { |
| 329 | return Err(RouteError::ForeignModelForDirectProvider { |
| 330 | provider: provider_id, |
| 331 | model: candidate.to_string(), |
| 332 | }); |
| 333 | } |
| 334 | } |
| 335 | _ => {} |
| 336 | } |
| 337 | |
| 338 | let (logical, wire_id, model) = if let Some(offering) = matched_offering { |
| 339 | let wire = offering.wire_model_id.as_str(); |
| 340 | let authoritative = if alias_matched && wire.eq_ignore_ascii_case(candidate) { |
| 341 | candidate.to_string() |
| 342 | } else { |
| 343 | wire.to_string() |
| 344 | }; |
| 345 | let logical = if authoritative.eq_ignore_ascii_case(candidate) { |
| 346 | authoritative.clone() |
| 347 | } else { |
| 348 | candidate.to_string() |
| 349 | }; |
| 350 | (logical, authoritative, offering.canonical_model.clone()) |
| 351 | } else { |
| 352 | (candidate.to_string(), candidate.to_string(), None) |
| 353 | }; |
| 354 | |
| 355 | Ok(ResolvedModel { |
| 356 | logical, |
| 357 | wire_id, |
| 358 | offering: matched_offering.cloned(), |
| 359 | model, |
| 360 | alias_matched, |
| 361 | is_auto: false, |
| 362 | }) |
| 363 | } |
| 364 | |
| 365 | /// A request to resolve into an executable route. |
| 366 | /// |
| 367 | /// Note the absence of any prompt-text/freeform field: the resolver cannot see |
| 368 | /// prompt content, so it cannot silently route on it. |
| 369 | #[derive(Debug, Clone, Default)] |
| 370 | pub struct RouteRequest { |
| 371 | /// Explicit provider choice. The ONLY source of provider identity. |
| 372 | pub explicit_provider: Option<ProviderKind>, |
| 373 | /// The model the caller selected (may be `auto` or prefixed). |
| 374 | pub model_selector: Option<LogicalModelRef>, |
| 375 | /// A previously-saved provider wire model id, used as scope fallback. |
| 376 | pub saved_provider_model: Option<WireModelId>, |
| 377 | /// An explicit base URL override for the endpoint. |
| 378 | pub base_url_override: Option<String>, |
| 379 | /// Sourced limit overrides, applied in order BEFORE the candidate is |
| 380 | /// constructed and recorded on it as provenance. This is the ONLY channel |
| 381 | /// for adjusting a route's effective limits: the candidate itself is |
| 382 | /// immutable once minted. |
| 383 | pub limit_overrides: Vec<SourcedLimitOverride>, |
| 384 | /// Wire override for a custom provider table, honored ONLY for |
| 385 | /// `ProviderKind::Custom` (built-ins keep their descriptor policy). The |
| 386 | /// tui route layer populates it from the resolved identity's |
| 387 | /// `[providers.<name>] wire` dialect so a table saying |
| 388 | /// `wire = "responses"` mints a wire-true candidate instead of Custom's |
| 389 | /// backward-compatible static Chat policy. |
| 390 | pub wire_override: Option<WireFormat>, |
| 391 | /// Explicit Responses profile from a custom provider table. Built-in |
| 392 | /// routes leave this empty and take the binding selected after the |
| 393 | /// protocol is known. `None` on a Responses route uses the default profile. |
| 394 | pub responses_profile_override: Option<String>, |
| 395 | } |
| 396 | |
| 397 | /// Resolves [`RouteRequest`]s into [`ReadyRouteCandidate`]s. |
| 398 | #[derive(Debug, Clone)] |
| 399 | pub struct RouteResolver { |
| 400 | offerings: Vec<ProviderModelOffering>, |
| 401 | configured_offerings: Vec<(String, ProviderModelOffering)>, |
| 402 | follow_registry_overlay: bool, |
| 403 | go_catalog: Option<std::sync::Arc<GoCatalogRoutes>>, |
| 404 | } |
| 405 | |
| 406 | /// Offering-owned facts selected within one provider scope before the final |
| 407 | /// executable route candidate is minted. |
| 408 | struct ResolvedOffering { |
| 409 | wire_model_id: WireModelId, |
| 410 | canonical_model: Option<ModelId>, |
| 411 | endpoint_key: String, |
| 412 | limits: RouteLimits, |
| 413 | capabilities: RouteCapabilities, |
| 414 | pricing: PricingSku, |
| 415 | } |
| 416 | |
| 417 | impl ResolvedOffering { |
| 418 | fn unknown(wire_model_id: WireModelId) -> Self { |
| 419 | Self { |
| 420 | wire_model_id, |
| 421 | canonical_model: None, |
| 422 | endpoint_key: "chat".to_string(), |
| 423 | limits: RouteLimits::default(), |
| 424 | capabilities: RouteCapabilities::default(), |
| 425 | pricing: PricingSku::UnknownOrStale, |
| 426 | } |
| 427 | } |
| 428 | |
| 429 | fn from_offering(offering: &ProviderModelOffering) -> Self { |
| 430 | Self { |
| 431 | wire_model_id: offering.wire_model_id.clone(), |
| 432 | canonical_model: offering.canonical_model.clone(), |
| 433 | endpoint_key: offering.endpoint_key.clone(), |
| 434 | limits: offering.limits, |
| 435 | capabilities: offering.capabilities, |
| 436 | pricing: offering.pricing.clone(), |
| 437 | } |
| 438 | } |
| 439 | } |
| 440 | |
| 441 | #[derive(Debug, Clone)] |
| 442 | struct GoCatalogRoutes { |
| 443 | connection: super::CatalogConnection, |
| 444 | models: std::collections::BTreeMap<String, (String, String)>, |
| 445 | } |
| 446 | |
| 447 | impl Default for RouteResolver { |
| 448 | fn default() -> Self { |
| 449 | Self::new() |
| 450 | } |
| 451 | } |
| 452 | |
| 453 | impl RouteResolver { |
| 454 | /// Construct a resolver with CodeWhale's bundled offline offerings. |
| 455 | /// |
| 456 | /// The default offerings are the committed Models.dev-shaped catalog asset |
| 457 | /// (`crate::catalog::bundled_catalog_offerings`, real context windows and |
| 458 | /// honest per-row `cost`) merged with the reviewed transport projection |
| 459 | /// ([`bundled_offerings`]). The reviewed projection is given precedence on a |
| 460 | /// `(provider, wire id)` collision: it encodes the curated canonical-model |
| 461 | /// joins the route invariants depend on (e.g. a DeepSeek-native row and the |
| 462 | /// aggregator rows that map a prefixed wire id back to `deepseek-v4-pro`), |
| 463 | /// which generated Models.dev JSON does not prove. Asset-only rows (GLM, |
| 464 | /// Kimi, MiniMax, Qwen, …) add the real provider/model facts the picker and |
| 465 | /// candidates were previously missing. |
| 466 | #[must_use] |
| 467 | pub fn new() -> Self { |
| 468 | Self { |
| 469 | offerings: default_offerings(), |
| 470 | configured_offerings: Vec::new(), |
| 471 | follow_registry_overlay: true, |
| 472 | go_catalog: None, |
| 473 | } |
| 474 | } |
| 475 | |
| 476 | /// The process-wide resolver built from the committed bundled asset. |
| 477 | /// |
| 478 | /// [`Self::new`] re-projects the entire bundled Models.dev asset — every |
| 479 | /// text-chat row, the corrections pass, and the de-duplication maps — on |
| 480 | /// every call. Callers that only need to resolve against that bundled |
| 481 | /// layer should share this one instead: the asset is a committed constant, |
| 482 | /// so the projection is identical for the life of the process, and a |
| 483 | /// route-validity check that runs once per model row otherwise pays a full |
| 484 | /// catalog rebuild per row. |
| 485 | /// |
| 486 | /// Returns a shared reference, so the caller cannot mutate it. Use |
| 487 | /// [`Self::new`] or [`Self::with_configured_models`] when the resolver |
| 488 | /// needs route-specific configured offerings added. |
| 489 | #[must_use] |
| 490 | pub fn bundled() -> &'static Self { |
| 491 | static BUNDLED: std::sync::OnceLock<RouteResolver> = std::sync::OnceLock::new(); |
| 492 | BUNDLED.get_or_init(Self::new) |
| 493 | } |
| 494 | |
| 495 | /// Construct a resolver from a provider-scoped offering catalog. |
| 496 | /// |
| 497 | /// This is the bridge for Models.dev snapshots: callers parse a catalog, |
| 498 | /// emit provider offerings, then hand those rows to the resolver without |
| 499 | /// changing route-resolution semantics. |
| 500 | #[must_use] |
| 501 | pub fn from_offerings(offerings: Vec<ProviderModelOffering>) -> Self { |
| 502 | Self { |
| 503 | offerings, |
| 504 | configured_offerings: Vec::new(), |
| 505 | follow_registry_overlay: false, |
| 506 | go_catalog: None, |
| 507 | } |
| 508 | } |
| 509 | |
| 510 | pub fn with_go_catalog_routes( |
| 511 | mut self, |
| 512 | identity: &str, |
| 513 | binding: String, |
| 514 | base_url: &str, |
| 515 | models: std::collections::BTreeMap<String, (String, String)>, |
| 516 | ) -> Self { |
| 517 | self.go_catalog = Some(std::sync::Arc::new(GoCatalogRoutes { |
| 518 | connection: super::CatalogConnection { |
| 519 | binding, |
| 520 | identity: identity.to_owned(), |
| 521 | base_url: base_url.to_owned(), |
| 522 | }, |
| 523 | models, |
| 524 | })); |
| 525 | self |
| 526 | } |
| 527 | |
| 528 | /// Add validated operator declarations for this exact route. This does |
| 529 | /// not grant provider-catalog authority or establish model availability. |
| 530 | pub fn with_configured_models( |
| 531 | mut self, |
| 532 | models: &[crate::catalog::configured::ConfiguredModel], |
| 533 | identity: &str, |
| 534 | provider: ProviderKind, |
| 535 | base_url: &str, |
| 536 | ) -> Self { |
| 537 | if crate::catalog::configured::validate_configured_models(models).is_err() { |
| 538 | return self; |
| 539 | } |
| 540 | let pulled = self |
| 541 | .follow_registry_overlay |
| 542 | .then(crate::cloud_facts::overlay::pulled_registry) |
| 543 | .flatten(); |
| 544 | let current_offerings = pulled.as_deref().map_or(self.offerings.as_slice(), |reg| { |
| 545 | reg.compiled.route_offerings.as_slice() |
| 546 | }); |
| 547 | for model in models |
| 548 | .iter() |
| 549 | .filter(|model| model.matches_route(identity, base_url)) |
| 550 | { |
| 551 | let mut offering = model.to_catalog_offering().to_offering(); |
| 552 | offering.provider = ProviderId::from(provider.as_str()); |
| 553 | // Preserve an adapter's established protocol for an existing ID. |
| 554 | // The label/config declaration cannot choose a new wire dialect. |
| 555 | if let Some(existing) = current_offerings.iter().find(|row| { |
| 556 | row.provider == offering.provider && row.wire_model_id == offering.wire_model_id |
| 557 | }) { |
| 558 | offering.endpoint_key.clone_from(&existing.endpoint_key); |
| 559 | offering.default_for_provider = existing.default_for_provider; |
| 560 | } else if ProviderDescriptor::for_kind(provider).wire_policy() == WirePolicy::ModelAware |
| 561 | && provider != ProviderKind::Deepseek |
| 562 | { |
| 563 | continue; |
| 564 | } |
| 565 | // Positive declarations are not verified executable capabilities. |
| 566 | // Explicit negatives can still restrict a route conservatively. |
| 567 | let declared = offering.capabilities; |
| 568 | offering.capabilities = RouteCapabilities { |
| 569 | attachments: if model.attachment == Some(false) { |
| 570 | declared.attachments |
| 571 | } else { |
| 572 | Default::default() |
| 573 | }, |
| 574 | image_input: if declared.image_input == super::CapabilityState::Unsupported { |
| 575 | declared.image_input |
| 576 | } else { |
| 577 | Default::default() |
| 578 | }, |
| 579 | reasoning: if model.reasoning == Some(false) { |
| 580 | declared.reasoning |
| 581 | } else { |
| 582 | Default::default() |
| 583 | }, |
| 584 | native_tool_calls: if model.tool_call == Some(false) { |
| 585 | declared.native_tool_calls |
| 586 | } else { |
| 587 | Default::default() |
| 588 | }, |
| 589 | structured_output: if model.structured_output == Some(false) { |
| 590 | declared.structured_output |
| 591 | } else { |
| 592 | Default::default() |
| 593 | }, |
| 594 | ..RouteCapabilities::default() |
| 595 | }; |
| 596 | self.configured_offerings |
| 597 | .push((crate::catalog::base_url_fingerprint(base_url), offering)); |
| 598 | } |
| 599 | self |
| 600 | } |
| 601 | |
| 602 | /// Resolve a request into an executable route candidate. |
| 603 | /// |
| 604 | /// # Errors |
| 605 | /// Returns [`RouteError`] when the model is empty, the provider is invalid, |
| 606 | /// or a clearly-foreign model is requested for a strict direct provider. |
| 607 | pub fn resolve(&self, req: &RouteRequest) -> Result<ReadyRouteCandidate, RouteError> { |
| 608 | self.resolve_inner(req, false) |
| 609 | } |
| 610 | |
| 611 | /// Resolve with catalog facts authenticated against this exact endpoint. |
| 612 | /// |
| 613 | /// The ordinary [`Self::resolve`] path strips capabilities and pricing when |
| 614 | /// a route uses a custom base URL, because a same-named first-party model is |
| 615 | /// not evidence about an arbitrary proxy. Callers may use this seam only |
| 616 | /// when the injected offering came from the selected provider identity's |
| 617 | /// own endpoint and its base-URL fingerprint matches the request endpoint. |
| 618 | /// All normal routing and protocol validation still applies. |
| 619 | pub fn resolve_with_endpoint_catalog_authority( |
| 620 | &self, |
| 621 | req: &RouteRequest, |
| 622 | ) -> Result<ReadyRouteCandidate, RouteError> { |
| 623 | self.resolve_inner(req, true) |
| 624 | } |
| 625 | |
| 626 | fn resolve_inner( |
| 627 | &self, |
| 628 | req: &RouteRequest, |
| 629 | endpoint_catalog_authoritative: bool, |
| 630 | ) -> Result<ReadyRouteCandidate, RouteError> { |
| 631 | let pulled = self |
| 632 | .follow_registry_overlay |
| 633 | .then(crate::cloud_facts::overlay::pulled_registry) |
| 634 | .flatten(); |
| 635 | let active_offerings = pulled.as_deref().map_or(self.offerings.as_slice(), |reg| { |
| 636 | reg.compiled.route_offerings.as_slice() |
| 637 | }); |
| 638 | let provider = req.explicit_provider.unwrap_or_default(); |
| 639 | let active_naming = pulled |
| 640 | .as_deref() |
| 641 | .and_then(|reg| reg.compiled.naming.get(provider.as_str())); |
| 642 | if self.configured_offerings.is_empty() { |
| 643 | return self.resolve_scoped( |
| 644 | req, |
| 645 | endpoint_catalog_authoritative, |
| 646 | active_offerings, |
| 647 | active_naming, |
| 648 | ); |
| 649 | } |
| 650 | let mut scoped_offerings = active_offerings.to_vec(); |
| 651 | let mut scoped_configured = Vec::new(); |
| 652 | let base_url = req |
| 653 | .base_url_override |
| 654 | .as_deref() |
| 655 | .unwrap_or_else(|| ProviderDescriptor::for_kind(provider).default_base_url()); |
| 656 | let fingerprint = crate::catalog::base_url_fingerprint(base_url); |
| 657 | let selected_id = req |
| 658 | .model_selector |
| 659 | .as_ref() |
| 660 | .map(LogicalModelRef::raw) |
| 661 | .or_else(|| req.saved_provider_model.as_ref().map(WireModelId::as_str)); |
| 662 | for (endpoint, offering) in &self.configured_offerings { |
| 663 | if !base_url.contains(['@', '?', '#']) |
| 664 | && *endpoint == fingerprint |
| 665 | && offering.provider.as_str() == provider.as_str() |
| 666 | && selected_id == Some(offering.wire_model_id.as_str()) |
| 667 | { |
| 668 | scoped_offerings.retain(|row| { |
| 669 | row.provider != offering.provider || row.wire_model_id != offering.wire_model_id |
| 670 | }); |
| 671 | scoped_offerings.push(offering.clone()); |
| 672 | scoped_configured.push((endpoint.clone(), offering.clone())); |
| 673 | } |
| 674 | } |
| 675 | let scoped = Self { |
| 676 | offerings: scoped_offerings, |
| 677 | configured_offerings: scoped_configured, |
| 678 | follow_registry_overlay: false, |
| 679 | go_catalog: self.go_catalog.clone(), |
| 680 | }; |
| 681 | scoped.resolve_scoped( |
| 682 | req, |
| 683 | endpoint_catalog_authoritative, |
| 684 | &scoped.offerings, |
| 685 | active_naming, |
| 686 | ) |
| 687 | } |
| 688 | |
| 689 | fn resolve_scoped( |
| 690 | &self, |
| 691 | req: &RouteRequest, |
| 692 | endpoint_catalog_authoritative: bool, |
| 693 | offerings: &[ProviderModelOffering], |
| 694 | pulled_naming: Option<&CompiledNamingRules>, |
| 695 | ) -> Result<ReadyRouteCandidate, RouteError> { |
| 696 | // 1. Provider scope from explicit choice only; default otherwise. |
| 697 | // The provider is NEVER inferred from a model prefix. |
| 698 | let provider_kind = req.explicit_provider.unwrap_or_default(); |
| 699 | if provider_kind == ProviderKind::Antigravity { |
| 700 | return Err(RouteError::InvalidProvider( |
| 701 | crate::LEGACY_ANTIGRAVITY_TOMBSTONE_MESSAGE.to_string(), |
| 702 | )); |
| 703 | } |
| 704 | let descriptor = ProviderDescriptor::for_kind(provider_kind); |
| 705 | let provider_id = descriptor.id(); |
| 706 | let default_offering = Self::default_offering(offerings, &provider_id); |
| 707 | // Bound once so the endpoint-key consumers below cannot desync from |
| 708 | // the protocol stamp: only a custom table may override the descriptor |
| 709 | // policy, and a `chat` / unknown dialect arrives as `None` (the |
| 710 | // static policy applies). |
| 711 | let custom_wire_override = match (provider_kind, req.wire_override) { |
| 712 | (ProviderKind::Custom, Some(protocol)) => Some(protocol), |
| 713 | _ => None, |
| 714 | }; |
| 715 | |
| 716 | // 2. Determine the logical selector from explicit choice, then the |
| 717 | // saved-model fallback, then the provider default. |
| 718 | let logical_model = match &req.model_selector { |
| 719 | Some(selector) => selector.clone(), |
| 720 | None => { |
| 721 | // No selector: fall back to saved wire model, then provider |
| 722 | // default. Both stay in the resolved provider's scope. |
| 723 | let raw = req |
| 724 | .saved_provider_model |
| 725 | .as_ref() |
| 726 | .map(|w| w.as_str().to_string()) |
| 727 | .unwrap_or_else(|| { |
| 728 | default_offering.map_or_else( |
| 729 | || descriptor.default_wire_model().as_str().to_string(), |
| 730 | |offering| offering.wire_model_id.as_str().to_string(), |
| 731 | ) |
| 732 | }); |
| 733 | LogicalModelRef::from(raw) |
| 734 | } |
| 735 | }; |
| 736 | |
| 737 | // Reject an empty selector from ANY source (explicit, saved, or a |
| 738 | // degenerate default), not just an empty explicit selector. |
| 739 | if logical_model.raw().is_empty() { |
| 740 | return Err(RouteError::EmptyModel); |
| 741 | } |
| 742 | |
| 743 | // 3. `auto` is an opt-in sentinel: resolve to the provider default wire |
| 744 | // id without treating "auto" as a literal model name. |
| 745 | let is_auto = logical_model.is_auto(); |
| 746 | |
| 747 | // 4. Map the selector to a wire id within provider scope. |
| 748 | // Prefixed selectors are preserved VERBATIM as the wire id. |
| 749 | let custom_endpoint = |
| 750 | request_uses_custom_endpoint(&descriptor, req.base_url_override.as_deref()); |
| 751 | let model_aware = descriptor.wire_policy() == WirePolicy::ModelAware; |
| 752 | // A model-aware protocol row is an exact provider-endpoint fact. |
| 753 | // OpenCode Zen's published roster is closed; DeepSeek's direct route |
| 754 | // deliberately preserves its existing future-model pass-through and |
| 755 | // sends unknown bare ids over Chat until an exact Responses row exists. |
| 756 | // A custom DeepSeek-compatible endpoint retains that pass-through, but |
| 757 | // a custom URL must not weaken another model-aware provider's closed |
| 758 | // protocol roster. |
| 759 | let require_catalog_match = model_aware && provider_kind != ProviderKind::Deepseek; |
| 760 | let mut selected = if is_auto { |
| 761 | match default_offering { |
| 762 | None if require_catalog_match => { |
| 763 | return Err(RouteError::UnsupportedModelProtocol { |
| 764 | provider: provider_id.clone(), |
| 765 | model: descriptor.default_wire_model().as_str().to_string(), |
| 766 | endpoint_key: "unproven".to_string(), |
| 767 | }); |
| 768 | } |
| 769 | None => ResolvedOffering::unknown(descriptor.default_wire_model()), |
| 770 | Some(offering) => ResolvedOffering::from_offering(offering), |
| 771 | } |
| 772 | } else { |
| 773 | self.scope_selector( |
| 774 | provider_kind, |
| 775 | &provider_id, |
| 776 | &logical_model, |
| 777 | req.base_url_override.as_deref(), |
| 778 | custom_endpoint, |
| 779 | require_catalog_match, |
| 780 | offerings, |
| 781 | pulled_naming, |
| 782 | )? |
| 783 | }; |
| 784 | let connection_base = req |
| 785 | .base_url_override |
| 786 | .as_deref() |
| 787 | .unwrap_or_else(|| descriptor.default_base_url()); |
| 788 | let mut go_dispatch = None; |
| 789 | if provider_kind == ProviderKind::OpencodeGo { |
| 790 | let id = selected.wire_model_id.as_str(); |
| 791 | let unproven = || RouteError::UnsupportedModelProtocol { |
| 792 | provider: provider_id.clone(), |
| 793 | model: id.to_string(), |
| 794 | endpoint_key: "unproven".to_string(), |
| 795 | }; |
| 796 | if let Some(catalog) = &self.go_catalog { |
| 797 | if !endpoint_catalog_authoritative || catalog.connection.base_url != connection_base |
| 798 | { |
| 799 | return Err(unproven()); |
| 800 | } |
| 801 | let (key, url) = catalog.models.get(id).ok_or_else(unproven)?; |
| 802 | let base = crate::opencode_go_dispatch_base_url(connection_base, url) |
| 803 | .ok_or_else(unproven)?; |
| 804 | selected.endpoint_key = key.clone(); |
| 805 | go_dispatch = Some((catalog.connection.clone(), base)); |
| 806 | } else { |
| 807 | selected.endpoint_key = crate::opencode_go_endpoint_key(id) |
| 808 | .ok_or_else(unproven)? |
| 809 | .to_string(); |
| 810 | } |
| 811 | } |
| 812 | if provider_kind == ProviderKind::Deepseek && custom_endpoint { |
| 813 | selected.endpoint_key = "chat".to_string(); |
| 814 | } |
| 815 | if custom_endpoint && !endpoint_catalog_authoritative { |
| 816 | // Capabilities and pricing belong to the exact provider endpoint |
| 817 | // offering that reported them. Reusing a provider enum and a |
| 818 | // first-party model id against a custom compatible endpoint does |
| 819 | // not prove that proxy serves the same canonical model, limits, |
| 820 | // modality, tool, reasoning, or billing contract. Keep the |
| 821 | // caller's wire model id, but clear every unowned offering fact at |
| 822 | // the authority boundary instead of presenting it as verified. |
| 823 | // The endpoint_key/protocol stays: it is the provider adapter's |
| 824 | // wire contract (a model-aware roster row or fixed policy), not an |
| 825 | // endpoint-catalog fact, and coercing it to Chat would silently |
| 826 | // change how a Responses- or Messages-bound route speaks. |
| 827 | // Deepseek's custom-endpoint Chat pass-through is handled above. |
| 828 | selected.canonical_model = None; |
| 829 | selected.limits = RouteLimits::default(); |
| 830 | selected.capabilities = RouteCapabilities::default(); |
| 831 | selected.pricing = PricingSku::UnknownOrStale; |
| 832 | } |
| 833 | let base_url = req |
| 834 | .base_url_override |
| 835 | .as_deref() |
| 836 | .unwrap_or_else(|| descriptor.default_base_url()); |
| 837 | let mut declared_limit_overrides = Vec::new(); |
| 838 | if let Some((_, offering)) = |
| 839 | self.configured_offerings |
| 840 | .iter() |
| 841 | .find(|(fingerprint, offering)| { |
| 842 | !base_url.contains(['@', '?', '#']) |
| 843 | && offering.provider == provider_id |
| 844 | && offering.wire_model_id == selected.wire_model_id |
| 845 | && req |
| 846 | .model_selector |
| 847 | .as_ref() |
| 848 | .map(LogicalModelRef::raw) |
| 849 | .or_else(|| req.saved_provider_model.as_ref().map(WireModelId::as_str)) |
| 850 | == Some(offering.wire_model_id.as_str()) |
| 851 | && *fingerprint == crate::catalog::base_url_fingerprint(base_url) |
| 852 | }) |
| 853 | { |
| 854 | selected.canonical_model = None; |
| 855 | selected.limits = RouteLimits { |
| 856 | output_declared: offering.limits.output_tokens.is_some(), |
| 857 | ..offering.limits |
| 858 | }; |
| 859 | selected.capabilities = offering.capabilities; |
| 860 | selected.pricing = offering.pricing.clone(); |
| 861 | for (field, value) in [ |
| 862 | (LimitField::ContextTokens, offering.limits.context_tokens), |
| 863 | (LimitField::InputTokens, offering.limits.input_tokens), |
| 864 | (LimitField::OutputTokens, offering.limits.output_tokens), |
| 865 | ] { |
| 866 | declared_limit_overrides.push(SourcedLimitOverride { |
| 867 | field, |
| 868 | value, |
| 869 | source: super::OverrideSource::UserModelMetadata, |
| 870 | }); |
| 871 | } |
| 872 | } |
| 873 | if provider_kind == ProviderKind::Zai { |
| 874 | let effective_base_url = req |
| 875 | .base_url_override |
| 876 | .as_deref() |
| 877 | .unwrap_or_else(|| descriptor.default_base_url()); |
| 878 | selected.capabilities.server_side_web_search = documented_zai_web_search_for_route( |
| 879 | provider_kind, |
| 880 | selected.wire_model_id.as_str(), |
| 881 | effective_base_url, |
| 882 | ); |
| 883 | } |
| 884 | if provider_kind == ProviderKind::Moonshot { |
| 885 | let effective_base_url = req |
| 886 | .base_url_override |
| 887 | .as_deref() |
| 888 | .unwrap_or_else(|| descriptor.default_base_url()); |
| 889 | selected.capabilities.server_side_web_search = documented_moonshot_web_search_for_route( |
| 890 | provider_kind, |
| 891 | selected.wire_model_id.as_str(), |
| 892 | effective_base_url, |
| 893 | ); |
| 894 | } |
| 895 | if matches!( |
| 896 | provider_kind, |
| 897 | ProviderKind::Deepseek | ProviderKind::DeepseekAnthropic |
| 898 | ) { |
| 899 | let effective_base_url = req |
| 900 | .base_url_override |
| 901 | .as_deref() |
| 902 | .unwrap_or_else(|| descriptor.default_base_url()); |
| 903 | selected.capabilities.server_side_web_search = documented_deepseek_web_search_for_route( |
| 904 | provider_kind, |
| 905 | selected.wire_model_id.as_str(), |
| 906 | effective_base_url, |
| 907 | ); |
| 908 | selected.capabilities.files_api = documented_deepseek_files_api_for_route( |
| 909 | provider_kind, |
| 910 | selected.wire_model_id.as_str(), |
| 911 | effective_base_url, |
| 912 | ); |
| 913 | // Flash accepts images on every official DeepSeek dialect, |
| 914 | // including the Messages route the curated rows do not cover. |
| 915 | // Only ever widens: an official Pro row keeps its documented |
| 916 | // `Unsupported`, a custom host keeps its cleared `Unknown`. |
| 917 | if documented_deepseek_image_input_for_route( |
| 918 | provider_kind, |
| 919 | selected.wire_model_id.as_str(), |
| 920 | effective_base_url, |
| 921 | ) == super::CapabilityState::Supported |
| 922 | { |
| 923 | selected.capabilities.image_input = super::CapabilityState::Supported; |
| 924 | } |
| 925 | } |
| 926 | |
| 927 | let protocol = custom_wire_override |
| 928 | .or_else(|| descriptor.protocol_for_endpoint(&selected.endpoint_key)) |
| 929 | .ok_or_else(|| RouteError::UnsupportedModelProtocol { |
| 930 | provider: provider_id.clone(), |
| 931 | model: selected.wire_model_id.as_str().to_string(), |
| 932 | endpoint_key: selected.endpoint_key.clone(), |
| 933 | })?; |
| 934 | let (catalog_connection, dispatch_base) = match go_dispatch { |
| 935 | Some((connection, base)) => (Some(connection), base), |
| 936 | None => (None, connection_base.to_owned()), |
| 937 | }; |
| 938 | let endpoint = ResolvedEndpoint { |
| 939 | catalog_connection, |
| 940 | base_url: dispatch_base, |
| 941 | endpoint_key: selected.endpoint_key, |
| 942 | protocol, |
| 943 | }; |
| 944 | |
| 945 | // Advisory validation (#1519): a non-loopback `http://` endpoint sends |
| 946 | // credentials in plaintext. This is advisory, not a hard fail, so |
| 947 | // `ok` stays true and local `http://localhost` runtimes (Ollama / vLLM / |
| 948 | // SGLang defaults) stay clean. |
| 949 | let mut messages = Vec::new(); |
| 950 | if endpoint_uses_insecure_http(&endpoint.base_url) { |
| 951 | messages |
| 952 | .push("endpoint uses insecure http:// (credentials sent in plaintext)".to_string()); |
| 953 | } |
| 954 | let validation = ValidationReport { ok: true, messages }; |
| 955 | let responses_profile_id = crate::responses_dialect::select_responses_profile( |
| 956 | crate::responses_dialect::ResponsesProfileQuery { |
| 957 | protocol, |
| 958 | provider: provider_kind, |
| 959 | endpoint_key: &endpoint.endpoint_key, |
| 960 | base_url: &endpoint.base_url, |
| 961 | explicit_profile: req.responses_profile_override.as_deref(), |
| 962 | }, |
| 963 | ) |
| 964 | .map_err(|err| RouteError::ResponsesProfile { |
| 965 | provider: provider_id.clone(), |
| 966 | detail: err.to_string(), |
| 967 | })? |
| 968 | .map(|profile| profile.id); |
| 969 | |
| 970 | // Apply caller-requested limit overrides in order, BEFORE the candidate |
| 971 | // is minted. The candidate is immutable afterwards; the applied |
| 972 | // overrides are recorded on it as provenance. |
| 973 | let mut limits = selected.limits; |
| 974 | for limit_override in &req.limit_overrides { |
| 975 | match limit_override.field { |
| 976 | LimitField::ContextTokens => limits.context_tokens = limit_override.value, |
| 977 | LimitField::InputTokens => limits.input_tokens = limit_override.value, |
| 978 | LimitField::OutputTokens => { |
| 979 | limits.output_tokens = limit_override.value; |
| 980 | limits.output_declared = limit_override.source |
| 981 | == super::OverrideSource::UserModelMetadata |
| 982 | && limit_override.value.is_some(); |
| 983 | } |
| 984 | } |
| 985 | } |
| 986 | |
| 987 | Ok(ReadyRouteCandidate::new( |
| 988 | provider_id, |
| 989 | provider_kind, |
| 990 | logical_model, |
| 991 | selected.canonical_model, |
| 992 | selected.wire_model_id, |
| 993 | endpoint, |
| 994 | // The resolver never inspects credentials: auth is honestly |
| 995 | // `Unresolved` at resolution time, not a claimed `Missing`. |
| 996 | ResolvedAuthSource::Unresolved, |
| 997 | protocol, |
| 998 | responses_profile_id, |
| 999 | limits, |
| 1000 | selected.capabilities, |
| 1001 | // #3085: honest pricing projected from the matched offering (the |
| 1002 | // catalog layer maps sourced cost → SKU); `UnknownOrStale` whenever |
| 1003 | // no offering was matched or the offering carried no price. |
| 1004 | Some(selected.pricing), |
| 1005 | validation, |
| 1006 | declared_limit_overrides |
| 1007 | .into_iter() |
| 1008 | .chain(req.limit_overrides.iter().cloned()) |
| 1009 | .collect(), |
| 1010 | )) |
| 1011 | } |
| 1012 | |
| 1013 | /// Interpret a concrete (non-auto) selector strictly within provider scope. |
| 1014 | #[expect(clippy::too_many_arguments)] |
| 1015 | fn scope_selector( |
| 1016 | &self, |
| 1017 | provider_kind: ProviderKind, |
| 1018 | provider_id: &ProviderId, |
| 1019 | logical_model: &LogicalModelRef, |
| 1020 | base_url_override: Option<&str>, |
| 1021 | custom_endpoint: bool, |
| 1022 | require_catalog_match: bool, |
| 1023 | offerings: &[ProviderModelOffering], |
| 1024 | pulled_naming: Option<&CompiledNamingRules>, |
| 1025 | ) -> Result<ResolvedOffering, RouteError> { |
| 1026 | let resolved = resolve_model_against_offerings( |
| 1027 | provider_kind, |
| 1028 | logical_model.raw(), |
| 1029 | base_url_override, |
| 1030 | offerings, |
| 1031 | &self.configured_offerings, |
| 1032 | pulled_naming, |
| 1033 | )?; |
| 1034 | if let Some(offering) = resolved.offering { |
| 1035 | return Ok(ResolvedOffering::from_offering(&offering)); |
| 1036 | } |
| 1037 | |
| 1038 | if !custom_endpoint |
| 1039 | && provider_kind == ProviderKind::Zai |
| 1040 | && (Self::selector_matches_other_provider_offering( |
| 1041 | offerings, |
| 1042 | provider_id, |
| 1043 | &resolved.logical, |
| 1044 | ) || logical_model.namespace_hint().is_some()) |
| 1045 | { |
| 1046 | return Err(RouteError::ForeignModelForDirectProvider { |
| 1047 | provider: provider_id.clone(), |
| 1048 | model: resolved.logical, |
| 1049 | }); |
| 1050 | } |
| 1051 | |
| 1052 | if require_catalog_match { |
| 1053 | if provider_kind == ProviderKind::Codewhale { |
| 1054 | return Ok(ResolvedOffering { |
| 1055 | wire_model_id: WireModelId::from(resolved.wire_id.as_str()), |
| 1056 | canonical_model: None, |
| 1057 | endpoint_key: super::codewhale_endpoint_key_for_model(&resolved.wire_id) |
| 1058 | .to_string(), |
| 1059 | limits: RouteLimits::default(), |
| 1060 | capabilities: RouteCapabilities::default(), |
| 1061 | pricing: PricingSku::UnknownOrStale, |
| 1062 | }); |
| 1063 | } |
| 1064 | if provider_kind == ProviderKind::OpencodeZen |
| 1065 | && resolved.wire_id.to_ascii_lowercase().contains("muse-spark") |
| 1066 | { |
| 1067 | return Ok(ResolvedOffering { |
| 1068 | wire_model_id: WireModelId::from(resolved.wire_id.as_str()), |
| 1069 | canonical_model: None, |
| 1070 | endpoint_key: "responses".to_string(), |
| 1071 | limits: RouteLimits::default(), |
| 1072 | capabilities: RouteCapabilities::default(), |
| 1073 | pricing: PricingSku::UnknownOrStale, |
| 1074 | }); |
| 1075 | } |
| 1076 | return Err(RouteError::UnsupportedModelProtocol { |
| 1077 | provider: provider_id.clone(), |
| 1078 | model: resolved.wire_id, |
| 1079 | endpoint_key: "unproven".to_string(), |
| 1080 | }); |
| 1081 | } |
| 1082 | |
| 1083 | Ok(ResolvedOffering::unknown(WireModelId::from( |
| 1084 | resolved.wire_id, |
| 1085 | ))) |
| 1086 | } |
| 1087 | |
| 1088 | fn default_offering<'a>( |
| 1089 | offerings: &'a [ProviderModelOffering], |
| 1090 | provider_id: &ProviderId, |
| 1091 | ) -> Option<&'a ProviderModelOffering> { |
| 1092 | offerings |
| 1093 | .iter() |
| 1094 | .find(|offering| offering.provider == *provider_id && offering.default_for_provider) |
| 1095 | } |
| 1096 | |
| 1097 | /// True when `raw` names an offering that lives on a *different* provider. |
| 1098 | /// |
| 1099 | /// The `wire_model_id` arm catches the common case (a bare id another |
| 1100 | /// provider serves). The `canonical_model` arm covers catalog rows whose |
| 1101 | /// canonical id is slash-free: Models.dev canonical ids normally contain a |
| 1102 | /// namespace (`zhipuai/glm-5.2`) and are already caught by the |
| 1103 | /// `namespace_hint()` guard at the call site, but a bare canonical id (or a |
| 1104 | /// hand-authored offering) would slip through wire-id matching alone. It is |
| 1105 | /// kept deliberately so a bare canonical selector cannot masquerade as a |
| 1106 | /// pass-through model on the wrong provider. |
| 1107 | fn selector_matches_other_provider_offering( |
| 1108 | offerings: &[ProviderModelOffering], |
| 1109 | provider_id: &ProviderId, |
| 1110 | raw: &str, |
| 1111 | ) -> bool { |
| 1112 | offerings.iter().any(|offering| { |
| 1113 | offering.provider != *provider_id |
| 1114 | && (offering.wire_model_id.as_str() == raw |
| 1115 | || offering |
| 1116 | .canonical_model |
| 1117 | .as_ref() |
| 1118 | .is_some_and(|model| model.as_str() == raw)) |
| 1119 | }) |
| 1120 | } |
| 1121 | } |
| 1122 | |
| 1123 | fn build_default_offerings() -> Vec<ProviderModelOffering> { |
| 1124 | let mut seen: std::collections::HashSet<(String, String)> = std::collections::HashSet::new(); |
| 1125 | let mut out = Vec::new(); |
| 1126 | let asset_rows = seed_catalog_offerings() |
| 1127 | .iter() |
| 1128 | .map(CatalogOffering::to_offering) |
| 1129 | .collect::<Vec<_>>(); |
| 1130 | // Seam first so it wins identity collisions, then asset-only rows follow. |
| 1131 | let go_metadata: std::collections::HashMap<_, _> = asset_rows |
| 1132 | .iter() |
| 1133 | .filter(|row| row.provider.as_str() == "opencode-go") |
| 1134 | .map(|row| (row.wire_model_id.as_str(), row)) |
| 1135 | .collect(); |
| 1136 | for mut offering in bundled_offerings() |
| 1137 | .into_iter() |
| 1138 | .chain(asset_rows.iter().cloned()) |
| 1139 | { |
| 1140 | // The transport seam must not erase already sourced Go limits/prices. |
| 1141 | if offering.provider.as_str() == "opencode-go" |
| 1142 | && let Some(metadata) = go_metadata.get(offering.wire_model_id.as_str()) |
| 1143 | { |
| 1144 | offering |
| 1145 | .canonical_model |
| 1146 | .clone_from(&metadata.canonical_model); |
| 1147 | offering.limits = metadata.limits; |
| 1148 | offering.capabilities = metadata.capabilities; |
| 1149 | offering.pricing.clone_from(&metadata.pricing); |
| 1150 | } |
| 1151 | let key = ( |
| 1152 | offering.provider.as_str().to_string(), |
| 1153 | offering.wire_model_id.as_str().to_string(), |
| 1154 | ); |
| 1155 | if seen.insert(key) { |
| 1156 | out.push(offering); |
| 1157 | } |
| 1158 | } |
| 1159 | out |
| 1160 | } |
| 1161 | |
| 1162 | fn default_offerings() -> Vec<ProviderModelOffering> { |
| 1163 | default_offerings_slice().to_vec() |
| 1164 | } |
| 1165 | |
| 1166 | fn request_uses_custom_endpoint( |
| 1167 | descriptor: &ProviderDescriptor, |
| 1168 | base_url_override: Option<&str>, |
| 1169 | ) -> bool { |
| 1170 | base_url_override |
| 1171 | .is_some_and(|base_url| provider_preserves_custom_base_url_model(descriptor.kind, base_url)) |
| 1172 | } |
| 1173 | |
| 1174 | /// True when `base_url` is an `http://` endpoint whose host is NOT loopback |
| 1175 | /// (#1519). Such an endpoint sends credentials in plaintext over the network; |
| 1176 | /// loopback (`localhost` / `127.0.0.1` / `::1`) is exempt because local |
| 1177 | /// runtimes (Ollama / vLLM / SGLang) default to plain `http://localhost`. |
| 1178 | fn endpoint_uses_insecure_http(base_url: &str) -> bool { |
| 1179 | let trimmed = base_url.trim(); |
| 1180 | // Scheme match is case-insensitive but must be `http`, not `https`. |
| 1181 | let Some(rest) = strip_http_scheme(trimmed) else { |
| 1182 | return false; |
| 1183 | }; |
| 1184 | !is_loopback_host(host_of_authority(rest)) |
| 1185 | } |
| 1186 | |
| 1187 | /// Strip a leading case-insensitive `http://` scheme, returning the remainder. |
| 1188 | /// Returns `None` for any other scheme (including `https://`) or no scheme. |
| 1189 | fn strip_http_scheme(base_url: &str) -> Option<&str> { |
| 1190 | let idx = base_url.find("://")?; |
| 1191 | let (scheme, rest) = base_url.split_at(idx); |
| 1192 | if scheme.eq_ignore_ascii_case("http") { |
| 1193 | Some(&rest[3..]) |
| 1194 | } else { |
| 1195 | None |
| 1196 | } |
| 1197 | } |
| 1198 | |
| 1199 | /// Extract the bare host from an authority+path string: take the authority up |
| 1200 | /// to the first `/`, drop any `user@` userinfo and `:port` suffix, and unwrap |
| 1201 | /// `[..]` IPv6 brackets. |
| 1202 | fn host_of_authority(rest: &str) -> &str { |
| 1203 | let authority = rest.split('/').next().unwrap_or(rest); |
| 1204 | // Drop userinfo (`user:pass@host`) if present. |
| 1205 | let authority = authority.rsplit('@').next().unwrap_or(authority); |
| 1206 | if let Some(inner) = authority.strip_prefix('[') { |
| 1207 | // Bracketed IPv6 literal: host is everything up to the closing bracket. |
| 1208 | return inner.split(']').next().unwrap_or(inner); |
| 1209 | } |
| 1210 | // Otherwise strip a trailing `:port`. |
| 1211 | authority.split(':').next().unwrap_or(authority) |
| 1212 | } |
| 1213 | |
| 1214 | /// Whether `host` is an IPv4/IPv6/name loopback address. |
| 1215 | fn is_loopback_host(host: &str) -> bool { |
| 1216 | let host = host.trim().trim_matches(|c| c == '[' || c == ']'); |
| 1217 | if host.eq_ignore_ascii_case("localhost") { |
| 1218 | return true; |
| 1219 | } |
| 1220 | // Parse real addresses rather than pattern-matching a `127.` prefix: the |
| 1221 | // old `strip_prefix("127.") && 4 dot-parts` check classified |
| 1222 | // `127.evil.example.com` as loopback (2026-08-04 review), which would let |
| 1223 | // a hostile hostname inherit local-trust routing. `Ipv4Addr::is_loopback` |
| 1224 | // is exactly the 127.0.0.0/8 block; `Ipv6Addr::is_loopback` is `::1`. |
| 1225 | if let Ok(v4) = host.parse::<std::net::Ipv4Addr>() { |
| 1226 | return v4.is_loopback(); |
| 1227 | } |
| 1228 | if let Ok(v6) = host.parse::<std::net::Ipv6Addr>() { |
| 1229 | return v6.is_loopback(); |
| 1230 | } |
| 1231 | false |
| 1232 | } |
| 1233 | |
| 1234 | #[cfg(test)] |
| 1235 | mod loopback_tests { |
| 1236 | use super::{endpoint_uses_insecure_http, is_loopback_host}; |
| 1237 | |
| 1238 | #[test] |
| 1239 | fn loopback_matches_only_real_loopback_addresses() { |
| 1240 | assert!(is_loopback_host("localhost")); |
| 1241 | assert!(is_loopback_host("LocalHost")); |
| 1242 | assert!(is_loopback_host("127.0.0.1")); |
| 1243 | assert!(is_loopback_host("127.1.2.3")); // all of 127.0.0.0/8 |
| 1244 | assert!(is_loopback_host("::1")); |
| 1245 | assert!(is_loopback_host("[::1]")); |
| 1246 | |
| 1247 | // The 2026-08-04 regression: a hostile hostname that merely starts |
| 1248 | // with `127.` and has four dot-parts must NOT be trusted as local. |
| 1249 | assert!(!is_loopback_host("127.evil.example.com")); |
| 1250 | assert!(!is_loopback_host("127.0.0.1.evil.com")); |
| 1251 | assert!(!is_loopback_host("notlocalhost")); |
| 1252 | assert!(!is_loopback_host("10.0.0.1")); |
| 1253 | assert!(!is_loopback_host("localhost.evil.com")); |
| 1254 | } |
| 1255 | |
| 1256 | #[test] |
| 1257 | fn insecure_http_flags_a_hostile_127_lookalike() { |
| 1258 | // loopback stays exempt (local runtimes use plain http) |
| 1259 | assert!(!endpoint_uses_insecure_http("http://127.0.0.1:11434/v1")); |
| 1260 | assert!(!endpoint_uses_insecure_http("http://localhost:8000/v1")); |
| 1261 | // a real remote host dressed up as 127.* is insecure http |
| 1262 | assert!(endpoint_uses_insecure_http( |
| 1263 | "http://127.evil.example.com/v1" |
| 1264 | )); |
| 1265 | } |
| 1266 | } |
| 1267 |