| 1 | use std::collections::{BTreeMap, BTreeSet}; |
| 2 | use std::sync::OnceLock; |
| 3 | |
| 4 | use serde::{Deserialize, Serialize}; |
| 5 | use serde_json::{Map, Value}; |
| 6 | |
| 7 | use super::keys::{KeyRole, TrustedKey}; |
| 8 | use super::types::{ModelFact, PricingFact}; |
| 9 | use super::verify::{ |
| 10 | Authenticated, EnvelopeLimits, FUTURE_CLOCK_TOLERANCE_SECS, FactsRejection, authenticate, |
| 11 | check_automation_window, parse_rfc3339_utc, sha256_hex, |
| 12 | }; |
| 13 | use crate::catalog::{CatalogOffering, CatalogSource}; |
| 14 | use crate::descriptors::{ |
| 15 | DESCRIPTORS_JSON, DescriptorDiscovery, DescriptorWire, ModelIdsPolicy, ProviderDescriptor, |
| 16 | model_rules_for, normalize_model_lookup_key, |
| 17 | }; |
| 18 | use crate::models_dev::{ModelsDevCost, ModelsDevLimit, ModelsDevModel, ModelsDevProviderModel}; |
| 19 | use crate::route::{ |
| 20 | CapabilityState, ModelId, OPENCODE_ZEN_DEPRECATED_ENDPOINT_KEY, ProviderModelOffering, |
| 21 | RouteCapabilities, RouteLimits, opencode_zen_endpoint_key_for_npm, |
| 22 | }; |
| 23 | |
| 24 | pub const REGISTRY_SCHEMA: &str = "codewhale.registry.v1"; |
| 25 | pub const REGISTRY_CHANNEL: &str = "registry"; |
| 26 | pub const MAX_REGISTRY_PAYLOAD_BYTES: usize = 8 * 1024 * 1024; |
| 27 | pub const MAX_REGISTRY_ENVELOPE_BYTES: usize = MAX_REGISTRY_PAYLOAD_BYTES / 3 * 4 + 64 * 1024; |
| 28 | const OPENAI_COMPATIBLE_WIRE: &str = "openai-compatible"; |
| 29 | const MAX_PROVIDER_ID_CHARS: usize = 48; |
| 30 | |
| 31 | const PRODUCT_RESERVED_ENV_VARS: &[&str] = &[ |
| 32 | "ARK_API_KEY", |
| 33 | "BAIDU_SEARCH_API_KEY", |
| 34 | "BRAVE_API_KEY", |
| 35 | "EXA_API_KEY", |
| 36 | "FIRECRAWL_API_KEY", |
| 37 | "GEMINI_API_KEY", |
| 38 | "GLM_API_KEY", |
| 39 | "GOOGLE_GENERATIVE_AI_API_KEY", |
| 40 | "JINA_API_KEY", |
| 41 | "KIMI_API_KEY", |
| 42 | "METASO_API_KEY", |
| 43 | "MIMO_API_KEY", |
| 44 | "MIMO_TOKEN_PLAN_API_KEY", |
| 45 | "MODEL_API_KEY", |
| 46 | "NVIDIA_API_KEY", |
| 47 | "OLLAMA_API_KEY", |
| 48 | "OLLAMA_CLOUD_API_KEY", |
| 49 | "OPENCODE_API_KEY", |
| 50 | "PERPLEXITY_API_KEY", |
| 51 | "SEARCHAPI_API_KEY", |
| 52 | "SERPER_API_KEY", |
| 53 | "SERPLY_API_KEY", |
| 54 | "STEP_API_KEY", |
| 55 | "TAVILY_API_KEY", |
| 56 | "VOLCENGINE_ARK_API_KEY", |
| 57 | "WANJIE_API_KEY", |
| 58 | "WANJIE_MAAS_API_KEY", |
| 59 | "XIAOMI_API_KEY", |
| 60 | "XIAOMI_MIMO_TOKEN_PLAN_API_KEY", |
| 61 | "ZHIPU_API_KEY", |
| 62 | "Z_AI_API_KEY", |
| 63 | ]; |
| 64 | |
| 65 | #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] |
| 66 | pub struct Registry { |
| 67 | pub schema: String, |
| 68 | pub revision: u64, |
| 69 | pub generated_at: String, |
| 70 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 71 | pub not_after: Option<String>, |
| 72 | #[serde(default)] |
| 73 | pub providers: Vec<RegistryProvider>, |
| 74 | #[serde(default)] |
| 75 | pub models: Vec<Value>, |
| 76 | #[serde(default)] |
| 77 | pub offerings: Vec<Value>, |
| 78 | #[serde(default)] |
| 79 | pub dialects: Map<String, Value>, |
| 80 | } |
| 81 | |
| 82 | #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] |
| 83 | pub struct RegistryProvider { |
| 84 | pub id: String, |
| 85 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 86 | pub label: Option<String>, |
| 87 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 88 | pub kind: Option<String>, |
| 89 | #[serde(default, skip_serializing_if = "Vec::is_empty")] |
| 90 | pub aliases: Vec<String>, |
| 91 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 92 | pub wire_policy: Option<String>, |
| 93 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 94 | pub base_url: Option<String>, |
| 95 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 96 | pub auth: Option<RegistryAuth>, |
| 97 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 98 | pub default_model: Option<String>, |
| 99 | #[serde(flatten)] |
| 100 | pub rest: BTreeMap<String, Value>, |
| 101 | } |
| 102 | |
| 103 | #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] |
| 104 | pub struct RegistryAuth { |
| 105 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 106 | pub secret_slot: Option<String>, |
| 107 | #[serde(default, skip_serializing_if = "Vec::is_empty")] |
| 108 | pub env_vars: Vec<String>, |
| 109 | #[serde(flatten)] |
| 110 | pub rest: BTreeMap<String, Value>, |
| 111 | } |
| 112 | |
| 113 | #[derive(Debug, Clone, PartialEq)] |
| 114 | pub struct VerifiedRegistry { |
| 115 | pub registry: Registry, |
| 116 | pub key_id: String, |
| 117 | pub key_role: KeyRole, |
| 118 | pub sha256: String, |
| 119 | pub generated_at_unix: u64, |
| 120 | pub not_after: Option<u64>, |
| 121 | } |
| 122 | |
| 123 | #[derive(Debug, Clone)] |
| 124 | struct BundledProviderTrust { |
| 125 | kind: Option<String>, |
| 126 | base_url: Option<String>, |
| 127 | wire_policy: Option<String>, |
| 128 | wire: Option<String>, |
| 129 | secret_slot: Option<String>, |
| 130 | env_vars: Vec<String>, |
| 131 | api_key_env: Option<String>, |
| 132 | default_model: Option<String>, |
| 133 | is_descriptor: bool, |
| 134 | raw: Map<String, Value>, |
| 135 | } |
| 136 | |
| 137 | static BUNDLED_PROVIDER_TRUST: OnceLock<BTreeMap<String, BundledProviderTrust>> = OnceLock::new(); |
| 138 | |
| 139 | fn bundled_provider_trust() -> &'static BTreeMap<String, BundledProviderTrust> { |
| 140 | BUNDLED_PROVIDER_TRUST.get_or_init(|| { |
| 141 | let parsed: Value = serde_json::from_str(DESCRIPTORS_JSON) |
| 142 | .expect("committed provider_descriptors.json must parse"); |
| 143 | let mut map = BTreeMap::new(); |
| 144 | if let Some(providers) = parsed.get("providers").and_then(Value::as_array) { |
| 145 | for entry in providers { |
| 146 | let Some(id) = entry.get("id").and_then(Value::as_str) else { |
| 147 | continue; |
| 148 | }; |
| 149 | let env_vars = entry |
| 150 | .get("env_vars") |
| 151 | .and_then(Value::as_array) |
| 152 | .map(|items| { |
| 153 | items |
| 154 | .iter() |
| 155 | .filter_map(Value::as_str) |
| 156 | .map(String::from) |
| 157 | .collect() |
| 158 | }) |
| 159 | .unwrap_or_default(); |
| 160 | map.insert( |
| 161 | id.to_string(), |
| 162 | BundledProviderTrust { |
| 163 | kind: entry.get("kind").and_then(Value::as_str).map(String::from), |
| 164 | base_url: entry |
| 165 | .get("base_url") |
| 166 | .and_then(Value::as_str) |
| 167 | .map(String::from), |
| 168 | wire_policy: entry |
| 169 | .get("wire_policy") |
| 170 | .and_then(Value::as_str) |
| 171 | .map(String::from), |
| 172 | wire: None, |
| 173 | secret_slot: entry |
| 174 | .get("secret_store_slot") |
| 175 | .and_then(Value::as_str) |
| 176 | .map(String::from), |
| 177 | env_vars, |
| 178 | api_key_env: None, |
| 179 | default_model: entry |
| 180 | .get("default_model") |
| 181 | .and_then(Value::as_str) |
| 182 | .map(String::from), |
| 183 | is_descriptor: false, |
| 184 | raw: entry.as_object().cloned().unwrap_or_default(), |
| 185 | }, |
| 186 | ); |
| 187 | } |
| 188 | } |
| 189 | if let Some(descriptors) = parsed.get("descriptors").and_then(Value::as_array) { |
| 190 | for entry in descriptors { |
| 191 | let Some(id) = entry.get("id").and_then(Value::as_str) else { |
| 192 | continue; |
| 193 | }; |
| 194 | let wire = entry.get("wire").and_then(Value::as_str).map(String::from); |
| 195 | let api_key_env = entry |
| 196 | .get("api_key_env") |
| 197 | .and_then(Value::as_str) |
| 198 | .map(String::from); |
| 199 | map.insert( |
| 200 | id.to_string(), |
| 201 | BundledProviderTrust { |
| 202 | kind: None, |
| 203 | base_url: entry |
| 204 | .get("base_url") |
| 205 | .and_then(Value::as_str) |
| 206 | .map(String::from), |
| 207 | wire_policy: wire |
| 208 | .clone() |
| 209 | .or_else(|| Some(OPENAI_COMPATIBLE_WIRE.to_string())), |
| 210 | wire, |
| 211 | secret_slot: Some(id.to_string()), |
| 212 | env_vars: api_key_env.iter().cloned().collect(), |
| 213 | api_key_env, |
| 214 | default_model: entry |
| 215 | .get("default_model") |
| 216 | .and_then(Value::as_str) |
| 217 | .map(String::from), |
| 218 | is_descriptor: true, |
| 219 | raw: entry.as_object().cloned().unwrap_or_default(), |
| 220 | }, |
| 221 | ); |
| 222 | } |
| 223 | } |
| 224 | map |
| 225 | }) |
| 226 | } |
| 227 | |
| 228 | fn automation_provider_violation( |
| 229 | registry: &Registry, |
| 230 | raw_providers: Option<&Value>, |
| 231 | ) -> Option<String> { |
| 232 | if registry.providers.is_empty() { |
| 233 | return None; |
| 234 | } |
| 235 | let Some(raw_list) = raw_providers.and_then(Value::as_array) else { |
| 236 | return Some("providers do not match signed bytes".into()); |
| 237 | }; |
| 238 | if raw_list.len() != registry.providers.len() { |
| 239 | return Some("providers do not match signed bytes".into()); |
| 240 | } |
| 241 | let trust = bundled_provider_trust(); |
| 242 | let mut seen = BTreeSet::new(); |
| 243 | for (row, raw_row) in registry.providers.iter().zip(raw_list.iter()) { |
| 244 | let Some(obj) = raw_row.as_object() else { |
| 245 | return Some("malformed provider row".into()); |
| 246 | }; |
| 247 | if !seen.insert(row.id.as_str()) { |
| 248 | return Some(format!("duplicate provider {:?}", row.id)); |
| 249 | } |
| 250 | if let Some(adm) = obj.get("admission") |
| 251 | && !adm.is_null() |
| 252 | { |
| 253 | let Some(adm_obj) = adm.as_object() else { |
| 254 | return Some(format!("provider {:?} has malformed admission", row.id)); |
| 255 | }; |
| 256 | if adm_obj |
| 257 | .get("founder_signature") |
| 258 | .is_some_and(|v| !v.is_null()) |
| 259 | { |
| 260 | return Some(format!( |
| 261 | "provider {:?} requires a founder signature", |
| 262 | row.id |
| 263 | )); |
| 264 | } |
| 265 | } |
| 266 | let Some(bundled) = trust.get(&row.id) else { |
| 267 | return Some(format!( |
| 268 | "provider {:?} requires a founder signature", |
| 269 | row.id |
| 270 | )); |
| 271 | }; |
| 272 | if let Some(v) = obj.get("kind") |
| 273 | && v.as_str() != bundled.kind.as_deref() |
| 274 | { |
| 275 | return Some(format!("provider {:?} changes kind", row.id)); |
| 276 | } |
| 277 | if let Some(v) = obj.get("base_url") |
| 278 | && v.as_str() != bundled.base_url.as_deref() |
| 279 | { |
| 280 | return Some(format!("provider {:?} changes base_url", row.id)); |
| 281 | } |
| 282 | if let Some(v) = obj.get("wire_policy") |
| 283 | && v.as_str() != bundled.wire_policy.as_deref() |
| 284 | { |
| 285 | return Some(format!("provider {:?} changes wire_policy", row.id)); |
| 286 | } |
| 287 | if let Some(v) = obj.get("wire") |
| 288 | && v.as_str() != bundled.wire.as_deref() |
| 289 | { |
| 290 | return Some(format!("provider {:?} changes wire", row.id)); |
| 291 | } |
| 292 | if let Some(v) = obj.get("api_key_env") |
| 293 | && v.as_str() != bundled.api_key_env.as_deref() |
| 294 | { |
| 295 | return Some(format!("provider {:?} changes api_key_env", row.id)); |
| 296 | } |
| 297 | if let Some(v) = obj.get("secret_store_slot") |
| 298 | && v.as_str() != bundled.secret_slot.as_deref() |
| 299 | { |
| 300 | return Some(format!("provider {:?} changes secret_store_slot", row.id)); |
| 301 | } |
| 302 | if let Some(v) = obj.get("env_vars") { |
| 303 | let got = v |
| 304 | .as_array() |
| 305 | .and_then(|arr| arr.iter().map(Value::as_str).collect::<Option<Vec<_>>>()); |
| 306 | let expected: Vec<&str> = bundled.env_vars.iter().map(String::as_str).collect(); |
| 307 | if got.as_deref() != Some(expected.as_slice()) { |
| 308 | return Some(format!("provider {:?} changes env_vars", row.id)); |
| 309 | } |
| 310 | } |
| 311 | if let Some(v) = obj.get("auth") { |
| 312 | let Some(auth_obj) = v.as_object() else { |
| 313 | return Some(format!("provider {:?} changes auth", row.id)); |
| 314 | }; |
| 315 | let Some(auth) = &row.auth else { |
| 316 | return Some(format!("provider {:?} changes auth", row.id)); |
| 317 | }; |
| 318 | if !auth.rest.is_empty() |
| 319 | || auth_obj.is_empty() |
| 320 | || (auth_obj.contains_key("secret_slot") |
| 321 | && auth.secret_slot.as_deref() != bundled.secret_slot.as_deref()) |
| 322 | || (auth_obj.contains_key("env_vars") && auth.env_vars != bundled.env_vars) |
| 323 | { |
| 324 | return Some(format!("provider {:?} changes auth", row.id)); |
| 325 | } |
| 326 | } |
| 327 | for (key, value) in obj { |
| 328 | if value.is_null() |
| 329 | || matches!( |
| 330 | key.as_str(), |
| 331 | "id" | "admission" |
| 332 | | "auth" |
| 333 | | "kind" |
| 334 | | "base_url" |
| 335 | | "wire_policy" |
| 336 | | "wire" |
| 337 | | "api_key_env" |
| 338 | | "secret_store_slot" |
| 339 | | "env_vars" |
| 340 | ) |
| 341 | { |
| 342 | continue; |
| 343 | } |
| 344 | if key == "models" { |
| 345 | let Some(models) = value.as_object() else { |
| 346 | return Some(format!("provider {:?} has malformed models", row.id)); |
| 347 | }; |
| 348 | let bundled_models = bundled.raw.get("models").and_then(Value::as_object); |
| 349 | for (rule, rule_value) in models { |
| 350 | if rule_value.is_null() || matches!(rule.as_str(), "aliases" | "wire_slugs") { |
| 351 | continue; |
| 352 | } |
| 353 | if bundled_models.and_then(|m| m.get(rule)) != Some(rule_value) { |
| 354 | return Some(format!( |
| 355 | "provider {:?} changes models.{rule}, which requires a founder signature", |
| 356 | row.id |
| 357 | )); |
| 358 | } |
| 359 | } |
| 360 | continue; |
| 361 | } |
| 362 | if bundled.raw.get(key) != Some(value) { |
| 363 | return Some(format!( |
| 364 | "provider {:?} changes {key}, which requires a founder signature", |
| 365 | row.id |
| 366 | )); |
| 367 | } |
| 368 | } |
| 369 | } |
| 370 | None |
| 371 | } |
| 372 | |
| 373 | fn automation_offering_violation(offerings: &[Value]) -> Option<String> { |
| 374 | let is_true = |obj: Option<&Map<String, Value>>, key: &str| { |
| 375 | obj.and_then(|o| o.get(key)).and_then(Value::as_bool) == Some(true) |
| 376 | }; |
| 377 | for offering in offerings { |
| 378 | let Some(obj) = offering.as_object() else { |
| 379 | continue; |
| 380 | }; |
| 381 | let label = format!( |
| 382 | "offering {:?}/{:?}", |
| 383 | obj.get("provider") |
| 384 | .and_then(Value::as_str) |
| 385 | .unwrap_or_default(), |
| 386 | obj.get("id") |
| 387 | .or_else(|| obj.get("wire_model_id")) |
| 388 | .and_then(Value::as_str) |
| 389 | .unwrap_or_default() |
| 390 | ); |
| 391 | if obj.get("pricing_withheld").is_some_and(|v| !v.is_null()) { |
| 392 | return Some(format!( |
| 393 | "{label} sets pricing_withheld, which requires a founder signature" |
| 394 | )); |
| 395 | } |
| 396 | if obj |
| 397 | .get("corrections") |
| 398 | .is_some_and(|v| !v.is_null() && v.as_array().is_none_or(|a| !a.is_empty())) |
| 399 | { |
| 400 | return Some(format!( |
| 401 | "{label} carries corrections, which require a founder signature" |
| 402 | )); |
| 403 | } |
| 404 | let catalog = obj.get("catalog").and_then(Value::as_object); |
| 405 | let transport = obj.get("transport").and_then(Value::as_object); |
| 406 | if is_true(Some(obj), "default") |
| 407 | || is_true(Some(obj), "default_for_provider") |
| 408 | || is_true(catalog, "default") |
| 409 | || is_true(catalog, "default_for_provider") |
| 410 | || is_true(transport, "default_for_provider") |
| 411 | { |
| 412 | return Some(format!( |
| 413 | "{label} changes the provider default, which requires a founder signature" |
| 414 | )); |
| 415 | } |
| 416 | } |
| 417 | None |
| 418 | } |
| 419 | |
| 420 | pub fn verify_registry_envelope( |
| 421 | bytes: &[u8], |
| 422 | floor: Option<u64>, |
| 423 | keys: &[TrustedKey], |
| 424 | now_unix: u64, |
| 425 | ) -> Result<VerifiedRegistry, FactsRejection> { |
| 426 | let Authenticated { |
| 427 | envelope, |
| 428 | payload, |
| 429 | key_id, |
| 430 | key_role, |
| 431 | } = authenticate( |
| 432 | bytes, |
| 433 | REGISTRY_CHANNEL, |
| 434 | keys, |
| 435 | EnvelopeLimits { |
| 436 | envelope_bytes: MAX_REGISTRY_ENVELOPE_BYTES, |
| 437 | payload_bytes: MAX_REGISTRY_PAYLOAD_BYTES, |
| 438 | facts_metadata: false, |
| 439 | }, |
| 440 | )?; |
| 441 | let (Some(outer_published), Some(outer_sha)) = (&envelope.published_at, &envelope.sha256) |
| 442 | else { |
| 443 | return Err(FactsRejection::BadEnvelope( |
| 444 | "missing signed-payload metadata".into(), |
| 445 | )); |
| 446 | }; |
| 447 | let raw: Value = serde_json::from_slice(&payload) |
| 448 | .map_err(|err| FactsRejection::BadPayload(err.to_string()))?; |
| 449 | let schema = raw |
| 450 | .get("schema") |
| 451 | .and_then(Value::as_str) |
| 452 | .unwrap_or_default(); |
| 453 | if schema != REGISTRY_SCHEMA { |
| 454 | return Err(FactsRejection::WrongSchema { |
| 455 | got: schema.chars().take(64).collect(), |
| 456 | }); |
| 457 | } |
| 458 | let raw_providers = raw.get("providers").cloned(); |
| 459 | let registry: Registry = |
| 460 | serde_json::from_value(raw).map_err(|err| FactsRejection::BadPayload(err.to_string()))?; |
| 461 | if envelope.channel != REGISTRY_CHANNEL { |
| 462 | return Err(FactsRejection::WrongChannel { |
| 463 | expected: REGISTRY_CHANNEL.to_string(), |
| 464 | got: envelope.channel, |
| 465 | }); |
| 466 | } |
| 467 | if envelope.facts_version != registry.revision { |
| 468 | return Err(FactsRejection::Mismatch(format!( |
| 469 | "revision {} vs {}", |
| 470 | envelope.facts_version, registry.revision |
| 471 | ))); |
| 472 | } |
| 473 | if outer_published != ®istry.generated_at { |
| 474 | return Err(FactsRejection::Mismatch("generated_at".into())); |
| 475 | } |
| 476 | if envelope.not_after.is_some() && envelope.not_after != registry.not_after { |
| 477 | return Err(FactsRejection::Mismatch("not_after".into())); |
| 478 | } |
| 479 | if registry.revision == 0 { |
| 480 | return Err(FactsRejection::BadPayload( |
| 481 | "revision must be positive".into(), |
| 482 | )); |
| 483 | } |
| 484 | let generated_at = parse_rfc3339_utc(®istry.generated_at) |
| 485 | .ok_or_else(|| FactsRejection::BadPayload("invalid generated_at timestamp".into()))?; |
| 486 | if generated_at > now_unix.saturating_add(FUTURE_CLOCK_TOLERANCE_SECS) { |
| 487 | return Err(FactsRejection::BadPayload( |
| 488 | "generated_at is in the future".into(), |
| 489 | )); |
| 490 | } |
| 491 | let not_after = registry |
| 492 | .not_after |
| 493 | .as_deref() |
| 494 | .map(|value| { |
| 495 | parse_rfc3339_utc(value) |
| 496 | .ok_or_else(|| FactsRejection::BadPayload("invalid not_after timestamp".into())) |
| 497 | }) |
| 498 | .transpose()?; |
| 499 | if let Some(expires) = not_after |
| 500 | && expires <= generated_at |
| 501 | { |
| 502 | return Err(FactsRejection::BadPayload( |
| 503 | "not_after does not follow generated_at".into(), |
| 504 | )); |
| 505 | } |
| 506 | match key_role { |
| 507 | KeyRole::Founder => { |
| 508 | if not_after.is_some_and(|expires| now_unix >= expires) { |
| 509 | return Err(FactsRejection::BadPayload("not_after has expired".into())); |
| 510 | } |
| 511 | } |
| 512 | KeyRole::Automation => { |
| 513 | check_automation_window(generated_at, not_after, now_unix)?; |
| 514 | if let Some(violation) = |
| 515 | automation_provider_violation(®istry, raw_providers.as_ref()) |
| 516 | .or_else(|| automation_offering_violation(®istry.offerings)) |
| 517 | { |
| 518 | return Err(FactsRejection::OutOfScope(violation)); |
| 519 | } |
| 520 | } |
| 521 | } |
| 522 | if let Some(highest) = floor |
| 523 | && registry.revision < highest |
| 524 | { |
| 525 | return Err(FactsRejection::Rollback { |
| 526 | got: registry.revision, |
| 527 | highest_seen: highest, |
| 528 | }); |
| 529 | } |
| 530 | let sha256 = sha256_hex(&payload); |
| 531 | if outer_sha != &sha256 { |
| 532 | return Err(FactsRejection::Mismatch("sha256".into())); |
| 533 | } |
| 534 | Ok(VerifiedRegistry { |
| 535 | registry, |
| 536 | key_id, |
| 537 | key_role, |
| 538 | sha256, |
| 539 | generated_at_unix: generated_at, |
| 540 | not_after, |
| 541 | }) |
| 542 | } |
| 543 | |
| 544 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 545 | pub struct PulledProvider { |
| 546 | pub id: String, |
| 547 | pub label: String, |
| 548 | pub base_url: String, |
| 549 | pub default_model: Option<String>, |
| 550 | pub aliases: Vec<String>, |
| 551 | pub discovery: DescriptorDiscovery, |
| 552 | pub docs_url: Option<String>, |
| 553 | pub credential_url: Option<String>, |
| 554 | pub guidance: Option<String>, |
| 555 | } |
| 556 | |
| 557 | impl PulledProvider { |
| 558 | #[must_use] |
| 559 | pub fn secret_slot(&self) -> &str { |
| 560 | &self.id |
| 561 | } |
| 562 | |
| 563 | #[must_use] |
| 564 | pub fn api_key_env(&self) -> String { |
| 565 | derived_env_var(&self.id) |
| 566 | } |
| 567 | |
| 568 | #[must_use] |
| 569 | pub fn has_credential( |
| 570 | &self, |
| 571 | secret_present: impl Fn(&str) -> bool, |
| 572 | env: impl Fn(&str) -> Option<String>, |
| 573 | ) -> bool { |
| 574 | secret_present(self.secret_slot()) |
| 575 | || env(&self.api_key_env()).is_some_and(|value| !value.trim().is_empty()) |
| 576 | } |
| 577 | |
| 578 | #[must_use] |
| 579 | pub fn to_descriptor(&self) -> ProviderDescriptor { |
| 580 | ProviderDescriptor { |
| 581 | id: self.id.clone(), |
| 582 | label: self.label.clone(), |
| 583 | wire: DescriptorWire::OpenaiCompatible, |
| 584 | base_url: self.base_url.clone(), |
| 585 | api_key_env: self.api_key_env(), |
| 586 | default_model: self |
| 587 | .default_model |
| 588 | .clone() |
| 589 | .unwrap_or_else(|| self.id.clone()), |
| 590 | discovery: self.discovery, |
| 591 | docs_url: self.docs_url.clone(), |
| 592 | credential_url: self.credential_url.clone(), |
| 593 | guidance: self.guidance.clone(), |
| 594 | aliases: self.aliases.clone(), |
| 595 | } |
| 596 | } |
| 597 | } |
| 598 | |
| 599 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 600 | pub struct RefusedProvider { |
| 601 | pub id: String, |
| 602 | pub reason: String, |
| 603 | } |
| 604 | |
| 605 | #[derive(Debug, Clone, PartialEq, Eq, Default)] |
| 606 | pub struct CompiledNamingRules { |
| 607 | pub strip_prefixes: Vec<String>, |
| 608 | pub accept: Vec<String>, |
| 609 | pub aliases: BTreeMap<String, String>, |
| 610 | pub wire_slugs: BTreeMap<String, String>, |
| 611 | } |
| 612 | |
| 613 | #[derive(Debug, Clone, PartialEq, Default)] |
| 614 | pub struct CompiledRegistry { |
| 615 | pub naming: BTreeMap<String, CompiledNamingRules>, |
| 616 | pub provider_defaults: BTreeMap<String, String>, |
| 617 | pub descriptor_defaults: BTreeMap<String, String>, |
| 618 | pub intrinsic_models: BTreeMap<String, crate::catalog::reviewed::IntrinsicModel>, |
| 619 | pub catalog_offerings: Vec<CatalogOffering>, |
| 620 | pub route_offerings: Vec<ProviderModelOffering>, |
| 621 | } |
| 622 | |
| 623 | #[derive(Debug, Clone, PartialEq)] |
| 624 | pub struct AdmittedRegistry { |
| 625 | pub revision: u64, |
| 626 | pub key_id: String, |
| 627 | pub sha256: String, |
| 628 | pub not_after: Option<u64>, |
| 629 | pub registry: Registry, |
| 630 | pub providers: Vec<PulledProvider>, |
| 631 | pub builtin_rows: Vec<String>, |
| 632 | pub refused: Vec<RefusedProvider>, |
| 633 | pub compiled: CompiledRegistry, |
| 634 | } |
| 635 | |
| 636 | impl AdmittedRegistry { |
| 637 | #[must_use] |
| 638 | pub fn is_expired_at(&self, now_unix: u64) -> bool { |
| 639 | self.not_after.is_some_and(|expires| now_unix >= expires) |
| 640 | } |
| 641 | |
| 642 | #[must_use] |
| 643 | pub fn usable_providers( |
| 644 | &self, |
| 645 | secret_present: impl Fn(&str) -> bool, |
| 646 | env: impl Fn(&str) -> Option<String>, |
| 647 | ) -> Vec<&PulledProvider> { |
| 648 | self.providers |
| 649 | .iter() |
| 650 | .filter(|provider| provider.has_credential(&secret_present, &env)) |
| 651 | .collect() |
| 652 | } |
| 653 | } |
| 654 | |
| 655 | #[derive(Debug, Clone, Default)] |
| 656 | pub struct BuiltinNames { |
| 657 | pub names: BTreeSet<String>, |
| 658 | pub env_vars: BTreeSet<String>, |
| 659 | } |
| 660 | |
| 661 | impl BuiltinNames { |
| 662 | #[must_use] |
| 663 | pub fn bundled() -> Self { |
| 664 | let mut out = Self::default(); |
| 665 | for provider in crate::provider::all_providers() { |
| 666 | out.names.insert(normalize(provider.id())); |
| 667 | out.names.insert(normalize(provider.provider_config_key())); |
| 668 | out.names |
| 669 | .insert(normalize(provider.kind().secret_store_slot())); |
| 670 | out.names |
| 671 | .extend(provider.aliases().iter().map(|a| normalize(a))); |
| 672 | out.env_vars |
| 673 | .extend(provider.env_vars().iter().map(|v| v.to_string())); |
| 674 | } |
| 675 | for descriptor in crate::descriptors::bundled_provider_descriptors() { |
| 676 | out.names.insert(normalize(&descriptor.id)); |
| 677 | out.names |
| 678 | .extend(descriptor.aliases.iter().map(|a| normalize(a))); |
| 679 | out.env_vars.insert(descriptor.api_key_env.clone()); |
| 680 | } |
| 681 | for row in crate::descriptors::provider_compatibility() { |
| 682 | out.names.extend( |
| 683 | [ |
| 684 | row.id, |
| 685 | row.config_key, |
| 686 | row.base_url_config_key, |
| 687 | row.catalog_id, |
| 688 | row.catalog_source_id, |
| 689 | row.tui_wire_tag, |
| 690 | ] |
| 691 | .into_iter() |
| 692 | .chain(row.subagent_aliases.iter().copied()) |
| 693 | .chain(row.selector_aliases.iter().copied()) |
| 694 | .map(normalize), |
| 695 | ); |
| 696 | } |
| 697 | out.env_vars |
| 698 | .extend(PRODUCT_RESERVED_ENV_VARS.iter().map(|v| (*v).to_string())); |
| 699 | out |
| 700 | } |
| 701 | |
| 702 | fn reserved(&self, name: &str) -> bool { |
| 703 | self.names.contains(name) || crate::ProviderKind::parse_config_identity(name).is_some() |
| 704 | } |
| 705 | |
| 706 | fn reserved_env(&self, env_var: &str) -> bool { |
| 707 | env_var.starts_with("CODEWHALE_") |
| 708 | || env_var.starts_with("DEEPSEEK_") |
| 709 | || self.env_vars.contains(env_var) |
| 710 | } |
| 711 | } |
| 712 | |
| 713 | fn normalize(value: &str) -> String { |
| 714 | value.trim().to_ascii_lowercase().replace(['_', '.'], "-") |
| 715 | } |
| 716 | |
| 717 | #[must_use] |
| 718 | pub fn derived_env_var(id: &str) -> String { |
| 719 | format!("{}_API_KEY", id.to_ascii_uppercase().replace('-', "_")) |
| 720 | } |
| 721 | |
| 722 | fn valid_slug(value: &str) -> bool { |
| 723 | let bytes = value.as_bytes(); |
| 724 | (1..=MAX_PROVIDER_ID_CHARS).contains(&bytes.len()) |
| 725 | && bytes[0].is_ascii_lowercase() |
| 726 | && bytes |
| 727 | .iter() |
| 728 | .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || *b == b'-') |
| 729 | && !value.ends_with('-') |
| 730 | } |
| 731 | |
| 732 | fn plain(value: &str, max_chars: usize) -> bool { |
| 733 | !value.trim().is_empty() |
| 734 | && value.chars().count() <= max_chars |
| 735 | && !value.chars().any(char::is_control) |
| 736 | } |
| 737 | |
| 738 | fn valid_model_identifier(value: &str) -> bool { |
| 739 | !value.is_empty() |
| 740 | && value.len() <= 256 |
| 741 | && value.bytes().all(|byte| { |
| 742 | byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b':' | b'/' | b'-') |
| 743 | }) |
| 744 | } |
| 745 | |
| 746 | fn public_domain(host: Option<url::Host<&str>>) -> bool { |
| 747 | let Some(url::Host::Domain(domain)) = host else { |
| 748 | return false; |
| 749 | }; |
| 750 | let domain = domain.trim_end_matches('.').to_ascii_lowercase(); |
| 751 | domain.contains('.') |
| 752 | && !domain.ends_with(".localhost") |
| 753 | && !domain.ends_with(".local") |
| 754 | && !domain.ends_with(".internal") |
| 755 | } |
| 756 | |
| 757 | fn https_base_url(value: &str) -> Option<String> { |
| 758 | let parsed = url::Url::parse(value.trim()).ok()?; |
| 759 | (parsed.scheme() == "https" |
| 760 | && public_domain(parsed.host()) |
| 761 | && parsed.port().is_none() |
| 762 | && parsed.username().is_empty() |
| 763 | && parsed.password().is_none() |
| 764 | && parsed.query().is_none() |
| 765 | && parsed.fragment().is_none() |
| 766 | && value.len() <= 512) |
| 767 | .then(|| value.trim().trim_end_matches('/').to_string()) |
| 768 | } |
| 769 | |
| 770 | fn https_doc_url(value: &str) -> Option<String> { |
| 771 | let trimmed = value.trim(); |
| 772 | let parsed = url::Url::parse(trimmed).ok()?; |
| 773 | (parsed.scheme() == "https" |
| 774 | && public_domain(parsed.host()) |
| 775 | && parsed.port().is_none() |
| 776 | && parsed.username().is_empty() |
| 777 | && parsed.password().is_none() |
| 778 | && trimmed.len() <= 512 |
| 779 | && !trimmed.chars().any(char::is_control)) |
| 780 | .then(|| trimmed.to_string()) |
| 781 | } |
| 782 | |
| 783 | fn admit_row( |
| 784 | row: &RegistryProvider, |
| 785 | builtins: &BuiltinNames, |
| 786 | taken: &BTreeSet<String>, |
| 787 | ) -> Result<PulledProvider, String> { |
| 788 | let id = row.id.trim(); |
| 789 | if !valid_slug(id) { |
| 790 | return Err("id is not a lowercase slug".into()); |
| 791 | } |
| 792 | if row.kind.is_some() { |
| 793 | return Err("a provider kind needs a release".into()); |
| 794 | } |
| 795 | if !row |
| 796 | .wire_policy |
| 797 | .as_deref() |
| 798 | .is_some_and(|wire| wire == OPENAI_COMPATIBLE_WIRE) |
| 799 | { |
| 800 | return Err("only OpenAI-compatible providers can be pulled".into()); |
| 801 | } |
| 802 | if row |
| 803 | .rest |
| 804 | .get("wire") |
| 805 | .is_some_and(|v| !v.is_null() && v.as_str() != Some(OPENAI_COMPATIBLE_WIRE)) |
| 806 | { |
| 807 | return Err("only OpenAI-compatible providers can be pulled".into()); |
| 808 | } |
| 809 | let base_url = row |
| 810 | .base_url |
| 811 | .as_deref() |
| 812 | .and_then(https_base_url) |
| 813 | .ok_or_else(|| { |
| 814 | "base_url must be https on a public host name and the default port, without credentials, query or fragment".to_string() |
| 815 | })?; |
| 816 | let mut aliases = Vec::with_capacity(row.aliases.len()); |
| 817 | for alias in &row.aliases { |
| 818 | let alias = normalize(alias); |
| 819 | if !valid_slug(&alias) { |
| 820 | return Err(format!("alias {alias:?} is not a lowercase slug")); |
| 821 | } |
| 822 | if alias != id { |
| 823 | aliases.push(alias); |
| 824 | } |
| 825 | } |
| 826 | for name in std::iter::once(id).chain(aliases.iter().map(String::as_str)) { |
| 827 | if builtins.reserved(name) { |
| 828 | return Err(format!("{name:?} names a built-in provider")); |
| 829 | } |
| 830 | if taken.contains(name) { |
| 831 | return Err(format!("{name:?} is already taken")); |
| 832 | } |
| 833 | } |
| 834 | let env_var = derived_env_var(id); |
| 835 | if builtins.reserved_env(&env_var) { |
| 836 | return Err(format!("{env_var} belongs to a built-in provider")); |
| 837 | } |
| 838 | if row |
| 839 | .rest |
| 840 | .get("api_key_env") |
| 841 | .is_some_and(|v| !v.is_null() && v.as_str() != Some(env_var.as_str())) |
| 842 | { |
| 843 | return Err(format!("api_key_env is not {env_var}")); |
| 844 | } |
| 845 | if let Some(auth) = &row.auth { |
| 846 | if auth.secret_slot.as_deref().is_some_and(|slot| slot != id) { |
| 847 | return Err("secret slot must be the provider's own id".into()); |
| 848 | } |
| 849 | if let Some(other) = auth.env_vars.iter().find(|var| **var != env_var) { |
| 850 | return Err(format!("env var {other} is not {env_var}")); |
| 851 | } |
| 852 | } |
| 853 | let label = row.label.as_deref().unwrap_or(id); |
| 854 | if !plain(label, 80) { |
| 855 | return Err("label is empty, too long or not plain".into()); |
| 856 | } |
| 857 | if row |
| 858 | .default_model |
| 859 | .as_deref() |
| 860 | .is_some_and(|model| !plain(model, 200)) |
| 861 | { |
| 862 | return Err("default_model is empty, too long or not plain".into()); |
| 863 | } |
| 864 | let discovery = match row.rest.get("discovery").and_then(Value::as_str) { |
| 865 | Some("models_endpoint") => DescriptorDiscovery::ModelsEndpoint, |
| 866 | _ => DescriptorDiscovery::None, |
| 867 | }; |
| 868 | let docs_url = row |
| 869 | .rest |
| 870 | .get("docs_url") |
| 871 | .and_then(Value::as_str) |
| 872 | .and_then(https_doc_url); |
| 873 | let credential_url = row |
| 874 | .rest |
| 875 | .get("credential_url") |
| 876 | .and_then(Value::as_str) |
| 877 | .and_then(https_doc_url); |
| 878 | let guidance = row |
| 879 | .rest |
| 880 | .get("guidance") |
| 881 | .and_then(Value::as_str) |
| 882 | .filter(|g| plain(g, 300)) |
| 883 | .map(|g| g.trim().to_string()); |
| 884 | Ok(PulledProvider { |
| 885 | id: id.to_string(), |
| 886 | label: label.trim().to_string(), |
| 887 | base_url, |
| 888 | default_model: row.default_model.as_deref().map(|m| m.trim().to_string()), |
| 889 | aliases, |
| 890 | discovery, |
| 891 | docs_url, |
| 892 | credential_url, |
| 893 | guidance, |
| 894 | }) |
| 895 | } |
| 896 | |
| 897 | fn cloud_default_eligible(provider: &str) -> bool { |
| 898 | crate::ProviderKind::parse_config_identity(provider).is_some_and(|kind| { |
| 899 | kind.as_str() == provider |
| 900 | && !matches!( |
| 901 | kind, |
| 902 | crate::ProviderKind::Custom |
| 903 | | crate::ProviderKind::Ollama |
| 904 | | crate::ProviderKind::Sglang |
| 905 | | crate::ProviderKind::Vllm |
| 906 | | crate::ProviderKind::OpenaiCodex |
| 907 | | crate::ProviderKind::Antigravity |
| 908 | ) |
| 909 | }) |
| 910 | } |
| 911 | |
| 912 | fn parse_naming_block( |
| 913 | provider_id: &str, |
| 914 | block: &Map<String, Value>, |
| 915 | out: &mut CompiledNamingRules, |
| 916 | ) { |
| 917 | let builtin_verbatim = |
| 918 | crate::ProviderKind::parse_config_identity(provider_id).is_some_and(|kind| { |
| 919 | kind.as_str() == provider_id && model_rules_for(kind).ids == ModelIdsPolicy::Verbatim |
| 920 | }); |
| 921 | if builtin_verbatim { |
| 922 | return; |
| 923 | } |
| 924 | let block_verbatim = block |
| 925 | .get("ids") |
| 926 | .and_then(Value::as_str) |
| 927 | .is_some_and(|ids| ids == "verbatim"); |
| 928 | if let Some(prefixes) = block.get("strip_prefixes").and_then(Value::as_array) { |
| 929 | for item in prefixes.iter().filter_map(Value::as_str) { |
| 930 | let trimmed = item.trim(); |
| 931 | if !trimmed.is_empty() |
| 932 | && trimmed.len() <= 64 |
| 933 | && !trimmed.chars().any(char::is_control) |
| 934 | && !out |
| 935 | .strip_prefixes |
| 936 | .iter() |
| 937 | .any(|existing| existing == trimmed) |
| 938 | { |
| 939 | out.strip_prefixes.push(trimmed.to_string()); |
| 940 | } |
| 941 | } |
| 942 | } |
| 943 | if let Some(accepts) = block.get("accept").and_then(Value::as_array) { |
| 944 | for item in accepts.iter().filter_map(Value::as_str) { |
| 945 | let trimmed = item.trim(); |
| 946 | if !trimmed.is_empty() |
| 947 | && trimmed.len() <= 128 |
| 948 | && !trimmed.chars().any(char::is_control) |
| 949 | && !out.accept.iter().any(|existing| existing == trimmed) |
| 950 | { |
| 951 | out.accept.push(trimmed.to_string()); |
| 952 | } |
| 953 | } |
| 954 | } |
| 955 | if !block_verbatim && let Some(aliases) = block.get("aliases").and_then(Value::as_object) { |
| 956 | for (alias, target) in aliases { |
| 957 | let Some(target) = target.as_str() else { |
| 958 | continue; |
| 959 | }; |
| 960 | let key = normalize_model_lookup_key(alias); |
| 961 | let target = target.trim(); |
| 962 | if !key.is_empty() && valid_model_identifier(target) { |
| 963 | out.aliases.insert(key, target.to_string()); |
| 964 | } |
| 965 | } |
| 966 | } |
| 967 | if let Some(slugs) = block.get("wire_slugs").and_then(Value::as_object) { |
| 968 | for (model, slug) in slugs { |
| 969 | let Some(slug) = slug.as_str() else { |
| 970 | continue; |
| 971 | }; |
| 972 | let key = normalize_model_lookup_key(model); |
| 973 | let slug = slug.trim(); |
| 974 | if !key.is_empty() && valid_model_identifier(slug) { |
| 975 | out.wire_slugs.insert(key, slug.to_string()); |
| 976 | } |
| 977 | } |
| 978 | } |
| 979 | } |
| 980 | |
| 981 | fn fill_limit_shorthands(source: &Map<String, Value>, target: &mut Map<String, Value>) { |
| 982 | if !target.contains_key("limit") { |
| 983 | let context = source |
| 984 | .get("context_window") |
| 985 | .and_then(Value::as_u64) |
| 986 | .or_else(|| { |
| 987 | source |
| 988 | .get("limits") |
| 989 | .and_then(Value::as_object) |
| 990 | .and_then(|l| l.get("context_tokens")) |
| 991 | .and_then(Value::as_u64) |
| 992 | }); |
| 993 | let input = source |
| 994 | .get("limits") |
| 995 | .and_then(Value::as_object) |
| 996 | .and_then(|l| l.get("input_tokens")) |
| 997 | .and_then(Value::as_u64); |
| 998 | let output = source |
| 999 | .get("max_output") |
| 1000 | .and_then(Value::as_u64) |
| 1001 | .or_else(|| { |
| 1002 | source |
| 1003 | .get("limits") |
| 1004 | .and_then(Value::as_object) |
| 1005 | .and_then(|l| l.get("output_tokens")) |
| 1006 | .and_then(Value::as_u64) |
| 1007 | }); |
| 1008 | if context.is_some() || input.is_some() || output.is_some() { |
| 1009 | let mut limit = Map::new(); |
| 1010 | if let Some(v) = context { |
| 1011 | limit.insert("context".into(), Value::from(v)); |
| 1012 | } |
| 1013 | if let Some(v) = input { |
| 1014 | limit.insert("input".into(), Value::from(v)); |
| 1015 | } |
| 1016 | if let Some(v) = output { |
| 1017 | limit.insert("output".into(), Value::from(v)); |
| 1018 | } |
| 1019 | target.insert("limit".into(), Value::Object(limit)); |
| 1020 | } |
| 1021 | } |
| 1022 | if !target.contains_key("name") |
| 1023 | && let Some(display) = source.get("display_name").and_then(Value::as_str) |
| 1024 | { |
| 1025 | target.insert("name".into(), Value::String(display.to_string())); |
| 1026 | } |
| 1027 | } |
| 1028 | |
| 1029 | fn parse_registry_model( |
| 1030 | raw_model: &Value, |
| 1031 | revision: u64, |
| 1032 | ) -> Option<( |
| 1033 | String, |
| 1034 | ModelsDevModel, |
| 1035 | crate::catalog::reviewed::IntrinsicModel, |
| 1036 | )> { |
| 1037 | let obj = raw_model.as_object()?; |
| 1038 | let id = obj.get("id").and_then(Value::as_str)?.trim(); |
| 1039 | if !plain(id, 512) { |
| 1040 | return None; |
| 1041 | } |
| 1042 | let mut cat_map = match obj.get("catalog").and_then(Value::as_object) { |
| 1043 | Some(cat) => cat.clone(), |
| 1044 | None => obj.clone(), |
| 1045 | }; |
| 1046 | cat_map.insert("id".into(), Value::String(id.to_string())); |
| 1047 | fill_limit_shorthands(obj, &mut cat_map); |
| 1048 | let md_model: ModelsDevModel = serde_json::from_value(Value::Object(cat_map)).ok()?; |
| 1049 | if md_model |
| 1050 | .limit |
| 1051 | .as_ref() |
| 1052 | .is_some_and(|l| l.context == Some(0) || l.output == Some(0)) |
| 1053 | { |
| 1054 | return None; |
| 1055 | } |
| 1056 | let mut intrinsic = crate::catalog::reviewed::from_canonical(&md_model); |
| 1057 | intrinsic.source = format!("registry v{revision}"); |
| 1058 | if let Some(intr_obj) = obj.get("intrinsic").and_then(Value::as_object) { |
| 1059 | let mut intr_copy = intr_obj.clone(); |
| 1060 | intr_copy |
| 1061 | .entry("source".to_string()) |
| 1062 | .or_insert_with(|| Value::String(format!("registry v{revision}"))); |
| 1063 | if let Ok(mut parsed_intr) = serde_json::from_value::< |
| 1064 | crate::catalog::reviewed::IntrinsicModel, |
| 1065 | >(Value::Object(intr_copy)) |
| 1066 | && parsed_intr.context_window != Some(0) |
| 1067 | && parsed_intr.max_output != Some(0) |
| 1068 | && parsed_intr.generation_default != Some(0) |
| 1069 | { |
| 1070 | crate::catalog::reviewed::fill_missing(&mut parsed_intr, &intrinsic); |
| 1071 | intrinsic = parsed_intr; |
| 1072 | } |
| 1073 | } |
| 1074 | Some((id.to_ascii_lowercase(), md_model, intrinsic)) |
| 1075 | } |
| 1076 | |
| 1077 | #[derive(Debug, Deserialize, Default)] |
| 1078 | struct OfferingTransportOverlay { |
| 1079 | #[serde(default)] |
| 1080 | endpoint_key: Option<String>, |
| 1081 | #[serde(default)] |
| 1082 | canonical_model: Option<String>, |
| 1083 | #[serde(default)] |
| 1084 | default_for_provider: bool, |
| 1085 | #[serde(default)] |
| 1086 | limits: RouteLimits, |
| 1087 | #[serde(default)] |
| 1088 | capabilities: RouteCapabilities, |
| 1089 | } |
| 1090 | |
| 1091 | fn merge_canonical_into_offering(md: &mut ModelsDevProviderModel, canonical: &ModelsDevModel) { |
| 1092 | if md.name.is_none() { |
| 1093 | md.name.clone_from(&canonical.name); |
| 1094 | } |
| 1095 | if md.family.is_none() { |
| 1096 | md.family.clone_from(&canonical.family); |
| 1097 | } |
| 1098 | if md.description.is_none() { |
| 1099 | md.description.clone_from(&canonical.description); |
| 1100 | } |
| 1101 | if md.model_type.is_none() { |
| 1102 | md.model_type.clone_from(&canonical.model_type); |
| 1103 | } |
| 1104 | if md.knowledge.is_none() { |
| 1105 | md.knowledge.clone_from(&canonical.knowledge); |
| 1106 | } |
| 1107 | if md.release_date.is_none() { |
| 1108 | md.release_date.clone_from(&canonical.release_date); |
| 1109 | } |
| 1110 | if md.last_updated.is_none() { |
| 1111 | md.last_updated.clone_from(&canonical.last_updated); |
| 1112 | } |
| 1113 | md.attachment = md.attachment.or(canonical.attachment); |
| 1114 | md.reasoning = md.reasoning.or(canonical.reasoning); |
| 1115 | md.tool_call = md.tool_call.or(canonical.tool_call); |
| 1116 | md.structured_output = md.structured_output.or(canonical.structured_output); |
| 1117 | md.temperature = md.temperature.or(canonical.temperature); |
| 1118 | md.open_weights = md.open_weights.or(canonical.open_weights); |
| 1119 | if md.modalities.is_none() { |
| 1120 | md.modalities.clone_from(&canonical.modalities); |
| 1121 | } |
| 1122 | if let Some(canon_limit) = &canonical.limit { |
| 1123 | let mut limit = md.limit.clone().unwrap_or_default(); |
| 1124 | limit.context = limit.context.or(canon_limit.context); |
| 1125 | limit.input = limit.input.or(canon_limit.input); |
| 1126 | limit.output = limit.output.or(canon_limit.output); |
| 1127 | if md.limit.is_some() || limit != ModelsDevLimit::default() { |
| 1128 | md.limit = Some(limit); |
| 1129 | } |
| 1130 | } |
| 1131 | } |
| 1132 | |
| 1133 | fn merge_capability(primary: CapabilityState, fallback: CapabilityState) -> CapabilityState { |
| 1134 | if primary != CapabilityState::Unknown { |
| 1135 | primary |
| 1136 | } else { |
| 1137 | fallback |
| 1138 | } |
| 1139 | } |
| 1140 | |
| 1141 | fn compile_registry( |
| 1142 | verified: &VerifiedRegistry, |
| 1143 | admitted_providers: &[PulledProvider], |
| 1144 | ) -> CompiledRegistry { |
| 1145 | let trust = bundled_provider_trust(); |
| 1146 | let mut allowed_providers: BTreeSet<String> = trust |
| 1147 | .keys() |
| 1148 | .filter(|id| !matches!(id.as_str(), "antigravity" | "custom")) |
| 1149 | .cloned() |
| 1150 | .collect(); |
| 1151 | for pulled in admitted_providers { |
| 1152 | allowed_providers.insert(pulled.id.clone()); |
| 1153 | } |
| 1154 | |
| 1155 | let mut naming: BTreeMap<String, CompiledNamingRules> = BTreeMap::new(); |
| 1156 | let mut provider_defaults: BTreeMap<String, String> = BTreeMap::new(); |
| 1157 | let mut descriptor_defaults: BTreeMap<String, String> = BTreeMap::new(); |
| 1158 | let mut provider_headers: BTreeMap<String, (Option<String>, Option<String>)> = BTreeMap::new(); |
| 1159 | let mut provider_withheld: BTreeMap<String, String> = BTreeMap::new(); |
| 1160 | |
| 1161 | for row in &verified.registry.providers { |
| 1162 | let id = row.id.trim(); |
| 1163 | if !allowed_providers.contains(id) { |
| 1164 | continue; |
| 1165 | } |
| 1166 | if let Some(models_obj) = row.rest.get("models").and_then(Value::as_object) { |
| 1167 | let entry = naming.entry(id.to_string()).or_default(); |
| 1168 | parse_naming_block(id, models_obj, entry); |
| 1169 | } |
| 1170 | if let Some(cat_obj) = row.rest.get("catalog").and_then(Value::as_object) { |
| 1171 | let api = cat_obj |
| 1172 | .get("api") |
| 1173 | .and_then(Value::as_str) |
| 1174 | .map(str::to_string); |
| 1175 | let npm = cat_obj |
| 1176 | .get("npm") |
| 1177 | .and_then(Value::as_str) |
| 1178 | .map(str::to_string); |
| 1179 | provider_headers.insert(id.to_string(), (api, npm)); |
| 1180 | } |
| 1181 | if let Some(corrs) = row.rest.get("corrections").and_then(Value::as_array) { |
| 1182 | for corr in corrs { |
| 1183 | if let Some(reason) = corr |
| 1184 | .as_object() |
| 1185 | .and_then(|c| c.get("pricing_withheld")) |
| 1186 | .and_then(Value::as_str) |
| 1187 | .map(str::trim) |
| 1188 | .filter(|s| !s.is_empty()) |
| 1189 | { |
| 1190 | provider_withheld.insert(id.to_string(), reason.to_string()); |
| 1191 | } |
| 1192 | } |
| 1193 | } |
| 1194 | if let Some(default_model) = row.default_model.as_deref().map(str::trim).filter(|m| { |
| 1195 | valid_model_identifier(m) |
| 1196 | && !m.eq_ignore_ascii_case("auto") |
| 1197 | && !m.eq_ignore_ascii_case("unknown") |
| 1198 | }) && let Some(bundled) = trust.get(id) |
| 1199 | { |
| 1200 | if bundled.is_descriptor { |
| 1201 | if bundled.default_model.as_deref() != Some(default_model) { |
| 1202 | descriptor_defaults.insert(id.to_string(), default_model.to_string()); |
| 1203 | } |
| 1204 | } else if cloud_default_eligible(id) |
| 1205 | && bundled.default_model.as_deref() != Some(default_model) |
| 1206 | { |
| 1207 | provider_defaults.insert(id.to_string(), default_model.to_string()); |
| 1208 | } |
| 1209 | } |
| 1210 | } |
| 1211 | |
| 1212 | let mut canonical_models: BTreeMap<String, ModelsDevModel> = BTreeMap::new(); |
| 1213 | let mut intrinsic_models: BTreeMap<String, crate::catalog::reviewed::IntrinsicModel> = |
| 1214 | BTreeMap::new(); |
| 1215 | for raw_model in &verified.registry.models { |
| 1216 | if let Some((key, md_model, intrinsic)) = |
| 1217 | parse_registry_model(raw_model, verified.registry.revision) |
| 1218 | { |
| 1219 | canonical_models.insert(key.clone(), md_model); |
| 1220 | intrinsic_models.insert(key, intrinsic); |
| 1221 | } |
| 1222 | } |
| 1223 | |
| 1224 | let source = CatalogSource::CloudFacts { |
| 1225 | facts_version: verified.registry.revision, |
| 1226 | key_id: verified.key_id.clone(), |
| 1227 | fetched_at: verified.generated_at_unix.min(crate::catalog::now_unix()), |
| 1228 | valid_until: verified.not_after, |
| 1229 | }; |
| 1230 | |
| 1231 | let mut pulled_catalog_rows: BTreeMap<(String, String), CatalogOffering> = BTreeMap::new(); |
| 1232 | let mut pulled_route_rows: BTreeMap<(String, String), ProviderModelOffering> = BTreeMap::new(); |
| 1233 | let mut providers_with_pulled_default: BTreeSet<String> = BTreeSet::new(); |
| 1234 | |
| 1235 | for raw_off in &verified.registry.offerings { |
| 1236 | let Some(obj) = raw_off.as_object() else { |
| 1237 | continue; |
| 1238 | }; |
| 1239 | let Some(provider) = obj |
| 1240 | .get("provider") |
| 1241 | .and_then(Value::as_str) |
| 1242 | .map(str::trim) |
| 1243 | .filter(|p| allowed_providers.contains(*p)) |
| 1244 | else { |
| 1245 | continue; |
| 1246 | }; |
| 1247 | let Some(wire_id) = obj |
| 1248 | .get("id") |
| 1249 | .or_else(|| obj.get("wire_model_id")) |
| 1250 | .and_then(Value::as_str) |
| 1251 | .map(str::trim) |
| 1252 | .filter(|id| valid_model_identifier(id)) |
| 1253 | else { |
| 1254 | continue; |
| 1255 | }; |
| 1256 | |
| 1257 | if let Some(sel_aliases) = obj |
| 1258 | .get("selection") |
| 1259 | .and_then(Value::as_object) |
| 1260 | .and_then(|s| s.get("aliases")) |
| 1261 | .and_then(Value::as_array) |
| 1262 | { |
| 1263 | let builtin_verbatim = crate::ProviderKind::parse_config_identity(provider) |
| 1264 | .is_some_and(|kind| { |
| 1265 | kind.as_str() == provider |
| 1266 | && model_rules_for(kind).ids == ModelIdsPolicy::Verbatim |
| 1267 | }); |
| 1268 | if !builtin_verbatim { |
| 1269 | let entry = naming.entry(provider.to_string()).or_default(); |
| 1270 | for alias in sel_aliases.iter().filter_map(Value::as_str) { |
| 1271 | let key = normalize_model_lookup_key(alias); |
| 1272 | if !key.is_empty() { |
| 1273 | entry |
| 1274 | .aliases |
| 1275 | .entry(key) |
| 1276 | .or_insert_with(|| wire_id.to_string()); |
| 1277 | } |
| 1278 | } |
| 1279 | } |
| 1280 | } |
| 1281 | |
| 1282 | let transport_overlay: Option<OfferingTransportOverlay> = obj |
| 1283 | .get("transport") |
| 1284 | .and_then(|v| serde_json::from_value(v.clone()).ok()); |
| 1285 | |
| 1286 | let has_catalog_block = obj.get("catalog").is_some_and(Value::is_object); |
| 1287 | let has_flat_facts = !has_catalog_block |
| 1288 | && (obj.contains_key("limit") |
| 1289 | || obj.contains_key("limits") |
| 1290 | || obj.contains_key("context_window") |
| 1291 | || obj.contains_key("max_output") |
| 1292 | || obj.contains_key("cost") |
| 1293 | || obj.contains_key("pricing") |
| 1294 | || obj.contains_key("reasoning") |
| 1295 | || obj.contains_key("tool_call") |
| 1296 | || obj.contains_key("modalities") |
| 1297 | || obj.contains_key("name") |
| 1298 | || obj.contains_key("display_name") |
| 1299 | || obj.contains_key("default") |
| 1300 | || obj.contains_key("default_for_provider") |
| 1301 | || transport_overlay.is_none()); |
| 1302 | |
| 1303 | let mut md_model = if has_catalog_block || has_flat_facts { |
| 1304 | let mut cat_map = match obj.get("catalog").and_then(Value::as_object) { |
| 1305 | Some(cat) => cat.clone(), |
| 1306 | None => { |
| 1307 | let mut copy = obj.clone(); |
| 1308 | if copy.get("provider").is_some_and(|v| !v.is_object()) { |
| 1309 | copy.remove("provider"); |
| 1310 | } |
| 1311 | copy.remove("transport"); |
| 1312 | copy.remove("selection"); |
| 1313 | copy.remove("corrections"); |
| 1314 | copy |
| 1315 | } |
| 1316 | }; |
| 1317 | cat_map.insert("id".into(), Value::String(wire_id.to_string())); |
| 1318 | fill_limit_shorthands(obj, &mut cat_map); |
| 1319 | if !cat_map.contains_key("cost") |
| 1320 | && let Some(pricing) = obj |
| 1321 | .get("pricing") |
| 1322 | .and_then(|v| serde_json::from_value::<PricingFact>(v.clone()).ok()) |
| 1323 | { |
| 1324 | let cost = ModelsDevCost { |
| 1325 | input: pricing.input_per_m, |
| 1326 | output: pricing.output_per_m, |
| 1327 | cache_read: pricing.cache_read_per_m, |
| 1328 | ..ModelsDevCost::default() |
| 1329 | }; |
| 1330 | if let Ok(val) = serde_json::to_value(cost) { |
| 1331 | cat_map.insert("cost".into(), val); |
| 1332 | } |
| 1333 | } |
| 1334 | match serde_json::from_value::<ModelsDevProviderModel>(Value::Object(cat_map)) { |
| 1335 | Ok(parsed) => Some(parsed), |
| 1336 | Err(_) => continue, |
| 1337 | } |
| 1338 | } else { |
| 1339 | None |
| 1340 | }; |
| 1341 | |
| 1342 | let explicit_canonical = obj |
| 1343 | .get("model") |
| 1344 | .or_else(|| obj.get("canonical_model")) |
| 1345 | .and_then(Value::as_str) |
| 1346 | .map(str::trim) |
| 1347 | .filter(|s| !s.is_empty()) |
| 1348 | .map(str::to_string) |
| 1349 | .or_else(|| { |
| 1350 | transport_overlay |
| 1351 | .as_ref() |
| 1352 | .and_then(|t| t.canonical_model.as_deref()) |
| 1353 | .map(str::trim) |
| 1354 | .filter(|s| !s.is_empty()) |
| 1355 | .map(str::to_string) |
| 1356 | }) |
| 1357 | .or_else(|| { |
| 1358 | md_model |
| 1359 | .as_ref() |
| 1360 | .and_then(ModelsDevProviderModel::canonical_id) |
| 1361 | .map(str::to_string) |
| 1362 | }); |
| 1363 | |
| 1364 | if let (Some(md), Some(canon_id)) = (&mut md_model, explicit_canonical.as_deref()) |
| 1365 | && let Some(canon_row) = canonical_models.get(&canon_id.to_ascii_lowercase()) |
| 1366 | { |
| 1367 | merge_canonical_into_offering(md, canon_row); |
| 1368 | } |
| 1369 | |
| 1370 | if let Some(md) = &mut md_model { |
| 1371 | if !md.supports_text_chat() { |
| 1372 | continue; |
| 1373 | } |
| 1374 | if md |
| 1375 | .limit |
| 1376 | .as_ref() |
| 1377 | .is_some_and(|l| l.context == Some(0) || l.output == Some(0)) |
| 1378 | { |
| 1379 | continue; |
| 1380 | } |
| 1381 | if md.cost.as_ref().is_some_and(|c| c.validate().is_err()) { |
| 1382 | md.cost = None; |
| 1383 | } |
| 1384 | } |
| 1385 | |
| 1386 | if let Some(t) = &transport_overlay |
| 1387 | && (t.limits.context_tokens == Some(0) || t.limits.output_tokens == Some(0)) |
| 1388 | { |
| 1389 | continue; |
| 1390 | } |
| 1391 | |
| 1392 | let (provider_api, provider_npm) = provider_headers |
| 1393 | .get(provider) |
| 1394 | .cloned() |
| 1395 | .unwrap_or((None, None)); |
| 1396 | |
| 1397 | let endpoint_key = transport_overlay |
| 1398 | .as_ref() |
| 1399 | .and_then(|t| t.endpoint_key.as_deref()) |
| 1400 | .or_else(|| obj.get("endpoint_key").and_then(Value::as_str)) |
| 1401 | .map(str::trim) |
| 1402 | .filter(|s| !s.is_empty()) |
| 1403 | .map(str::to_string) |
| 1404 | .unwrap_or_else(|| { |
| 1405 | if provider != crate::ProviderKind::OpencodeZen.as_str() { |
| 1406 | "chat".to_string() |
| 1407 | } else if md_model |
| 1408 | .as_ref() |
| 1409 | .is_some_and(ModelsDevProviderModel::is_deprecated) |
| 1410 | { |
| 1411 | OPENCODE_ZEN_DEPRECATED_ENDPOINT_KEY.to_string() |
| 1412 | } else { |
| 1413 | opencode_zen_endpoint_key_for_npm( |
| 1414 | md_model |
| 1415 | .as_ref() |
| 1416 | .and_then(|m| m.provider.as_ref()) |
| 1417 | .and_then(|p| p.npm.as_deref()) |
| 1418 | .or(provider_npm.as_deref()), |
| 1419 | ) |
| 1420 | .to_string() |
| 1421 | } |
| 1422 | }); |
| 1423 | |
| 1424 | let default_for_provider = md_model.as_ref().is_some_and(|m| m.default_for_provider) |
| 1425 | || transport_overlay |
| 1426 | .as_ref() |
| 1427 | .is_some_and(|t| t.default_for_provider); |
| 1428 | |
| 1429 | let key = (provider.to_string(), wire_id.to_string()); |
| 1430 | |
| 1431 | let catalog_row = if let Some(md) = md_model { |
| 1432 | let mut row = CatalogOffering { |
| 1433 | provider: provider.to_string(), |
| 1434 | wire_model_id: wire_id.to_string(), |
| 1435 | canonical_model: explicit_canonical.clone(), |
| 1436 | endpoint_key: endpoint_key.clone(), |
| 1437 | default_for_provider, |
| 1438 | family: md.family, |
| 1439 | name: md.name, |
| 1440 | description: md.description, |
| 1441 | model_type: md.model_type, |
| 1442 | knowledge: md.knowledge, |
| 1443 | release_date: md.release_date, |
| 1444 | last_updated: md.last_updated, |
| 1445 | temperature: md.temperature, |
| 1446 | open_weights: md.open_weights, |
| 1447 | interleaved: md.interleaved, |
| 1448 | transport: md.provider, |
| 1449 | provider_api, |
| 1450 | provider_npm, |
| 1451 | status: md.status, |
| 1452 | experimental: md.experimental, |
| 1453 | limit: md.limit, |
| 1454 | cost: md.cost, |
| 1455 | modalities: md.modalities, |
| 1456 | attachment: md.attachment, |
| 1457 | reasoning: md.reasoning, |
| 1458 | tool_call: md.tool_call, |
| 1459 | structured_output: md.structured_output, |
| 1460 | reasoning_options: md.reasoning_options.clone().unwrap_or_default(), |
| 1461 | reasoning_options_present: md.reasoning_options.is_some(), |
| 1462 | source: source.clone(), |
| 1463 | ..CatalogOffering::default() |
| 1464 | }; |
| 1465 | let mut patches = Vec::new(); |
| 1466 | if let Some(reason) = provider_withheld.get(provider) { |
| 1467 | patches.push(ModelFact { |
| 1468 | provider: provider.to_string(), |
| 1469 | id: wire_id.to_string(), |
| 1470 | pricing_withheld: Some(reason.clone()), |
| 1471 | ..ModelFact::default() |
| 1472 | }); |
| 1473 | } |
| 1474 | if let Some(reason) = obj |
| 1475 | .get("pricing_withheld") |
| 1476 | .and_then(Value::as_str) |
| 1477 | .map(str::trim) |
| 1478 | .filter(|s| !s.is_empty()) |
| 1479 | { |
| 1480 | patches.push(ModelFact { |
| 1481 | provider: provider.to_string(), |
| 1482 | id: wire_id.to_string(), |
| 1483 | pricing_withheld: Some(reason.to_string()), |
| 1484 | ..ModelFact::default() |
| 1485 | }); |
| 1486 | } |
| 1487 | if let Some(corrs) = obj.get("corrections").and_then(Value::as_array) { |
| 1488 | for corr in corrs { |
| 1489 | if let Some(corr_obj) = corr.as_object() { |
| 1490 | let mut copy = corr_obj.clone(); |
| 1491 | copy.remove("position"); |
| 1492 | copy.remove("reason"); |
| 1493 | copy.insert("provider".into(), Value::String(provider.to_string())); |
| 1494 | copy.insert("id".into(), Value::String(wire_id.to_string())); |
| 1495 | if let Ok(fact) = serde_json::from_value::<ModelFact>(Value::Object(copy)) { |
| 1496 | patches.push(fact); |
| 1497 | } |
| 1498 | } |
| 1499 | } |
| 1500 | } |
| 1501 | if !patches.is_empty() { |
| 1502 | let mut single = BTreeMap::from([(key.clone(), row)]); |
| 1503 | super::catalog_patch::apply_patches(&mut single, &patches, &source, false); |
| 1504 | let Some(patched) = single.remove(&key) else { |
| 1505 | continue; |
| 1506 | }; |
| 1507 | row = patched; |
| 1508 | } |
| 1509 | Some(row) |
| 1510 | } else { |
| 1511 | None |
| 1512 | }; |
| 1513 | |
| 1514 | let route_row = match (&catalog_row, &transport_overlay) { |
| 1515 | (Some(cat), Some(trans)) => { |
| 1516 | let mut offering = cat.to_offering(); |
| 1517 | offering.endpoint_key.clone_from(&endpoint_key); |
| 1518 | offering.default_for_provider = default_for_provider; |
| 1519 | if let Some(canon) = &explicit_canonical { |
| 1520 | offering.canonical_model = Some(ModelId::from(canon.clone())); |
| 1521 | } |
| 1522 | if trans.limits.has_known_limit() && provider != "opencode-go" { |
| 1523 | offering.limits = RouteLimits { |
| 1524 | context_tokens: trans |
| 1525 | .limits |
| 1526 | .context_tokens |
| 1527 | .or(offering.limits.context_tokens), |
| 1528 | input_tokens: trans.limits.input_tokens.or(offering.limits.input_tokens), |
| 1529 | output_tokens: trans.limits.output_tokens.or(offering.limits.output_tokens), |
| 1530 | output_declared: offering.limits.output_declared, |
| 1531 | }; |
| 1532 | } |
| 1533 | offering.capabilities = RouteCapabilities { |
| 1534 | streaming: merge_capability( |
| 1535 | trans.capabilities.streaming, |
| 1536 | offering.capabilities.streaming, |
| 1537 | ), |
| 1538 | native_tool_calls: merge_capability( |
| 1539 | trans.capabilities.native_tool_calls, |
| 1540 | offering.capabilities.native_tool_calls, |
| 1541 | ), |
| 1542 | reasoning: merge_capability( |
| 1543 | trans.capabilities.reasoning, |
| 1544 | offering.capabilities.reasoning, |
| 1545 | ), |
| 1546 | structured_output: merge_capability( |
| 1547 | trans.capabilities.structured_output, |
| 1548 | offering.capabilities.structured_output, |
| 1549 | ), |
| 1550 | attachments: merge_capability( |
| 1551 | trans.capabilities.attachments, |
| 1552 | offering.capabilities.attachments, |
| 1553 | ), |
| 1554 | image_input: merge_capability( |
| 1555 | trans.capabilities.image_input, |
| 1556 | offering.capabilities.image_input, |
| 1557 | ), |
| 1558 | parallel_tool_calls: merge_capability( |
| 1559 | trans.capabilities.parallel_tool_calls, |
| 1560 | offering.capabilities.parallel_tool_calls, |
| 1561 | ), |
| 1562 | server_side_web_search: merge_capability( |
| 1563 | trans.capabilities.server_side_web_search, |
| 1564 | offering.capabilities.server_side_web_search, |
| 1565 | ), |
| 1566 | prompt_caching: merge_capability( |
| 1567 | trans.capabilities.prompt_caching, |
| 1568 | offering.capabilities.prompt_caching, |
| 1569 | ), |
| 1570 | files_api: merge_capability( |
| 1571 | trans.capabilities.files_api, |
| 1572 | offering.capabilities.files_api, |
| 1573 | ), |
| 1574 | }; |
| 1575 | Some(offering) |
| 1576 | } |
| 1577 | (Some(cat), None) => Some(cat.to_offering()), |
| 1578 | (None, Some(trans)) => Some(ProviderModelOffering { |
| 1579 | provider: crate::route::ProviderId::from(provider.to_string()), |
| 1580 | canonical_model: explicit_canonical.map(ModelId::from), |
| 1581 | wire_model_id: crate::route::WireModelId::from(wire_id.to_string()), |
| 1582 | endpoint_key, |
| 1583 | default_for_provider, |
| 1584 | limits: trans.limits, |
| 1585 | capabilities: trans.capabilities, |
| 1586 | pricing: crate::route::PricingSku::UnknownOrStale, |
| 1587 | }), |
| 1588 | (None, None) => None, |
| 1589 | }; |
| 1590 | |
| 1591 | if default_for_provider { |
| 1592 | providers_with_pulled_default.insert(provider.to_string()); |
| 1593 | } |
| 1594 | if let Some(cat) = catalog_row { |
| 1595 | pulled_catalog_rows.insert(key.clone(), cat); |
| 1596 | } |
| 1597 | if let Some(route) = route_row { |
| 1598 | pulled_route_rows.insert(key, route); |
| 1599 | } |
| 1600 | } |
| 1601 | |
| 1602 | let seed_catalog = crate::catalog::seed_catalog_offerings(); |
| 1603 | let mut catalog_offerings = Vec::with_capacity(seed_catalog.len() + pulled_catalog_rows.len()); |
| 1604 | for seed in seed_catalog { |
| 1605 | let key = (seed.provider.clone(), seed.wire_model_id.clone()); |
| 1606 | if let Some(pulled) = pulled_catalog_rows.remove(&key) { |
| 1607 | catalog_offerings.push(pulled); |
| 1608 | } else { |
| 1609 | let mut cloned = seed.clone(); |
| 1610 | if providers_with_pulled_default.contains(&cloned.provider) { |
| 1611 | cloned.default_for_provider = false; |
| 1612 | } |
| 1613 | catalog_offerings.push(cloned); |
| 1614 | } |
| 1615 | } |
| 1616 | catalog_offerings.extend(pulled_catalog_rows.into_values()); |
| 1617 | |
| 1618 | let seed_routes = crate::route::resolver::seed_route_offerings(); |
| 1619 | let mut route_offerings = Vec::with_capacity(seed_routes.len() + pulled_route_rows.len()); |
| 1620 | for seed in seed_routes { |
| 1621 | let key = ( |
| 1622 | seed.provider.as_str().to_string(), |
| 1623 | seed.wire_model_id.as_str().to_string(), |
| 1624 | ); |
| 1625 | if let Some(pulled) = pulled_route_rows.remove(&key) { |
| 1626 | route_offerings.push(pulled); |
| 1627 | } else { |
| 1628 | let mut cloned = seed.clone(); |
| 1629 | if providers_with_pulled_default.contains(cloned.provider.as_str()) { |
| 1630 | cloned.default_for_provider = false; |
| 1631 | } |
| 1632 | route_offerings.push(cloned); |
| 1633 | } |
| 1634 | } |
| 1635 | route_offerings.extend(pulled_route_rows.into_values()); |
| 1636 | |
| 1637 | CompiledRegistry { |
| 1638 | naming, |
| 1639 | provider_defaults, |
| 1640 | descriptor_defaults, |
| 1641 | intrinsic_models, |
| 1642 | catalog_offerings, |
| 1643 | route_offerings, |
| 1644 | } |
| 1645 | } |
| 1646 | |
| 1647 | #[must_use] |
| 1648 | pub fn admit_registry(verified: VerifiedRegistry, builtins: &BuiltinNames) -> AdmittedRegistry { |
| 1649 | let mut providers = Vec::new(); |
| 1650 | let mut builtin_rows = Vec::new(); |
| 1651 | let mut refused = Vec::new(); |
| 1652 | let mut taken = BTreeSet::new(); |
| 1653 | for row in &verified.registry.providers { |
| 1654 | let normalized = normalize(&row.id); |
| 1655 | if builtins.reserved(&normalized) { |
| 1656 | builtin_rows.push(normalized); |
| 1657 | continue; |
| 1658 | } |
| 1659 | if verified.key_role != KeyRole::Founder { |
| 1660 | refused.push(RefusedProvider { |
| 1661 | id: row.id.chars().take(64).collect(), |
| 1662 | reason: "a pulled provider requires a founder signature".into(), |
| 1663 | }); |
| 1664 | continue; |
| 1665 | } |
| 1666 | match admit_row(row, builtins, &taken) { |
| 1667 | Ok(provider) => { |
| 1668 | taken.insert(provider.id.clone()); |
| 1669 | taken.extend(provider.aliases.iter().cloned()); |
| 1670 | providers.push(provider); |
| 1671 | } |
| 1672 | Err(reason) => refused.push(RefusedProvider { |
| 1673 | id: row.id.chars().take(64).collect(), |
| 1674 | reason, |
| 1675 | }), |
| 1676 | } |
| 1677 | } |
| 1678 | let compiled = compile_registry(&verified, &providers); |
| 1679 | AdmittedRegistry { |
| 1680 | revision: verified.registry.revision, |
| 1681 | key_id: verified.key_id, |
| 1682 | sha256: verified.sha256, |
| 1683 | not_after: verified.not_after, |
| 1684 | registry: verified.registry, |
| 1685 | providers, |
| 1686 | builtin_rows, |
| 1687 | refused, |
| 1688 | compiled, |
| 1689 | } |
| 1690 | } |
| 1691 | |
| 1692 | #[cfg(test)] |
| 1693 | mod tests; |
| 1694 |