| 1 | //! Compile immutable provider metadata from its one committed data owner. |
| 2 | |
| 3 | use std::{ |
| 4 | collections::{BTreeMap, BTreeSet}, |
| 5 | env, fs, |
| 6 | path::PathBuf, |
| 7 | }; |
| 8 | |
| 9 | use serde::de::{Deserialize, Deserializer, MapAccess, SeqAccess, Visitor}; |
| 10 | use serde_json::Value; |
| 11 | |
| 12 | #[path = "src/responses_dialect_data.rs"] |
| 13 | mod responses_dialect_data; |
| 14 | |
| 15 | fn text<'a>(row: &'a Value, key: &str) -> &'a str { |
| 16 | row[key] |
| 17 | .as_str() |
| 18 | .unwrap_or_else(|| panic!("missing string {key}")) |
| 19 | } |
| 20 | |
| 21 | fn quoted(value: &str) -> String { |
| 22 | format!("{value:?}") |
| 23 | } |
| 24 | |
| 25 | fn optional(row: &Value, key: &str) -> String { |
| 26 | match row.get(key) { |
| 27 | Some(Value::String(value)) => format!("Some({})", quoted(value)), |
| 28 | Some(Value::Null) => "None".into(), |
| 29 | _ => panic!("missing or malformed optional string {key}"), |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | fn strings(row: &Value, key: &str) -> String { |
| 34 | let values = row[key] |
| 35 | .as_array() |
| 36 | .unwrap_or_else(|| panic!("missing array {key}")); |
| 37 | format!( |
| 38 | "&[{}]", |
| 39 | values |
| 40 | .iter() |
| 41 | .map(|value| quoted(value.as_str().expect("string array"))) |
| 42 | .collect::<Vec<_>>() |
| 43 | .join(", ") |
| 44 | ) |
| 45 | } |
| 46 | |
| 47 | fn credential(row: &Value) -> String { |
| 48 | let acquisition = match text(row, "acquisition") { |
| 49 | "api_key" => "ApiKey", |
| 50 | "api_key_or_oauth" => "ApiKeyOrOAuth", |
| 51 | "local_optional" => "LocalOptional", |
| 52 | "oauth" => "OAuth", |
| 53 | "configuration" => "Configuration", |
| 54 | other => panic!("unknown credential classification {other}"), |
| 55 | }; |
| 56 | format!( |
| 57 | "crate::provider::CredentialHelp {{ acquisition: crate::provider::CredentialAcquisition::{acquisition}, credential_url: {}, docs_url: {}, guidance: {} }}", |
| 58 | optional(row, "credential_url"), |
| 59 | optional(row, "docs_url"), |
| 60 | quoted(text(row, "guidance")) |
| 61 | ) |
| 62 | } |
| 63 | |
| 64 | fn wire(row: &Value) -> &'static str { |
| 65 | match text(row, "wire_policy") { |
| 66 | "chat_completions" => { |
| 67 | "crate::provider::WirePolicy::Fixed(crate::provider::WireFormat::ChatCompletions)" |
| 68 | } |
| 69 | "responses" => "crate::provider::WirePolicy::Fixed(crate::provider::WireFormat::Responses)", |
| 70 | "anthropic_messages" => { |
| 71 | "crate::provider::WirePolicy::Fixed(crate::provider::WireFormat::AnthropicMessages)" |
| 72 | } |
| 73 | "generate_content" => { |
| 74 | "crate::provider::WirePolicy::Fixed(crate::provider::WireFormat::GenerateContent)" |
| 75 | } |
| 76 | "model_aware" => "crate::provider::WirePolicy::ModelAware", |
| 77 | other => panic!("unknown wire classification {other}"), |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | fn pair_slices(map: &Value) -> String { |
| 82 | let entries = map |
| 83 | .as_object() |
| 84 | .expect("missing object map") |
| 85 | .iter() |
| 86 | .map(|(k, v)| { |
| 87 | format!( |
| 88 | "({}, {})", |
| 89 | quoted(k), |
| 90 | quoted(v.as_str().expect("string value")) |
| 91 | ) |
| 92 | }) |
| 93 | .collect::<Vec<_>>() |
| 94 | .join(", "); |
| 95 | format!("&[{entries}]") |
| 96 | } |
| 97 | |
| 98 | fn model_rules(row: &Value) -> String { |
| 99 | let rules = &row["models"]; |
| 100 | let ids = match text(rules, "ids") { |
| 101 | "strict" => "ModelIdsPolicy::Strict", |
| 102 | "roster" => "ModelIdsPolicy::Roster", |
| 103 | "catalog" => "ModelIdsPolicy::Catalog", |
| 104 | "verbatim" => "ModelIdsPolicy::Verbatim", |
| 105 | other => panic!("unknown model ids policy {other}"), |
| 106 | }; |
| 107 | format!( |
| 108 | "ModelRules {{ ids: {ids}, accept: {}, strip_prefixes: {}, aliases: {}, wire_slugs: {} }}", |
| 109 | strings(rules, "accept"), |
| 110 | strings(rules, "strip_prefixes"), |
| 111 | pair_slices(&rules["aliases"]), |
| 112 | pair_slices(&rules["wire_slugs"]), |
| 113 | ) |
| 114 | } |
| 115 | |
| 116 | struct UniqueKeys; |
| 117 | |
| 118 | impl<'de> Deserialize<'de> for UniqueKeys { |
| 119 | fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { |
| 120 | deserializer.deserialize_any(UniqueKeys) |
| 121 | } |
| 122 | } |
| 123 | |
| 124 | impl<'de> Visitor<'de> for UniqueKeys { |
| 125 | type Value = UniqueKeys; |
| 126 | |
| 127 | fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 128 | f.write_str("JSON without duplicate object keys") |
| 129 | } |
| 130 | |
| 131 | fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self, A::Error> { |
| 132 | let mut seen = BTreeSet::new(); |
| 133 | while let Some(key) = map.next_key::<String>()? { |
| 134 | if !seen.insert(key.clone()) { |
| 135 | return Err(serde::de::Error::custom(format!("duplicate key {key}"))); |
| 136 | } |
| 137 | map.next_value::<UniqueKeys>()?; |
| 138 | } |
| 139 | Ok(UniqueKeys) |
| 140 | } |
| 141 | |
| 142 | fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Self, A::Error> { |
| 143 | while seq.next_element::<UniqueKeys>()?.is_some() {} |
| 144 | Ok(UniqueKeys) |
| 145 | } |
| 146 | |
| 147 | fn visit_bool<E>(self, _: bool) -> Result<Self, E> { |
| 148 | Ok(UniqueKeys) |
| 149 | } |
| 150 | fn visit_i64<E>(self, _: i64) -> Result<Self, E> { |
| 151 | Ok(UniqueKeys) |
| 152 | } |
| 153 | fn visit_u64<E>(self, _: u64) -> Result<Self, E> { |
| 154 | Ok(UniqueKeys) |
| 155 | } |
| 156 | fn visit_f64<E>(self, _: f64) -> Result<Self, E> { |
| 157 | Ok(UniqueKeys) |
| 158 | } |
| 159 | fn visit_str<E>(self, _: &str) -> Result<Self, E> { |
| 160 | Ok(UniqueKeys) |
| 161 | } |
| 162 | fn visit_unit<E>(self) -> Result<Self, E> { |
| 163 | Ok(UniqueKeys) |
| 164 | } |
| 165 | } |
| 166 | |
| 167 | fn model_key(value: &str) -> String { |
| 168 | value.trim().to_ascii_lowercase().replace(['_', ' '], "-") |
| 169 | } |
| 170 | |
| 171 | fn glob(pattern: &[u8], value: &[u8]) -> bool { |
| 172 | match (pattern.first(), value.first()) { |
| 173 | (None, None) => true, |
| 174 | (Some(b'*'), _) => { |
| 175 | glob(&pattern[1..], value) |
| 176 | || value.first().is_some_and(|c| *c != b'/') && glob(pattern, &value[1..]) |
| 177 | } |
| 178 | (Some(p), Some(v)) if p == v => glob(&pattern[1..], &value[1..]), |
| 179 | _ => false, |
| 180 | } |
| 181 | } |
| 182 | |
| 183 | fn validate_model_rules(id: &str, rules: &Value, offerings: &BTreeMap<String, BTreeSet<String>>) { |
| 184 | let object = rules |
| 185 | .as_object() |
| 186 | .unwrap_or_else(|| panic!("{id}: models block missing")); |
| 187 | let allowed = ["ids", "accept", "strip_prefixes", "aliases", "wire_slugs"]; |
| 188 | for key in object.keys() { |
| 189 | assert!( |
| 190 | allowed.contains(&key.as_str()), |
| 191 | "{id}: unknown models field {key}" |
| 192 | ); |
| 193 | } |
| 194 | let ids = text(rules, "ids"); |
| 195 | assert!( |
| 196 | matches!(ids, "strict" | "roster" | "catalog" | "verbatim"), |
| 197 | "{id}: unknown models.ids {ids}" |
| 198 | ); |
| 199 | let accept: Vec<&str> = rules["accept"] |
| 200 | .as_array() |
| 201 | .unwrap_or_else(|| panic!("{id}: models.accept")) |
| 202 | .iter() |
| 203 | .map(|value| value.as_str().expect("accept glob")) |
| 204 | .collect(); |
| 205 | assert!( |
| 206 | ids == "strict" || accept.is_empty(), |
| 207 | "{id}: accept needs ids = strict" |
| 208 | ); |
| 209 | let own = offerings.get(id); |
| 210 | let is_offering = |model: &str| { |
| 211 | own.is_some_and(|set| { |
| 212 | set.iter() |
| 213 | .any(|offered| offered.eq_ignore_ascii_case(model)) |
| 214 | }) |
| 215 | }; |
| 216 | for table in ["aliases", "wire_slugs"] { |
| 217 | let map = rules[table] |
| 218 | .as_object() |
| 219 | .unwrap_or_else(|| panic!("{id}: models.{table}")); |
| 220 | for (key, target) in map { |
| 221 | let target = target.as_str().expect("models target"); |
| 222 | assert!( |
| 223 | *key == model_key(key) && !key.is_empty(), |
| 224 | "{id}: models.{table} key {key} is not in lookup form" |
| 225 | ); |
| 226 | assert!( |
| 227 | !target.is_empty() && target.trim() == target, |
| 228 | "{id}: models.{table} target for {key} is empty or padded" |
| 229 | ); |
| 230 | if table == "aliases" { |
| 231 | let lower = target.to_ascii_lowercase(); |
| 232 | match ids { |
| 233 | "strict" => assert!( |
| 234 | is_offering(target) |
| 235 | || accept |
| 236 | .iter() |
| 237 | .any(|pattern| glob(pattern.as_bytes(), lower.as_bytes())), |
| 238 | "{id}: alias {key} targets {target}, neither an offering nor accepted" |
| 239 | ), |
| 240 | "roster" => assert!( |
| 241 | is_offering(target), |
| 242 | "{id}: alias {key} targets {target}, which is not on the roster" |
| 243 | ), |
| 244 | "verbatim" => panic!("{id}: verbatim providers take no aliases"), |
| 245 | _ => {} |
| 246 | } |
| 247 | } |
| 248 | } |
| 249 | } |
| 250 | } |
| 251 | |
| 252 | fn main() { |
| 253 | println!("cargo:rerun-if-changed=assets/provider_descriptors.json"); |
| 254 | let file: Value = serde_json::from_str( |
| 255 | &fs::read_to_string("assets/provider_descriptors.json").expect("provider data"), |
| 256 | ) |
| 257 | .expect("provider data JSON"); |
| 258 | assert_eq!( |
| 259 | file["schema_version"].as_u64(), |
| 260 | Some(3), |
| 261 | "unsupported provider schema" |
| 262 | ); |
| 263 | let descriptor_text = |
| 264 | fs::read_to_string("assets/provider_descriptors.json").expect("provider data"); |
| 265 | serde_json::from_str::<UniqueKeys>(&descriptor_text).expect("provider data has unique keys"); |
| 266 | println!("cargo:rerun-if-changed=assets/models_dev.bundled.json"); |
| 267 | let seed: Value = serde_json::from_str( |
| 268 | &fs::read_to_string("assets/models_dev.bundled.json").expect("bundled catalog"), |
| 269 | ) |
| 270 | .expect("bundled catalog JSON"); |
| 271 | let corrections: Value = serde_json::from_str( |
| 272 | &fs::read_to_string("assets/catalog_corrections.json").expect("catalog data"), |
| 273 | ) |
| 274 | .expect("catalog data JSON"); |
| 275 | let mut offerings: BTreeMap<String, BTreeSet<String>> = BTreeMap::new(); |
| 276 | for (provider, row) in seed["providers"].as_object().expect("seed providers") { |
| 277 | for (model, offering) in row["models"].as_object().expect("seed models") { |
| 278 | let set = offerings.entry(provider.clone()).or_default(); |
| 279 | set.insert(model.clone()); |
| 280 | if let Some(wire) = offering["id"].as_str() { |
| 281 | set.insert(wire.to_string()); |
| 282 | } |
| 283 | } |
| 284 | } |
| 285 | for transport in corrections["reviewed"]["transports"] |
| 286 | .as_array() |
| 287 | .expect("reviewed transports") |
| 288 | { |
| 289 | offerings |
| 290 | .entry(text(transport, "provider").to_string()) |
| 291 | .or_default() |
| 292 | .insert(text(transport, "id").to_string()); |
| 293 | } |
| 294 | for row in file["descriptors"].as_array().expect("descriptor rows") { |
| 295 | validate_model_rules(text(row, "id"), &row["models"], &offerings); |
| 296 | } |
| 297 | validate_model_rules( |
| 298 | text(&file["legacy_tui"], "id"), |
| 299 | &file["legacy_tui"]["models"], |
| 300 | &offerings, |
| 301 | ); |
| 302 | let rows = file["providers"].as_array().expect("built-in rows"); |
| 303 | let mut ids = BTreeSet::new(); |
| 304 | let mut kinds = BTreeSet::new(); |
| 305 | let mut output = String::from("// Generated from provider_descriptors.json. Do not edit.\n"); |
| 306 | let mut selected = Vec::new(); |
| 307 | output.push_str("pub(crate) static BUILTIN_DESCRIPTORS: &[BuiltinProviderDescriptor] = &[\n"); |
| 308 | for row in rows { |
| 309 | let id = text(row, "id"); |
| 310 | let kind = text(row, "kind"); |
| 311 | assert!(!id.is_empty() && !kind.is_empty(), "empty identity"); |
| 312 | assert!(ids.insert(id), "duplicate provider id {id}"); |
| 313 | assert!(kinds.insert(kind), "duplicate provider kind {kind}"); |
| 314 | assert!( |
| 315 | kind.chars().all(|c| c.is_ascii_alphanumeric()), |
| 316 | "invalid Rust kind" |
| 317 | ); |
| 318 | validate_model_rules(id, &row["models"], &offerings); |
| 319 | let selectable = row["selectable"].as_bool().expect("selectable status"); |
| 320 | let retired = row["retired"].as_bool().expect("retired status"); |
| 321 | assert!( |
| 322 | !retired || !selectable, |
| 323 | "retired provider cannot be selectable" |
| 324 | ); |
| 325 | if kind == "Antigravity" { |
| 326 | assert!(retired && !selectable, "Antigravity remains retired"); |
| 327 | } |
| 328 | if selectable { |
| 329 | selected.push(( |
| 330 | row["selection_order"].as_u64().expect("selection order"), |
| 331 | format!("crate::ProviderKind::{kind}"), |
| 332 | )); |
| 333 | } else { |
| 334 | assert!(row["selection_order"].is_null(), "non-selectable order"); |
| 335 | } |
| 336 | output.push_str(&format!("BuiltinProviderDescriptor {{ kind: crate::ProviderKind::{kind}, id: {}, label: {}, base_url: {}, default_model: {}, env_vars: {}, aliases: {}, config_key: {}, secret_store_slot: {}, family: {}, selectable: {selectable}, retired: {retired}, wire_policy: {}, credential_help: {}, models: {} }},\n", |
| 337 | quoted(id),quoted(text(row,"label")),quoted(text(row,"base_url")),quoted(text(row,"default_model")),strings(row,"env_vars"),strings(row,"aliases"),quoted(text(row,"config_key")),quoted(text(row,"secret_store_slot")),quoted(text(row,"family")),wire(row),credential(&row["credential_help"]),model_rules(row))); |
| 338 | } |
| 339 | output.push_str("];\n"); |
| 340 | // Generated exhaustive projection makes a new/missing enum variant a |
| 341 | // compiler error, rather than a delayed registry panic. |
| 342 | output.push_str("pub(crate) const fn builtin_provider_descriptor(kind: crate::ProviderKind) -> &'static BuiltinProviderDescriptor { match kind {\n"); |
| 343 | for (index, row) in rows.iter().enumerate() { |
| 344 | output.push_str(&format!( |
| 345 | "crate::ProviderKind::{} => &BUILTIN_DESCRIPTORS[{index}],\n", |
| 346 | text(row, "kind") |
| 347 | )); |
| 348 | } |
| 349 | output.push_str("} }\n"); |
| 350 | selected.sort_by_key(|(order, _)| *order); |
| 351 | for (index, (order, _)) in selected.iter().enumerate() { |
| 352 | assert_eq!( |
| 353 | *order, |
| 354 | u64::try_from(index).expect("selection index"), |
| 355 | "selection order must be unique and contiguous" |
| 356 | ); |
| 357 | } |
| 358 | let selected: Vec<_> = selected.into_iter().map(|(_, kind)| kind).collect(); |
| 359 | output.push_str(&format!( |
| 360 | "pub(crate) const SELECTABLE_PROVIDER_KINDS: [crate::ProviderKind; {}] = [{}];\n", |
| 361 | selected.len(), |
| 362 | selected.join(", ") |
| 363 | )); |
| 364 | for row in file["descriptors"].as_array().expect("compatible rows") { |
| 365 | assert!( |
| 366 | ids.insert(text(row, "id")), |
| 367 | "descriptor shadows built-in identity" |
| 368 | ); |
| 369 | for field in ["id", "label", "base_url", "api_key_env", "default_model"] { |
| 370 | assert!(!text(row, field).is_empty(), "empty compatible-host field"); |
| 371 | } |
| 372 | assert!( |
| 373 | matches!( |
| 374 | text(row, "wire"), |
| 375 | "openai-compatible" | "anthropic-messages" |
| 376 | ), |
| 377 | "unknown compatible wire" |
| 378 | ); |
| 379 | assert!( |
| 380 | matches!( |
| 381 | text(row, "discovery"), |
| 382 | "models_endpoint" | "public_models_endpoint" | "none" |
| 383 | ), |
| 384 | "unknown discovery" |
| 385 | ); |
| 386 | if row.get("aliases").is_some() { |
| 387 | let _ = strings(row, "aliases"); |
| 388 | } |
| 389 | for field in ["docs_url", "credential_url", "guidance"] { |
| 390 | if row.get(field).is_some() { |
| 391 | let _ = optional(row, field); |
| 392 | } |
| 393 | } |
| 394 | } |
| 395 | let legacy = &file["legacy_tui"]; |
| 396 | output.push_str(&format!("/// Exact retained TUI-only compatibility metadata.\npub const LEGACY_DEEPSEEK_CN: LegacyProviderDescriptor = LegacyProviderDescriptor {{ id: {}, label: {}, base_url: {}, default_model: {}, config_key: {}, secret_store_slot: {} }};\n", |
| 397 | quoted(text(legacy,"id")),quoted(text(legacy,"label")),quoted(text(legacy,"base_url")),quoted(text(legacy,"default_model")),quoted(text(legacy,"config_key")),quoted(text(legacy,"secret_store_slot")))); |
| 398 | // Existing descriptor data owns the released presentation tags and typed |
| 399 | // table projection. A missing field or duplicate tag refuses the build. |
| 400 | let mut compatibility: Vec<_> = rows.iter().chain(std::iter::once(legacy)).collect(); |
| 401 | compatibility.sort_by_key(|row| row["tui_order"].as_u64().expect("compatibility order")); |
| 402 | let mut tags = BTreeSet::new(); |
| 403 | let mut compatibility_ids = BTreeSet::new(); |
| 404 | output.push_str("static PROVIDER_COMPATIBILITY: &[ProviderCompatibility] = &[\n"); |
| 405 | for (index, row) in compatibility.iter().enumerate() { |
| 406 | assert_eq!( |
| 407 | row["tui_order"].as_u64(), |
| 408 | Some(index as u64), |
| 409 | "compatibility order must be contiguous" |
| 410 | ); |
| 411 | let id = text(row, "id"); |
| 412 | let tag = text(row, "tui_wire_tag"); |
| 413 | assert!( |
| 414 | !tag.is_empty() && tags.insert(tag), |
| 415 | "duplicate/empty compatibility tag" |
| 416 | ); |
| 417 | assert!( |
| 418 | compatibility_ids.insert(id), |
| 419 | "duplicate compatibility identity" |
| 420 | ); |
| 421 | for field in ["catalog_id", "catalog_source_id"] { |
| 422 | assert!( |
| 423 | rows.iter() |
| 424 | .any(|primary| text(primary, "id") == text(row, field)) |
| 425 | || text(row, field) == id, |
| 426 | "unknown catalog projection" |
| 427 | ); |
| 428 | } |
| 429 | let field = text(row, "table_field"); |
| 430 | assert!( |
| 431 | field.chars().next().is_some_and(|c| c.is_ascii_lowercase()) |
| 432 | && field |
| 433 | .chars() |
| 434 | .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_'), |
| 435 | "invalid Rust table field" |
| 436 | ); |
| 437 | if let Some(key) = row.get("base_url_config_key") { |
| 438 | let key = key.as_str().expect("endpoint table key"); |
| 439 | assert!( |
| 440 | rows.iter().any(|row| text(row, "config_key") == key), |
| 441 | "unknown endpoint config table" |
| 442 | ); |
| 443 | } |
| 444 | output.push_str(&format!("ProviderCompatibility {{ kind: crate::ProviderKind::{}, id: {}, tui_wire_tag: {}, config_key: {}, base_url_config_key: {}, catalog_id: {}, catalog_source_id: {}, subagent_aliases: {}, selector_aliases: {}, label: {}, base_url: {}, default_model: {} }},\n", text(row,"kind"),quoted(id),quoted(tag),quoted(text(row,"config_key")),quoted(row.get("base_url_config_key").map_or_else(|| text(row,"config_key"), |value| value.as_str().expect("endpoint table key"))),quoted(text(row,"catalog_id")),quoted(text(row,"catalog_source_id")),strings(row,"subagent_aliases"),strings(row,"selector_aliases"),quoted(text(row,"label")),quoted(text(row,"base_url")),quoted(text(row,"default_model")))); |
| 445 | } |
| 446 | output.push_str("];\n"); |
| 447 | // Expand against the consumer's released typed configuration struct. The |
| 448 | // field inventory remains generated; custom/legacy provenance is admitted |
| 449 | // by that consumer before this pure projection is called. |
| 450 | output.push_str("#[macro_export]\nmacro_rules! provider_config_table {\n"); |
| 451 | for (mode, borrow) in [("read", "&"), ("write", "&mut ")] { |
| 452 | output.push_str(&format!( |
| 453 | "(@{mode} $providers:expr, $id:expr) => {{ match $id {{\n" |
| 454 | )); |
| 455 | for row in &compatibility { |
| 456 | if text(row, "kind") != "Custom" { |
| 457 | output.push_str(&format!( |
| 458 | "{} => Some({borrow}$providers.{}),\n", |
| 459 | quoted(text(row, "id")), |
| 460 | text(row, "table_field") |
| 461 | )); |
| 462 | } |
| 463 | } |
| 464 | output.push_str("_ => None } };\n"); |
| 465 | } |
| 466 | output.push_str("}\n"); |
| 467 | let mut public_orders = BTreeSet::new(); |
| 468 | for row in rows { |
| 469 | if row["retired"] == false && text(row, "kind") != "Custom" { |
| 470 | let order = row["web"]["order"] |
| 471 | .as_u64() |
| 472 | .expect("public presentation order"); |
| 473 | assert!( |
| 474 | public_orders.insert(order), |
| 475 | "duplicate public presentation order" |
| 476 | ); |
| 477 | assert!( |
| 478 | row["web"].get("variant").is_none(), |
| 479 | "retired enum presentation identity" |
| 480 | ); |
| 481 | } |
| 482 | } |
| 483 | assert!( |
| 484 | public_orders |
| 485 | .iter() |
| 486 | .enumerate() |
| 487 | .all(|(index, order)| *order == index as u64), |
| 488 | "public order must be contiguous" |
| 489 | ); |
| 490 | for (key, row) in file["route_credential_help"] |
| 491 | .as_object() |
| 492 | .expect("route credential help") |
| 493 | .iter() |
| 494 | .collect::<BTreeMap<_, _>>() |
| 495 | { |
| 496 | let name = key.replace('-', "_").to_ascii_uppercase(); |
| 497 | assert!( |
| 498 | name.chars().all(|c| c.is_ascii_uppercase() || c == '_'), |
| 499 | "invalid route help key" |
| 500 | ); |
| 501 | output.push_str(&format!( |
| 502 | "pub(crate) const {name}_CREDENTIAL_HELP: crate::provider::CredentialHelp = {};\n", |
| 503 | credential(row) |
| 504 | )); |
| 505 | } |
| 506 | let mut defaults = String::from("// Generated data projections. Do not edit.\n"); |
| 507 | let refs = file["constant_refs"] |
| 508 | .as_object() |
| 509 | .expect("constant references"); |
| 510 | let constants = file["compatibility_constants"] |
| 511 | .as_object() |
| 512 | .expect("compatibility constants"); |
| 513 | for (name, value) in refs.iter().collect::<BTreeMap<_, _>>() { |
| 514 | assert!(!constants.contains_key(name), "duplicate constant"); |
| 515 | assert!( |
| 516 | name.chars() |
| 517 | .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_'), |
| 518 | "invalid constant name" |
| 519 | ); |
| 520 | let row = rows |
| 521 | .iter() |
| 522 | .find(|row| row["id"] == value["provider"]) |
| 523 | .expect("constant row"); |
| 524 | let field = text(value, "field"); |
| 525 | assert!( |
| 526 | matches!(field, "base_url" | "default_model" | "credential_url"), |
| 527 | "unknown constant field" |
| 528 | ); |
| 529 | let source = if field == "credential_url" { |
| 530 | &row["credential_help"][field] |
| 531 | } else { |
| 532 | &row[field] |
| 533 | }; |
| 534 | defaults.push_str(&format!( |
| 535 | "/// Projection of the committed provider descriptor.\npub const {name}: &str = {};\n", |
| 536 | quoted(source.as_str().expect("constant field string")) |
| 537 | )); |
| 538 | } |
| 539 | for (name, value) in constants.iter().collect::<BTreeMap<_, _>>() { |
| 540 | assert!( |
| 541 | name.chars() |
| 542 | .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_'), |
| 543 | "invalid constant name" |
| 544 | ); |
| 545 | defaults.push_str(&format!( |
| 546 | "/// Retained data-owned compatibility seed.\npub const {name}: &str = {};\n", |
| 547 | quoted(value.as_str().expect("compatibility string")) |
| 548 | )); |
| 549 | } |
| 550 | let directory = PathBuf::from(env::var_os("OUT_DIR").expect("build output")); |
| 551 | fs::write(directory.join("provider_descriptors.rs"), output).expect("write descriptors"); |
| 552 | fs::write(directory.join("provider_defaults.rs"), defaults).expect("write defaults"); |
| 553 | |
| 554 | println!("cargo:rerun-if-changed=assets/catalog_corrections.json"); |
| 555 | let catalog: Value = serde_json::from_str( |
| 556 | &fs::read_to_string("assets/catalog_corrections.json").expect("catalog data"), |
| 557 | ) |
| 558 | .expect("catalog JSON"); |
| 559 | let reviewed = &catalog["reviewed"]; |
| 560 | assert!(!text(reviewed, "revision").is_empty(), "reviewed revision"); |
| 561 | let mut catalog_constants = |
| 562 | String::from("// Generated from catalog_corrections.json.reviewed. Do not edit.\n"); |
| 563 | for (name, value) in reviewed["constants"] |
| 564 | .as_object() |
| 565 | .expect("model constants") |
| 566 | .iter() |
| 567 | .collect::<BTreeMap<_, _>>() |
| 568 | { |
| 569 | assert!( |
| 570 | name.chars() |
| 571 | .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_'), |
| 572 | "invalid catalog constant" |
| 573 | ); |
| 574 | catalog_constants.push_str(&format!( |
| 575 | "pub const {name}: &str = {};\n", |
| 576 | quoted(value.as_str().expect("model constant string")) |
| 577 | )); |
| 578 | } |
| 579 | for (name, reference) in reviewed["numeric_refs"] |
| 580 | .as_object() |
| 581 | .expect("numeric contract references") |
| 582 | { |
| 583 | assert!( |
| 584 | name.chars() |
| 585 | .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_'), |
| 586 | "invalid numeric contract name" |
| 587 | ); |
| 588 | let field = text(reference, "field"); |
| 589 | assert!( |
| 590 | matches!( |
| 591 | field, |
| 592 | "context_window" | "max_output" | "generation_default" |
| 593 | ), |
| 594 | "unknown numeric contract field" |
| 595 | ); |
| 596 | let value = reviewed["intrinsic"][text(reference, "model")][field] |
| 597 | .as_u64() |
| 598 | .expect("numeric intrinsic fact"); |
| 599 | assert!( |
| 600 | value > 0 && value <= u64::from(u32::MAX), |
| 601 | "numeric intrinsic bound" |
| 602 | ); |
| 603 | catalog_constants.push_str(&format!("pub const {name}: u32 = {value};\n")); |
| 604 | } |
| 605 | for (name, value) in reviewed["groups"] |
| 606 | .as_object() |
| 607 | .expect("model rosters") |
| 608 | .iter() |
| 609 | .collect::<BTreeMap<_, _>>() |
| 610 | { |
| 611 | assert!( |
| 612 | name.chars() |
| 613 | .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_'), |
| 614 | "invalid catalog group" |
| 615 | ); |
| 616 | let values = value |
| 617 | .as_array() |
| 618 | .expect("model roster array") |
| 619 | .iter() |
| 620 | .map(|v| quoted(v.as_str().expect("model roster string"))) |
| 621 | .collect::<Vec<_>>() |
| 622 | .join(", "); |
| 623 | catalog_constants.push_str(&format!("pub const {name}: &[&str] = &[{values}];\n")); |
| 624 | } |
| 625 | for (name, provider, endpoint) in [ |
| 626 | ( |
| 627 | "OPENCODE_ZEN_RESPONSES_MODELS", |
| 628 | "opencode-zen", |
| 629 | Some("responses"), |
| 630 | ), |
| 631 | ( |
| 632 | "OPENCODE_ZEN_MESSAGES_MODELS", |
| 633 | "opencode-zen", |
| 634 | Some("messages"), |
| 635 | ), |
| 636 | ("OPENCODE_ZEN_CHAT_MODELS", "opencode-zen", Some("chat")), |
| 637 | ("OPENCODE_GO_MODELS", "opencode-go", None), |
| 638 | ("MODELSTUDIO_TEXT_MODELS", "modelstudio-token-plan", None), |
| 639 | ("CODEWHALE_FALLBACK_MODELS", "codewhale", None), |
| 640 | ] { |
| 641 | let values = reviewed["transports"] |
| 642 | .as_array() |
| 643 | .expect("transport rows") |
| 644 | .iter() |
| 645 | .filter(|row| { |
| 646 | row["provider"] == provider |
| 647 | && endpoint.is_none_or(|endpoint| row["endpoint_key"] == endpoint) |
| 648 | }) |
| 649 | .map(|row| quoted(text(row, "id"))) |
| 650 | .collect::<Vec<_>>() |
| 651 | .join(", "); |
| 652 | catalog_constants.push_str(&format!("pub const {name}: &[&str] = &[{values}];\n")); |
| 653 | } |
| 654 | // Alias/completion entries refer to existing defaults or model groups; |
| 655 | // the source owner never repeats a descriptor-owned default value. |
| 656 | let mut values = BTreeMap::new(); |
| 657 | for (name, value) in constants { |
| 658 | values.insert(name.as_str(), value.as_str().expect("compatibility value")); |
| 659 | } |
| 660 | for (name, reference) in refs { |
| 661 | let provider = rows |
| 662 | .iter() |
| 663 | .find(|row| row["id"] == reference["provider"]) |
| 664 | .expect("constant provider"); |
| 665 | let field = text(reference, "field"); |
| 666 | let value = if field == "credential_url" { |
| 667 | &provider["credential_help"][field] |
| 668 | } else { |
| 669 | &provider[field] |
| 670 | }; |
| 671 | values.insert(name.as_str(), value.as_str().expect("constant value")); |
| 672 | } |
| 673 | for (name, value) in reviewed["constants"] |
| 674 | .as_object() |
| 675 | .expect("catalog constants") |
| 676 | { |
| 677 | assert!( |
| 678 | values |
| 679 | .insert(name, value.as_str().expect("catalog value")) |
| 680 | .is_none(), |
| 681 | "duplicate data constant" |
| 682 | ); |
| 683 | } |
| 684 | let resolve = |value: &str| -> String { |
| 685 | match value.strip_prefix('$') { |
| 686 | Some(name) => values |
| 687 | .get(name) |
| 688 | .unwrap_or_else(|| panic!("missing constant {name}")) |
| 689 | .to_string(), |
| 690 | None => value.to_string(), |
| 691 | } |
| 692 | }; |
| 693 | let mut groups: BTreeMap<String, Vec<String>> = reviewed["groups"] |
| 694 | .as_object() |
| 695 | .expect("groups") |
| 696 | .iter() |
| 697 | .map(|(name, value)| { |
| 698 | ( |
| 699 | name.clone(), |
| 700 | value |
| 701 | .as_array() |
| 702 | .expect("group") |
| 703 | .iter() |
| 704 | .map(|v| resolve(v.as_str().expect("group entry"))) |
| 705 | .collect(), |
| 706 | ) |
| 707 | }) |
| 708 | .collect(); |
| 709 | for (name, provider, endpoint) in [ |
| 710 | ( |
| 711 | "OPENCODE_ZEN_RESPONSES_MODELS", |
| 712 | "opencode-zen", |
| 713 | Some("responses"), |
| 714 | ), |
| 715 | ( |
| 716 | "OPENCODE_ZEN_MESSAGES_MODELS", |
| 717 | "opencode-zen", |
| 718 | Some("messages"), |
| 719 | ), |
| 720 | ("OPENCODE_ZEN_CHAT_MODELS", "opencode-zen", Some("chat")), |
| 721 | ("OPENCODE_GO_MODELS", "opencode-go", None), |
| 722 | ("MODELSTUDIO_TEXT_MODELS", "modelstudio-token-plan", None), |
| 723 | ("CODEWHALE_FALLBACK_MODELS", "codewhale", None), |
| 724 | ] { |
| 725 | groups.insert( |
| 726 | name.into(), |
| 727 | reviewed["transports"] |
| 728 | .as_array() |
| 729 | .expect("transports") |
| 730 | .iter() |
| 731 | .filter(|row| { |
| 732 | row["provider"] == provider |
| 733 | && endpoint.is_none_or(|endpoint| row["endpoint_key"] == endpoint) |
| 734 | }) |
| 735 | .map(|row| text(row, "id").to_string()) |
| 736 | .collect(), |
| 737 | ); |
| 738 | } |
| 739 | catalog_constants.push_str("#[must_use]\npub fn completion_names(provider: &str) -> &'static [&'static str] { match provider {\n"); |
| 740 | for (provider, roster) in reviewed["completion_rosters"] |
| 741 | .as_object() |
| 742 | .expect("completion rosters") |
| 743 | { |
| 744 | assert!( |
| 745 | rows.iter().any(|row| row["id"] == provider.as_str()) || provider == text(legacy, "id"), |
| 746 | "unknown completion provider" |
| 747 | ); |
| 748 | let mut list = Vec::new(); |
| 749 | for entry in roster.as_array().expect("completion roster") { |
| 750 | let entry = entry.as_str().expect("completion entry"); |
| 751 | if let Some(group) = entry.strip_prefix('@') { |
| 752 | list.extend( |
| 753 | groups |
| 754 | .get(group) |
| 755 | .unwrap_or_else(|| panic!("missing group {group}")) |
| 756 | .iter() |
| 757 | .cloned(), |
| 758 | ); |
| 759 | } else { |
| 760 | list.push(resolve(entry)); |
| 761 | } |
| 762 | } |
| 763 | // Zen's logical default can be an alias of a documented row. Preserve |
| 764 | // its original stable, case-insensitive first-occurrence projection. |
| 765 | if provider == "opencode-zen" { |
| 766 | let mut seen = BTreeSet::new(); |
| 767 | list.retain(|id| seen.insert(id.to_ascii_lowercase())); |
| 768 | } |
| 769 | assert!( |
| 770 | !matches!(provider.as_str(), "antigravity" | "custom") || list.is_empty(), |
| 771 | "retired/custom completion rows" |
| 772 | ); |
| 773 | catalog_constants.push_str(&format!( |
| 774 | "{} => &[{}],\n", |
| 775 | quoted(provider), |
| 776 | list.iter() |
| 777 | .map(|v| quoted(v)) |
| 778 | .collect::<Vec<_>>() |
| 779 | .join(", ") |
| 780 | )); |
| 781 | } |
| 782 | catalog_constants.push_str("_ => &[], } }\n"); |
| 783 | fs::write(directory.join("catalog_constants.rs"), catalog_constants) |
| 784 | .expect("write catalog constants"); |
| 785 | write_responses_dialects(); |
| 786 | } |
| 787 | |
| 788 | fn write_responses_dialects() { |
| 789 | println!("cargo:rerun-if-changed=assets/responses_dialects.json"); |
| 790 | println!("cargo:rerun-if-changed=src/responses_dialect_data.rs"); |
| 791 | let raw = fs::read_to_string("assets/responses_dialects.json").expect("responses dialects"); |
| 792 | let doc = responses_dialect_data::parse(&raw) |
| 793 | .unwrap_or_else(|err| panic!("responses dialects: {err}")); |
| 794 | let directory = PathBuf::from(env::var_os("OUT_DIR").expect("OUT_DIR")); |
| 795 | fs::write( |
| 796 | directory.join("responses_dialects.rs"), |
| 797 | responses_dialect_data::codegen(&doc), |
| 798 | ) |
| 799 | .expect("write responses dialects"); |
| 800 | } |
| 801 |