| 1 | //! Built-in provider metadata. |
| 2 | //! |
| 3 | //! This module is a metadata foundation for collapsing provider drift over |
| 4 | //! time. It deliberately does not mutate request bodies or choose fallback |
| 5 | //! providers; `ConfigToml::resolve_runtime_options` now mints the executable |
| 6 | //! route through `RouteResolver` (Phase 1). Auth/key resolution stays here. |
| 7 | |
| 8 | use crate::ProviderKind; |
| 9 | pub use crate::descriptors::defaults::{ |
| 10 | CODEWHALE_API_BASE_ENV, CODEWHALE_API_KEY_URL, KIMI_CODE_MEMBERSHIP_PLAN_CONSOLE_URL, |
| 11 | OLLAMA_CLOUD_API_KEY_URL, OLLAMA_CLOUD_BASE_URL, OPENAI_DEFAULT_MODEL, |
| 12 | }; |
| 13 | use crate::descriptors::{self, BuiltinProviderDescriptor}; |
| 14 | use std::sync::OnceLock; |
| 15 | |
| 16 | /// Wire protocol spoken by a provider. |
| 17 | #[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] |
| 18 | #[serde(rename_all = "snake_case")] |
| 19 | pub enum WireFormat { |
| 20 | /// OpenAI-compatible `/v1/chat/completions` style payloads. |
| 21 | ChatCompletions, |
| 22 | /// OpenAI Responses API (`/responses`). |
| 23 | Responses, |
| 24 | /// Native Anthropic Messages API (`/v1/messages`). |
| 25 | AnthropicMessages, |
| 26 | GenerateContent, |
| 27 | } |
| 28 | |
| 29 | /// How a user obtains or supplies credentials for a built-in provider. |
| 30 | /// |
| 31 | /// Keeping this typed prevents API-key onboarding from accidentally describing |
| 32 | /// a local runtime, OAuth-only route, or user-defined endpoint as though it had |
| 33 | /// a vendor key console. |
| 34 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 35 | pub enum CredentialAcquisition { |
| 36 | /// A provider-issued API key or access token. |
| 37 | ApiKey, |
| 38 | /// Either a provider-issued API key or the provider's supported OAuth path. |
| 39 | ApiKeyOrOAuth, |
| 40 | /// A self-hosted route that is keyless by default but can be configured with auth. |
| 41 | LocalOptional, |
| 42 | /// An OAuth-only route; Codewhale does not collect an API key for it. |
| 43 | OAuth, |
| 44 | /// A user-defined route whose credential source belongs in configuration. |
| 45 | Configuration, |
| 46 | } |
| 47 | |
| 48 | impl CredentialAcquisition { |
| 49 | /// Stable machine-readable label for diagnostics. |
| 50 | #[must_use] |
| 51 | pub const fn as_str(self) -> &'static str { |
| 52 | match self { |
| 53 | Self::ApiKey => "api_key", |
| 54 | Self::ApiKeyOrOAuth => "api_key_or_oauth", |
| 55 | Self::LocalOptional => "local_optional", |
| 56 | Self::OAuth => "oauth", |
| 57 | Self::Configuration => "configuration", |
| 58 | } |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | /// How a provider selects its request wire format. |
| 63 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 64 | pub enum WirePolicy { |
| 65 | /// Every model served by the provider uses the same wire format. |
| 66 | Fixed(WireFormat), |
| 67 | /// The provider catalog selects a wire format per model/endpoint. |
| 68 | ModelAware, |
| 69 | } |
| 70 | |
| 71 | impl WirePolicy { |
| 72 | /// Return the fixed format, or `None` for model-aware providers. |
| 73 | #[must_use] |
| 74 | pub const fn fixed(self) -> Option<WireFormat> { |
| 75 | match self { |
| 76 | Self::Fixed(format) => Some(format), |
| 77 | Self::ModelAware => None, |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | /// Resolve a concrete format from an offering endpoint key. |
| 82 | #[must_use] |
| 83 | pub fn resolve(self, endpoint_key: &str) -> Option<WireFormat> { |
| 84 | if let Self::Fixed(format) = self { |
| 85 | return Some(format); |
| 86 | } |
| 87 | |
| 88 | match endpoint_key.trim().to_ascii_lowercase().as_str() { |
| 89 | "chat" | "chat_completions" | "chat-completions" => Some(WireFormat::ChatCompletions), |
| 90 | "responses" => Some(WireFormat::Responses), |
| 91 | "messages" | "anthropic_messages" | "anthropic-messages" => { |
| 92 | Some(WireFormat::AnthropicMessages) |
| 93 | } |
| 94 | "generate-content" | "generate_content" | "generatecontent" | "gemini" => { |
| 95 | Some(WireFormat::GenerateContent) |
| 96 | } |
| 97 | _ => None, |
| 98 | } |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | /// Canonical, non-secret help for configuring one provider. |
| 103 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 104 | pub struct CredentialHelp { |
| 105 | pub acquisition: CredentialAcquisition, |
| 106 | /// Stable provider-owned page for creating or locating credentials. |
| 107 | /// |
| 108 | /// `None` is deliberate for local, OAuth-only, and user-defined routes; UI |
| 109 | /// callers must show [`Self::guidance`] instead of guessing a URL. |
| 110 | pub credential_url: Option<&'static str>, |
| 111 | /// Provider-owned documentation when the repository already has a stable link. |
| 112 | pub docs_url: Option<&'static str>, |
| 113 | /// Concise fallback or qualification for non-key and mixed-auth routes. |
| 114 | pub guidance: &'static str, |
| 115 | } |
| 116 | |
| 117 | /// Resolve the Codewhale API base URL from the environment. |
| 118 | /// |
| 119 | /// Returns `None` when the variable is unset, empty, or names an origin this |
| 120 | /// route refuses to send a `cwc_key_…` bearer to. A bearer token has no replay |
| 121 | /// protection, so cleartext is allowed only on loopback — the same rule the |
| 122 | /// account control plane applies to `CODEWHALE_CLOUD_API_BASE`. |
| 123 | #[must_use] |
| 124 | pub fn codewhale_api_base_from_env() -> Option<String> { |
| 125 | let raw = std::env::var(CODEWHALE_API_BASE_ENV).ok()?; |
| 126 | codewhale_api_base(&raw) |
| 127 | } |
| 128 | |
| 129 | /// Validate one candidate Codewhale API base URL. See [`codewhale_api_base_from_env`]. |
| 130 | #[must_use] |
| 131 | pub fn codewhale_api_base(raw: &str) -> Option<String> { |
| 132 | let trimmed = raw.trim().trim_end_matches('/'); |
| 133 | if trimmed.is_empty() { |
| 134 | return None; |
| 135 | } |
| 136 | let (scheme, host, has_credentials) = crate::device_code::url_scheme_and_host(trimmed).ok()?; |
| 137 | if has_credentials { |
| 138 | return None; |
| 139 | } |
| 140 | let allowed = |
| 141 | scheme == "https" || (scheme == "http" && crate::device_code::is_loopback_host(&host)); |
| 142 | allowed.then(|| trimmed.to_string()) |
| 143 | } |
| 144 | |
| 145 | /// Static metadata for a built-in model provider. |
| 146 | pub trait Provider: Send + Sync { |
| 147 | /// Provider enum variant represented by this entry. |
| 148 | fn kind(&self) -> ProviderKind; |
| 149 | |
| 150 | /// Canonical provider identifier. |
| 151 | fn id(&self) -> &'static str { |
| 152 | self.kind().as_str() |
| 153 | } |
| 154 | |
| 155 | /// Human-readable provider label for UIs and diagnostics. |
| 156 | fn display_name(&self) -> &'static str; |
| 157 | |
| 158 | /// Default base URL used when no config/env/CLI override is present. |
| 159 | fn default_base_url(&self) -> &'static str; |
| 160 | |
| 161 | /// Default model used when no config/env/CLI override is present. |
| 162 | fn default_model(&self) -> &'static str; |
| 163 | |
| 164 | /// Environment variable candidates used for this provider's API key. |
| 165 | fn env_vars(&self) -> &'static [&'static str]; |
| 166 | |
| 167 | /// TOML table key under `[providers.<key>]`. |
| 168 | fn provider_config_key(&self) -> &'static str; |
| 169 | |
| 170 | /// Alternate names accepted during provider resolution. |
| 171 | fn aliases(&self) -> &'static [&'static str] { |
| 172 | &[] |
| 173 | } |
| 174 | |
| 175 | /// Policy used to select the request wire format. |
| 176 | fn wire_policy(&self) -> WirePolicy { |
| 177 | WirePolicy::Fixed(WireFormat::ChatCompletions) |
| 178 | } |
| 179 | |
| 180 | /// Credential acquisition metadata shared by onboarding, setup, diagnostics, |
| 181 | /// and provider-help surfaces. |
| 182 | fn credential_help(&self) -> CredentialHelp { |
| 183 | credential_help(self.kind()) |
| 184 | } |
| 185 | } |
| 186 | |
| 187 | /// Return the canonical credential-acquisition metadata for a provider kind. |
| 188 | /// |
| 189 | /// URLs here are provider-owned links already documented in this repository. |
| 190 | /// If no stable vendor credential page is known, the URL remains absent and the |
| 191 | /// guidance explains the supported local, OAuth, or configuration path. |
| 192 | /// This is provider-level fallback metadata: callers that know a concrete base |
| 193 | /// URL must use [`credential_help_for_route`] so route-owned credentials do not |
| 194 | /// inherit a default endpoint's console. |
| 195 | #[must_use] |
| 196 | pub const fn credential_help(kind: ProviderKind) -> CredentialHelp { |
| 197 | descriptors::builtin_provider_descriptor(kind).credential_help |
| 198 | } |
| 199 | |
| 200 | fn is_exact_https_route(base_url: &str, expected_authority: &str, expected_path: &str) -> bool { |
| 201 | // URL schemes and host names are ASCII case-insensitive; paths are not. |
| 202 | // Do not lowercase the whole URL here: a differently-cased path is a |
| 203 | // neighboring route, not the official endpoint. Keep this intentionally |
| 204 | // dependency-free because provider metadata is used by low-level config |
| 205 | // callers that should not need URL parsing machinery just for this guard. |
| 206 | let trimmed = base_url.trim(); |
| 207 | let normalized = trimmed.strip_suffix('/').unwrap_or(trimmed); |
| 208 | let Some((scheme, authority_and_path)) = normalized.split_once("://") else { |
| 209 | return false; |
| 210 | }; |
| 211 | let Some((authority, path)) = authority_and_path.split_once('/') else { |
| 212 | return false; |
| 213 | }; |
| 214 | |
| 215 | scheme.eq_ignore_ascii_case("https") |
| 216 | && authority.eq_ignore_ascii_case(expected_authority) |
| 217 | && path == expected_path |
| 218 | } |
| 219 | |
| 220 | /// Whether a configured route is exactly the official Kimi Code endpoint. |
| 221 | /// |
| 222 | /// A trailing slash is insignificant, but neighboring Kimi-hosted paths must |
| 223 | /// not inherit membership-plan credentials merely because they share a host. |
| 224 | #[must_use] |
| 225 | pub fn is_exact_kimi_code_route(kind: ProviderKind, base_url: &str) -> bool { |
| 226 | if kind != ProviderKind::Moonshot { |
| 227 | return false; |
| 228 | } |
| 229 | |
| 230 | is_exact_https_route(base_url, "api.kimi.com", "coding/v1") |
| 231 | } |
| 232 | |
| 233 | /// Whether a configured Ollama route is exactly the hosted OpenAI-compatible |
| 234 | /// endpoint. |
| 235 | /// |
| 236 | /// Local Ollama remains keyless. Neighboring paths, HTTP downgrades, and |
| 237 | /// lookalike hosts remain custom routes so they cannot inherit an Ollama Cloud |
| 238 | /// credential or durable secret-store slot. |
| 239 | #[must_use] |
| 240 | pub fn is_exact_ollama_cloud_route(kind: ProviderKind, base_url: &str) -> bool { |
| 241 | matches!(kind, ProviderKind::Ollama | ProviderKind::OllamaCloud) |
| 242 | && is_exact_https_route(base_url, "ollama.com", "v1") |
| 243 | } |
| 244 | |
| 245 | /// In-memory compatibility classifier for the released route-sensitive shape. |
| 246 | /// |
| 247 | /// Only the old `ollama` identity at the exact hosted endpoint migrates. This |
| 248 | /// deliberately rejects neighboring paths, HTTP downgrades, and lookalike |
| 249 | /// hosts so no local/custom route can consume Ollama Cloud credentials. |
| 250 | #[must_use] |
| 251 | pub fn migrates_legacy_ollama_cloud_route(kind: ProviderKind, base_url: &str) -> bool { |
| 252 | kind == ProviderKind::Ollama && is_exact_ollama_cloud_route(kind, base_url) |
| 253 | } |
| 254 | |
| 255 | /// Whether a configured route is exactly Moonshot's direct API endpoint. |
| 256 | /// |
| 257 | /// Direct K3 owns a different reasoning-control dialect from the Kimi Code |
| 258 | /// membership endpoint. Keep this route guard exact so custom gateways and |
| 259 | /// neighboring Moonshot paths do not inherit direct-K3 wire semantics. |
| 260 | #[must_use] |
| 261 | pub fn is_exact_moonshot_platform_route(kind: ProviderKind, base_url: &str) -> bool { |
| 262 | kind == ProviderKind::Moonshot |
| 263 | && (is_exact_https_route(base_url, "api.moonshot.ai", "v1") |
| 264 | || is_exact_https_route(base_url, "api.moonshot.cn", "v1")) |
| 265 | } |
| 266 | |
| 267 | /// Whether a configured route is exactly xAI's first-party OpenAI-compatible |
| 268 | /// API endpoint. |
| 269 | /// |
| 270 | /// Grok-specific request fields must not leak to a custom compatible gateway |
| 271 | /// merely because the operator selected the `xai` provider identity. |
| 272 | #[must_use] |
| 273 | pub fn is_exact_xai_platform_route(kind: ProviderKind, base_url: &str) -> bool { |
| 274 | kind == ProviderKind::Xai && is_exact_https_route(base_url, "api.x.ai", "v1") |
| 275 | } |
| 276 | |
| 277 | /// Whether a configured route is one of Z.ai's exact first-party Chat |
| 278 | /// Completions endpoints. |
| 279 | /// |
| 280 | /// Z.ai-only request fields must not leak to compatible gateways merely |
| 281 | /// because they expose the same model id. Both api.z.ai and open.bigmodel.cn |
| 282 | /// products (Coding Plan and general platform) are first-party and share the |
| 283 | /// `thinking` / `reasoning_effort` dialect. Neighboring paths — including |
| 284 | /// BigModel's `/preview` — remain distinct, mirroring the web-search and |
| 285 | /// official-endpoint families. |
| 286 | #[must_use] |
| 287 | pub fn is_exact_zai_chat_route(kind: ProviderKind, base_url: &str) -> bool { |
| 288 | kind == ProviderKind::Zai |
| 289 | && (is_exact_https_route(base_url, "api.z.ai", "api/coding/paas/v4") |
| 290 | || is_exact_https_route(base_url, "api.z.ai", "api/paas/v4") |
| 291 | || is_exact_https_route(base_url, "open.bigmodel.cn", "api/coding/paas/v4") |
| 292 | || is_exact_https_route(base_url, "open.bigmodel.cn", "api/paas/v4")) |
| 293 | } |
| 294 | |
| 295 | /// Whether a configured route is one of MiniMax's exact first-party OpenAI |
| 296 | /// Chat Completions endpoints. |
| 297 | /// |
| 298 | /// This deliberately excludes the `/anthropic` routes: those use the native |
| 299 | /// Messages adapter and do not share Chat Completions token-limit fields. |
| 300 | #[must_use] |
| 301 | pub fn is_exact_minimax_chat_route(kind: ProviderKind, base_url: &str) -> bool { |
| 302 | kind == ProviderKind::Minimax |
| 303 | && (is_exact_https_route(base_url, "api.minimax.io", "v1") |
| 304 | || is_exact_https_route(base_url, "api.minimaxi.com", "v1")) |
| 305 | } |
| 306 | |
| 307 | /// Whether a configured route is one of MiniMax's exact first-party |
| 308 | /// Anthropic-compatible Messages endpoints. |
| 309 | /// |
| 310 | /// M3 exposes only adaptive/disabled thinking on these routes; it does not |
| 311 | /// expose distinct effort tiers. Keep the guard exact so a compatible gateway |
| 312 | /// cannot inherit first-party effective-state claims from its provider label. |
| 313 | #[must_use] |
| 314 | pub fn is_exact_minimax_anthropic_route(kind: ProviderKind, base_url: &str) -> bool { |
| 315 | kind == ProviderKind::MinimaxAnthropic |
| 316 | && (is_exact_https_route(base_url, "api.minimax.io", "anthropic") |
| 317 | || is_exact_https_route(base_url, "api.minimaxi.com", "anthropic")) |
| 318 | } |
| 319 | |
| 320 | /// Whether a configured route is exactly CSDN 星图's official OpenAI-compatible |
| 321 | /// platform endpoint. |
| 322 | /// |
| 323 | /// Coding Plan keys and general marketplace keys share this one endpoint, so |
| 324 | /// the URL proves neither product — only that the route is first-party. |
| 325 | /// Neighboring paths, HTTP downgrades, and lookalike hosts must not inherit |
| 326 | /// CSDN billing or wire semantics. |
| 327 | #[must_use] |
| 328 | pub fn is_exact_csdn_platform_route(kind: ProviderKind, base_url: &str) -> bool { |
| 329 | kind == ProviderKind::Csdn && is_exact_https_route(base_url, "ai.csdn.net", "api/model/v1") |
| 330 | } |
| 331 | |
| 332 | /// Return credential help for one concrete provider route. |
| 333 | /// |
| 334 | /// This protects non-UI callers such as diagnostics and command surfaces from |
| 335 | /// presenting Moonshot's direct API console for a Kimi Code membership-plan |
| 336 | /// endpoint. It performs no discovery, credential lookup, or network I/O. |
| 337 | #[must_use] |
| 338 | pub fn credential_help_for_route(kind: ProviderKind, base_url: &str) -> CredentialHelp { |
| 339 | if is_exact_ollama_cloud_route(kind, base_url) { |
| 340 | return descriptors::OLLAMA_CLOUD_CREDENTIAL_HELP; |
| 341 | } |
| 342 | if is_exact_kimi_code_route(kind, base_url) { |
| 343 | return descriptors::KIMI_CODE_CREDENTIAL_HELP; |
| 344 | } |
| 345 | credential_help(kind) |
| 346 | } |
| 347 | |
| 348 | impl Provider for BuiltinProviderDescriptor { |
| 349 | fn kind(&self) -> ProviderKind { |
| 350 | self.kind |
| 351 | } |
| 352 | fn id(&self) -> &'static str { |
| 353 | self.id |
| 354 | } |
| 355 | fn display_name(&self) -> &'static str { |
| 356 | self.label |
| 357 | } |
| 358 | fn default_base_url(&self) -> &'static str { |
| 359 | self.base_url |
| 360 | } |
| 361 | fn default_model(&self) -> &'static str { |
| 362 | self.default_model |
| 363 | } |
| 364 | fn env_vars(&self) -> &'static [&'static str] { |
| 365 | self.env_vars |
| 366 | } |
| 367 | fn provider_config_key(&self) -> &'static str { |
| 368 | self.config_key |
| 369 | } |
| 370 | fn aliases(&self) -> &'static [&'static str] { |
| 371 | self.aliases |
| 372 | } |
| 373 | fn wire_policy(&self) -> WirePolicy { |
| 374 | self.wire_policy |
| 375 | } |
| 376 | fn credential_help(&self) -> CredentialHelp { |
| 377 | self.credential_help |
| 378 | } |
| 379 | } |
| 380 | |
| 381 | static PROVIDER_REGISTRY: OnceLock<Vec<&'static dyn Provider>> = OnceLock::new(); |
| 382 | |
| 383 | /// Return all built-in and legacy provider metadata entries. |
| 384 | /// |
| 385 | /// The full registry retains legacy entries needed to read old configuration. |
| 386 | /// It is intentionally NOT a user-facing provider list; for browsing/picker |
| 387 | /// surfaces use [`providers_sorted_for_display`]. |
| 388 | #[must_use] |
| 389 | pub fn all_providers() -> &'static [&'static dyn Provider] { |
| 390 | PROVIDER_REGISTRY |
| 391 | .get_or_init(|| { |
| 392 | descriptors::BUILTIN_DESCRIPTORS |
| 393 | .iter() |
| 394 | .map(|row| row as &dyn Provider) |
| 395 | .collect() |
| 396 | }) |
| 397 | .as_slice() |
| 398 | } |
| 399 | |
| 400 | /// Return all built-in providers ordered for user-facing display. |
| 401 | /// |
| 402 | /// Providers are sorted alphabetically (case-insensitively) by |
| 403 | /// [`Provider::display_name`] so model/provider browsing surfaces present a |
| 404 | /// neutral, predictable list rather than leading with whichever provider |
| 405 | /// happens to sit first in [`ProviderKind::ALL`] (historically DeepSeek). The |
| 406 | /// ordering policy intentionally differs from internal parsing/default order: |
| 407 | /// |
| 408 | /// - [`all_providers`] — full compatibility registry for internal identity |
| 409 | /// matching, including legacy entries. |
| 410 | /// - [`ProviderKind::ALL`] — stable selectable catalog order. Do not reorder. |
| 411 | /// - [`providers_sorted_for_display`] — neutral alphabetical order for UI |
| 412 | /// browsing, with legacy tombstones omitted. DeepSeek stays present and |
| 413 | /// searchable but is not hard-coded first; a caller may still highlight/pin |
| 414 | /// the active provider separately. |
| 415 | /// |
| 416 | /// Returns an owned `Vec` because the sorted order is computed, not static. |
| 417 | #[must_use] |
| 418 | pub fn providers_sorted_for_display() -> Vec<&'static dyn Provider> { |
| 419 | let mut providers: Vec<_> = all_providers() |
| 420 | .iter() |
| 421 | .copied() |
| 422 | .filter(|provider| !descriptors::builtin_provider_descriptor(provider.kind()).retired) |
| 423 | .collect(); |
| 424 | providers.sort_by(|a, b| { |
| 425 | a.display_name() |
| 426 | .to_ascii_lowercase() |
| 427 | .cmp(&b.display_name().to_ascii_lowercase()) |
| 428 | }); |
| 429 | providers |
| 430 | } |
| 431 | |
| 432 | /// Find a provider by canonical id only. |
| 433 | #[must_use] |
| 434 | pub fn lookup_provider(id: &str) -> Option<&'static dyn Provider> { |
| 435 | let id = id.trim(); |
| 436 | all_providers() |
| 437 | .iter() |
| 438 | .copied() |
| 439 | .find(|provider| provider.id() == id) |
| 440 | } |
| 441 | |
| 442 | /// Resolve a provider by canonical id or supported legacy alias. |
| 443 | #[must_use] |
| 444 | pub fn resolve_provider(id_or_alias: &str) -> Option<&'static dyn Provider> { |
| 445 | ProviderKind::parse(id_or_alias).map(provider_for_kind) |
| 446 | } |
| 447 | |
| 448 | /// Return metadata for a known provider kind. |
| 449 | #[must_use] |
| 450 | pub fn provider_for_kind(kind: ProviderKind) -> &'static dyn Provider { |
| 451 | descriptors::builtin_provider_descriptor(kind) |
| 452 | } |
| 453 | |
| 454 | /// Whether a per-config `wire` dialect string names the Anthropic Messages |
| 455 | /// endpoint. Canonical parse shared by the tui wire-format/capability readers |
| 456 | /// and the route resolver's `RouteRequest::wire_override`, so one alias list |
| 457 | /// cannot drift from another. |
| 458 | #[must_use] |
| 459 | pub fn wire_dialect_prefers_anthropic(wire: Option<&str>) -> bool { |
| 460 | let Some(raw) = wire.map(str::trim).filter(|value| !value.is_empty()) else { |
| 461 | return false; |
| 462 | }; |
| 463 | let normalized = raw.to_ascii_lowercase().replace(['_', ' '], "-"); |
| 464 | matches!( |
| 465 | normalized.as_str(), |
| 466 | "anthropic" |
| 467 | | "anthropic-messages" |
| 468 | | "messages" |
| 469 | | "claude" |
| 470 | | "anthropic-compatible" |
| 471 | | "anthropic-compat" |
| 472 | ) |
| 473 | } |
| 474 | |
| 475 | /// Whether a per-config `wire` dialect string names the OpenAI Responses |
| 476 | /// endpoint. See [`wire_dialect_prefers_anthropic`] for the sharing contract. |
| 477 | #[must_use] |
| 478 | pub fn wire_dialect_prefers_responses(wire: Option<&str>) -> bool { |
| 479 | let Some(raw) = wire.map(str::trim).filter(|value| !value.is_empty()) else { |
| 480 | return false; |
| 481 | }; |
| 482 | let normalized = raw.to_ascii_lowercase().replace(['_', ' '], "-"); |
| 483 | matches!( |
| 484 | normalized.as_str(), |
| 485 | "responses" |
| 486 | | "responses-api" |
| 487 | | "openai-responses" |
| 488 | | "openai-responses-api" |
| 489 | | "response" |
| 490 | | "response-api" |
| 491 | | "openai-responses-compat" |
| 492 | | "responses-compat" |
| 493 | ) |
| 494 | } |
| 495 | |
| 496 | /// The wire override a per-config `wire` dialect asks for: `Some(Responses)` / |
| 497 | /// `Some(AnthropicMessages)` when the string names that endpoint, `None` for |
| 498 | /// `chat` / absent / unrecognized values (the static descriptor policy |
| 499 | /// applies). The resolver honors the override only for `ProviderKind::Custom`, |
| 500 | /// and every other consumer gates the same way, so the warning below can only |
| 501 | /// fire for a custom table — `table` names it in the log, since several |
| 502 | /// tables can coexist and the typo must be locatable. A non-empty |
| 503 | /// unrecognized value is most likely a typo of the one string that switches |
| 504 | /// the endpoint's protocol, so it is logged before degrading to the default |
| 505 | /// policy — the parse stays total and forward-compatible. |
| 506 | pub fn wire_dialect_prefers_generate_content(wire: Option<&str>) -> bool { |
| 507 | let Some(raw) = wire.map(str::trim).filter(|value| !value.is_empty()) else { |
| 508 | return false; |
| 509 | }; |
| 510 | let normalized = raw.to_ascii_lowercase().replace(['_', ' '], "-"); |
| 511 | matches!( |
| 512 | normalized.as_str(), |
| 513 | "generate-content" | "generatecontent" | "gemini" | "google-generate-content" |
| 514 | ) |
| 515 | } |
| 516 | |
| 517 | #[must_use] |
| 518 | pub fn wire_dialect_override(table: &str, wire: Option<&str>) -> Option<WireFormat> { |
| 519 | if wire_dialect_prefers_responses(wire) { |
| 520 | Some(WireFormat::Responses) |
| 521 | } else if wire_dialect_prefers_anthropic(wire) { |
| 522 | Some(WireFormat::AnthropicMessages) |
| 523 | } else if wire_dialect_prefers_generate_content(wire) { |
| 524 | Some(WireFormat::GenerateContent) |
| 525 | } else { |
| 526 | if let Some(raw) = wire.map(str::trim).filter(|value| !value.is_empty()) { |
| 527 | let normalized = raw.to_ascii_lowercase().replace(['_', ' '], "-"); |
| 528 | if !matches!( |
| 529 | normalized.as_str(), |
| 530 | "chat" | "chat-completions" | "openai" | "openai-chat" | "openai-chat-completions" |
| 531 | ) { |
| 532 | tracing::warn!( |
| 533 | table = %table, |
| 534 | dialect = %raw, |
| 535 | "unrecognized custom-provider wire dialect; using the default Chat Completions policy" |
| 536 | ); |
| 537 | } |
| 538 | } |
| 539 | None |
| 540 | } |
| 541 | } |
| 542 | |
| 543 | /// The explicit Responses profile a custom table may request. |
| 544 | /// |
| 545 | /// An empty value selects nothing, so an existing `wire = "responses"` table |
| 546 | /// keeps the default profile. A set value is rejected unless this is a custom |
| 547 | /// provider whose wire dialect is Responses and the id is on the custom |
| 548 | /// allowlist. Built-in profiles stay on their route bindings. |
| 549 | pub fn responses_profile_override( |
| 550 | kind: crate::ProviderKind, |
| 551 | table: &str, |
| 552 | wire: Option<&str>, |
| 553 | profile: Option<&str>, |
| 554 | ) -> Result<Option<String>, String> { |
| 555 | let Some(profile) = profile.map(str::trim).filter(|value| !value.is_empty()) else { |
| 556 | return Ok(None); |
| 557 | }; |
| 558 | if kind != crate::ProviderKind::Custom { |
| 559 | return Err(format!("provider {table} cannot set responses_profile")); |
| 560 | } |
| 561 | if !wire_dialect_prefers_responses(wire) { |
| 562 | return Err(format!( |
| 563 | "provider {table} responses_profile `{profile}` requires wire = \"responses\"" |
| 564 | )); |
| 565 | } |
| 566 | crate::responses_dialect::accept_custom_responses_profile(profile) |
| 567 | .map_err(|err| format!("provider {table}: {err}"))?; |
| 568 | Ok(Some(profile.to_string())) |
| 569 | } |
| 570 | |
| 571 | #[cfg(test)] |
| 572 | mod tests { |
| 573 | use super::*; |
| 574 | use crate::descriptors::defaults::*; |
| 575 | |
| 576 | #[test] |
| 577 | fn responses_profile_override_rejects_the_wrong_wire_and_identity() { |
| 578 | assert_eq!( |
| 579 | responses_profile_override( |
| 580 | crate::ProviderKind::Custom, |
| 581 | "gateway", |
| 582 | Some("responses"), |
| 583 | None |
| 584 | ) |
| 585 | .expect("absent"), |
| 586 | None |
| 587 | ); |
| 588 | assert_eq!( |
| 589 | responses_profile_override( |
| 590 | crate::ProviderKind::Custom, |
| 591 | "gateway", |
| 592 | Some("responses"), |
| 593 | Some(" standard "), |
| 594 | ) |
| 595 | .expect("standard"), |
| 596 | Some("standard".to_string()) |
| 597 | ); |
| 598 | for (kind, wire, profile, needle) in [ |
| 599 | ( |
| 600 | crate::ProviderKind::Openai, |
| 601 | Some("responses"), |
| 602 | Some("standard"), |
| 603 | "cannot set", |
| 604 | ), |
| 605 | ( |
| 606 | crate::ProviderKind::Custom, |
| 607 | Some("chat"), |
| 608 | Some("standard"), |
| 609 | "requires wire", |
| 610 | ), |
| 611 | ( |
| 612 | crate::ProviderKind::Custom, |
| 613 | Some("anthropic"), |
| 614 | Some("standard"), |
| 615 | "requires wire", |
| 616 | ), |
| 617 | ( |
| 618 | crate::ProviderKind::Custom, |
| 619 | Some("responses"), |
| 620 | Some("codex"), |
| 621 | "allowed: standard", |
| 622 | ), |
| 623 | ( |
| 624 | crate::ProviderKind::Custom, |
| 625 | Some("responses"), |
| 626 | Some("missing"), |
| 627 | "unknown responses profile", |
| 628 | ), |
| 629 | ] { |
| 630 | let error = responses_profile_override(kind, "gateway", wire, profile) |
| 631 | .expect_err("rejected profile"); |
| 632 | assert!(error.contains(needle), "{error}"); |
| 633 | assert!(error.contains("gateway"), "{error}"); |
| 634 | } |
| 635 | } |
| 636 | |
| 637 | #[test] |
| 638 | fn wire_dialect_override_parses_the_canonical_alias_sets() { |
| 639 | // The exact alias sets are the cross-crate contract: the tui route |
| 640 | // layer, the ambient client, the capability reporter, and the route |
| 641 | // resolver all resolve dialects through these two lists. |
| 642 | for dialect in [ |
| 643 | "responses", |
| 644 | "responses-api", |
| 645 | "openai-responses", |
| 646 | "openai-responses-api", |
| 647 | "response", |
| 648 | "response-api", |
| 649 | "openai-responses-compat", |
| 650 | "responses-compat", |
| 651 | ] { |
| 652 | assert_eq!( |
| 653 | wire_dialect_override("test", Some(dialect)), |
| 654 | Some(WireFormat::Responses), |
| 655 | "{dialect} must parse as the Responses dialect" |
| 656 | ); |
| 657 | } |
| 658 | for dialect in [ |
| 659 | "anthropic", |
| 660 | "anthropic-messages", |
| 661 | "messages", |
| 662 | "claude", |
| 663 | "anthropic-compatible", |
| 664 | "anthropic-compat", |
| 665 | ] { |
| 666 | assert_eq!( |
| 667 | wire_dialect_override("test", Some(dialect)), |
| 668 | Some(WireFormat::AnthropicMessages), |
| 669 | "{dialect} must parse as the Anthropic Messages dialect" |
| 670 | ); |
| 671 | } |
| 672 | } |
| 673 | |
| 674 | #[test] |
| 675 | fn wire_dialect_override_normalizes_case_whitespace_and_separators() { |
| 676 | for dialect in ["OpenAI_Responses", " responses-api ", "ANTHROPIC COMPAT"] { |
| 677 | let parsed = wire_dialect_override("test", Some(dialect)) |
| 678 | .unwrap_or_else(|| panic!("{dialect} must parse")); |
| 679 | assert_ne!( |
| 680 | parsed, |
| 681 | WireFormat::ChatCompletions, |
| 682 | "{dialect} must not degrade to the default policy" |
| 683 | ); |
| 684 | } |
| 685 | } |
| 686 | |
| 687 | #[test] |
| 688 | fn wire_dialect_override_defaults_chat_and_degrades_unknowns() { |
| 689 | assert_eq!(wire_dialect_override("test", None), None); |
| 690 | assert_eq!(wire_dialect_override("test", Some("")), None); |
| 691 | for chat in [ |
| 692 | "chat", |
| 693 | "chat-completions", |
| 694 | "openai", |
| 695 | "openai-chat", |
| 696 | "openai-chat-completions", |
| 697 | ] { |
| 698 | assert_eq!( |
| 699 | wire_dialect_override("test", Some(chat)), |
| 700 | None, |
| 701 | "an explicit chat dialect keeps the default policy" |
| 702 | ); |
| 703 | } |
| 704 | // A typo must not accidentally select a protocol; the static |
| 705 | // descriptor policy applies and the warn names the table. |
| 706 | assert_eq!(wire_dialect_override("my_table", Some("respones")), None); |
| 707 | } |
| 708 | |
| 709 | #[test] |
| 710 | fn credential_help_covers_every_provider_without_guessing_non_key_urls() { |
| 711 | for provider in all_providers() { |
| 712 | let help = provider.credential_help(); |
| 713 | assert!( |
| 714 | !help.guidance.trim().is_empty(), |
| 715 | "{} credential guidance must not be empty", |
| 716 | provider.id() |
| 717 | ); |
| 718 | |
| 719 | match help.acquisition { |
| 720 | CredentialAcquisition::ApiKey | CredentialAcquisition::ApiKeyOrOAuth => { |
| 721 | assert!( |
| 722 | help.credential_url.is_some(), |
| 723 | "{} needs a stable provider-owned credential link", |
| 724 | provider.id() |
| 725 | ); |
| 726 | } |
| 727 | CredentialAcquisition::LocalOptional |
| 728 | | CredentialAcquisition::OAuth |
| 729 | | CredentialAcquisition::Configuration => assert!( |
| 730 | help.credential_url.is_none(), |
| 731 | "{} must explain its non-key route instead of inventing a credential link", |
| 732 | provider.id() |
| 733 | ), |
| 734 | } |
| 735 | } |
| 736 | } |
| 737 | |
| 738 | #[test] |
| 739 | fn kimi_credential_help_uses_the_durable_api_key_console_only() { |
| 740 | let help = provider_for_kind(ProviderKind::Moonshot).credential_help(); |
| 741 | |
| 742 | assert_eq!(help.acquisition, CredentialAcquisition::ApiKey); |
| 743 | assert_eq!( |
| 744 | help.credential_url, |
| 745 | Some("https://platform.kimi.ai/console/api-keys") |
| 746 | ); |
| 747 | assert_eq!( |
| 748 | help.docs_url, |
| 749 | Some("https://platform.kimi.ai/docs/overview") |
| 750 | ); |
| 751 | assert!(help.guidance.contains("create and copy an API key")); |
| 752 | assert!(help.guidance.contains("OAuth is not available")); |
| 753 | } |
| 754 | |
| 755 | #[test] |
| 756 | fn kimi_code_route_credential_help_is_distinct_from_direct_moonshot() { |
| 757 | let direct = credential_help_for_route(ProviderKind::Moonshot, DEFAULT_MOONSHOT_BASE_URL); |
| 758 | let kimi_code = |
| 759 | credential_help_for_route(ProviderKind::Moonshot, "https://api.kimi.com/coding/v1/"); |
| 760 | |
| 761 | assert_eq!( |
| 762 | direct.credential_url, |
| 763 | Some("https://platform.kimi.ai/console/api-keys") |
| 764 | ); |
| 765 | assert_eq!( |
| 766 | kimi_code.credential_url, |
| 767 | Some(KIMI_CODE_MEMBERSHIP_PLAN_CONSOLE_URL) |
| 768 | ); |
| 769 | assert_eq!(kimi_code.docs_url, None); |
| 770 | assert!(kimi_code.guidance.contains("membership-plan API key")); |
| 771 | assert!( |
| 772 | kimi_code |
| 773 | .guidance |
| 774 | .contains("does not import Kimi CLI credentials") |
| 775 | ); |
| 776 | assert!(!is_exact_kimi_code_route( |
| 777 | ProviderKind::Moonshot, |
| 778 | "https://api.kimi.com/coding/v1/preview" |
| 779 | )); |
| 780 | |
| 781 | // Scheme and hostname casing are insignificant, but the endpoint |
| 782 | // path is a route identifier and must remain exact. |
| 783 | assert!(is_exact_kimi_code_route( |
| 784 | ProviderKind::Moonshot, |
| 785 | "HTTPS://API.KIMI.COM/coding/v1/" |
| 786 | )); |
| 787 | for neighboring_route in [ |
| 788 | "https://api.kimi.com/CODING/v1", |
| 789 | "https://api.kimi.com/coding/V1", |
| 790 | "http://api.kimi.com/coding/v1", |
| 791 | "https://api.kimi.com:443/coding/v1", |
| 792 | "https://api.kimi.com/coding/v1?preview=1", |
| 793 | "https://api.kimi.com/coding/v1#fragment", |
| 794 | "https://api.kimi.com/coding/v1//", |
| 795 | ] { |
| 796 | assert!( |
| 797 | !is_exact_kimi_code_route(ProviderKind::Moonshot, neighboring_route), |
| 798 | "{neighboring_route} must not inherit Kimi Code membership semantics" |
| 799 | ); |
| 800 | } |
| 801 | } |
| 802 | |
| 803 | #[test] |
| 804 | fn ollama_cloud_route_is_exact_and_requires_its_own_key() { |
| 805 | for base_url in [ |
| 806 | OLLAMA_CLOUD_BASE_URL, |
| 807 | "https://ollama.com/v1/", |
| 808 | " HTTPS://OLLAMA.COM/v1/ ", |
| 809 | ] { |
| 810 | for provider in [ProviderKind::Ollama, ProviderKind::OllamaCloud] { |
| 811 | assert!(is_exact_ollama_cloud_route(provider, base_url)); |
| 812 | let help = credential_help_for_route(provider, base_url); |
| 813 | assert_eq!(help.acquisition, CredentialAcquisition::ApiKey); |
| 814 | assert_eq!(help.credential_url, Some(OLLAMA_CLOUD_API_KEY_URL)); |
| 815 | assert_eq!( |
| 816 | help.docs_url, |
| 817 | Some("https://docs.ollama.com/api/authentication") |
| 818 | ); |
| 819 | assert!(help.guidance.contains("OLLAMA_CLOUD_API_KEY")); |
| 820 | assert!(help.guidance.contains("OLLAMA_API_KEY")); |
| 821 | } |
| 822 | } |
| 823 | |
| 824 | for base_url in [ |
| 825 | "http://ollama.com/v1", |
| 826 | "https://ollama.com", |
| 827 | "https://ollama.com/api", |
| 828 | "https://ollama.com/v1/preview", |
| 829 | "https://ollama.com.evil.example/v1", |
| 830 | "https://api.ollama.com/v1", |
| 831 | "https://ollama.com/v1?tenant=other", |
| 832 | ] { |
| 833 | assert!(!is_exact_ollama_cloud_route(ProviderKind::Ollama, base_url)); |
| 834 | assert!(!is_exact_ollama_cloud_route( |
| 835 | ProviderKind::OllamaCloud, |
| 836 | base_url |
| 837 | )); |
| 838 | } |
| 839 | assert!(!is_exact_ollama_cloud_route( |
| 840 | ProviderKind::Openai, |
| 841 | OLLAMA_CLOUD_BASE_URL |
| 842 | )); |
| 843 | |
| 844 | let local = credential_help_for_route(ProviderKind::Ollama, DEFAULT_OLLAMA_BASE_URL); |
| 845 | assert_eq!(local.acquisition, CredentialAcquisition::LocalOptional); |
| 846 | assert_eq!(local.credential_url, None); |
| 847 | assert!(local.guidance.contains("keyless by default")); |
| 848 | } |
| 849 | |
| 850 | #[test] |
| 851 | fn direct_moonshot_route_matching_is_exact() { |
| 852 | for route in ["HTTPS://API.MOONSHOT.AI/v1/", "HTTPS://API.MOONSHOT.CN/v1/"] { |
| 853 | assert!(is_exact_moonshot_platform_route( |
| 854 | ProviderKind::Moonshot, |
| 855 | route |
| 856 | )); |
| 857 | } |
| 858 | for neighboring_route in [ |
| 859 | "https://api.moonshot.ai/V1", |
| 860 | "http://api.moonshot.ai/v1", |
| 861 | "https://api.moonshot.ai:443/v1", |
| 862 | "https://api.moonshot.ai/v1?preview=1", |
| 863 | "https://api.moonshot.ai/v1#fragment", |
| 864 | "https://api.moonshot.ai/v1//", |
| 865 | "https://api.moonshot.ai/v1/chat/completions", |
| 866 | "https://api.moonshot.cn/v1/chat/completions", |
| 867 | "https://api.kimi.com/coding/v1", |
| 868 | ] { |
| 869 | assert!( |
| 870 | !is_exact_moonshot_platform_route(ProviderKind::Moonshot, neighboring_route), |
| 871 | "{neighboring_route} must not inherit direct Moonshot semantics" |
| 872 | ); |
| 873 | } |
| 874 | assert!(!is_exact_moonshot_platform_route( |
| 875 | ProviderKind::Openai, |
| 876 | crate::MOONSHOT_CN_BASE_URL |
| 877 | )); |
| 878 | } |
| 879 | |
| 880 | #[test] |
| 881 | fn direct_xai_route_matching_is_exact() { |
| 882 | assert!(is_exact_xai_platform_route( |
| 883 | ProviderKind::Xai, |
| 884 | "HTTPS://API.X.AI/v1/" |
| 885 | )); |
| 886 | for neighboring_route in [ |
| 887 | "https://api.x.ai/V1", |
| 888 | "http://api.x.ai/v1", |
| 889 | "https://api.x.ai:443/v1", |
| 890 | "https://api.x.ai/v1?preview=1", |
| 891 | "https://api.x.ai/v1#fragment", |
| 892 | "https://api.x.ai/v1//", |
| 893 | "https://api.x.ai/v1/chat/completions", |
| 894 | "https://gateway.example/v1", |
| 895 | ] { |
| 896 | assert!( |
| 897 | !is_exact_xai_platform_route(ProviderKind::Xai, neighboring_route), |
| 898 | "{neighboring_route} must not inherit xAI-only request fields" |
| 899 | ); |
| 900 | } |
| 901 | assert!(!is_exact_xai_platform_route( |
| 902 | ProviderKind::Openai, |
| 903 | DEFAULT_XAI_BASE_URL |
| 904 | )); |
| 905 | } |
| 906 | |
| 907 | #[test] |
| 908 | fn zai_chat_route_matching_is_exact() { |
| 909 | for route in [ |
| 910 | "https://api.z.ai/api/coding/paas/v4", |
| 911 | "https://api.z.ai/api/paas/v4/", |
| 912 | "HTTPS://API.Z.AI/api/paas/v4", |
| 913 | // BigModel's general platform endpoint is the same first-party |
| 914 | // open platform; authority case stays insignificant. |
| 915 | "https://open.bigmodel.cn/api/coding/paas/v4", |
| 916 | "https://open.bigmodel.cn/api/coding/paas/v4/", |
| 917 | "https://open.bigmodel.cn/api/paas/v4", |
| 918 | "https://open.bigmodel.cn/api/paas/v4/", |
| 919 | "HTTPS://OPEN.BIGMODEL.CN/api/paas/v4", |
| 920 | ] { |
| 921 | assert!(is_exact_zai_chat_route(ProviderKind::Zai, route), "{route}"); |
| 922 | } |
| 923 | for neighboring_route in [ |
| 924 | "http://api.z.ai/api/paas/v4", |
| 925 | "https://api.z.ai:443/api/paas/v4", |
| 926 | "https://api.z.ai/API/paas/v4", |
| 927 | "https://api.z.ai/api/paas/v4?preview=1", |
| 928 | "https://api.z.ai/api/paas/v4#fragment", |
| 929 | "https://api.z.ai/api/paas/v4//", |
| 930 | "https://api.z.ai/api/paas/v4/chat/completions", |
| 931 | "https://open.bigmodel.cn/api/paas/v4/preview", |
| 932 | "https://open.bigmodel.cn/api/v1", |
| 933 | "http://open.bigmodel.cn/api/paas/v4", |
| 934 | "https://open.bigmodel.cn/API/paas/v4", |
| 935 | "https://gateway.example/v1", |
| 936 | ] { |
| 937 | assert!( |
| 938 | !is_exact_zai_chat_route(ProviderKind::Zai, neighboring_route), |
| 939 | "{neighboring_route} must not inherit Z.ai-only request fields" |
| 940 | ); |
| 941 | } |
| 942 | assert!(!is_exact_zai_chat_route( |
| 943 | ProviderKind::Openai, |
| 944 | DEFAULT_ZAI_BASE_URL |
| 945 | )); |
| 946 | assert!(!is_exact_zai_chat_route( |
| 947 | ProviderKind::Openai, |
| 948 | "https://open.bigmodel.cn/api/paas/v4" |
| 949 | )); |
| 950 | } |
| 951 | |
| 952 | #[test] |
| 953 | fn minimax_chat_route_matching_is_exact_and_excludes_messages() { |
| 954 | for route in [ |
| 955 | "https://api.minimax.io/v1", |
| 956 | "https://api.minimaxi.com/v1/", |
| 957 | "HTTPS://API.MINIMAX.IO/v1", |
| 958 | ] { |
| 959 | assert!( |
| 960 | is_exact_minimax_chat_route(ProviderKind::Minimax, route), |
| 961 | "{route}" |
| 962 | ); |
| 963 | } |
| 964 | for neighboring_route in [ |
| 965 | "http://api.minimax.io/v1", |
| 966 | "https://api.minimax.io:443/v1", |
| 967 | "https://api.minimax.io/V1", |
| 968 | "https://api.minimax.io/v1?preview=1", |
| 969 | "https://api.minimax.io/v1#fragment", |
| 970 | "https://api.minimax.io/v1//", |
| 971 | "https://api.minimax.io/v1/chat/completions", |
| 972 | "https://api.minimax.io/anthropic", |
| 973 | "https://api.minimaxi.com/anthropic", |
| 974 | "https://gateway.example/v1", |
| 975 | ] { |
| 976 | assert!( |
| 977 | !is_exact_minimax_chat_route(ProviderKind::Minimax, neighboring_route), |
| 978 | "{neighboring_route} must not inherit MiniMax Chat request fields" |
| 979 | ); |
| 980 | } |
| 981 | assert!(!is_exact_minimax_chat_route( |
| 982 | ProviderKind::MinimaxAnthropic, |
| 983 | DEFAULT_MINIMAX_BASE_URL |
| 984 | )); |
| 985 | } |
| 986 | |
| 987 | #[test] |
| 988 | fn minimax_anthropic_route_matching_is_exact_and_excludes_chat() { |
| 989 | for route in [ |
| 990 | "https://api.minimax.io/anthropic", |
| 991 | "https://api.minimaxi.com/anthropic/", |
| 992 | "HTTPS://API.MINIMAX.IO/anthropic", |
| 993 | ] { |
| 994 | assert!( |
| 995 | is_exact_minimax_anthropic_route(ProviderKind::MinimaxAnthropic, route), |
| 996 | "{route}" |
| 997 | ); |
| 998 | } |
| 999 | for neighboring_route in [ |
| 1000 | "http://api.minimax.io/anthropic", |
| 1001 | "https://api.minimax.io:443/anthropic", |
| 1002 | "https://api.minimax.io/Anthropic", |
| 1003 | "https://api.minimax.io/anthropic?preview=1", |
| 1004 | "https://api.minimax.io/anthropic#fragment", |
| 1005 | "https://api.minimax.io/anthropic//", |
| 1006 | "https://api.minimax.io/anthropic/v1/messages", |
| 1007 | "https://api.minimax.io/v1", |
| 1008 | "https://gateway.example/anthropic", |
| 1009 | ] { |
| 1010 | assert!( |
| 1011 | !is_exact_minimax_anthropic_route( |
| 1012 | ProviderKind::MinimaxAnthropic, |
| 1013 | neighboring_route |
| 1014 | ), |
| 1015 | "{neighboring_route} must not inherit MiniMax Messages semantics" |
| 1016 | ); |
| 1017 | } |
| 1018 | assert!(!is_exact_minimax_anthropic_route( |
| 1019 | ProviderKind::Minimax, |
| 1020 | DEFAULT_MINIMAX_ANTHROPIC_BASE_URL |
| 1021 | )); |
| 1022 | } |
| 1023 | |
| 1024 | #[test] |
| 1025 | fn non_key_and_mixed_routes_are_typed_explicitly() { |
| 1026 | for kind in [ |
| 1027 | ProviderKind::Sglang, |
| 1028 | ProviderKind::Vllm, |
| 1029 | ProviderKind::Ollama, |
| 1030 | ] { |
| 1031 | assert_eq!( |
| 1032 | provider_for_kind(kind).credential_help().acquisition, |
| 1033 | CredentialAcquisition::LocalOptional |
| 1034 | ); |
| 1035 | } |
| 1036 | assert_eq!( |
| 1037 | provider_for_kind(ProviderKind::OpenaiCodex) |
| 1038 | .credential_help() |
| 1039 | .acquisition, |
| 1040 | CredentialAcquisition::OAuth |
| 1041 | ); |
| 1042 | assert_eq!( |
| 1043 | provider_for_kind(ProviderKind::Xai) |
| 1044 | .credential_help() |
| 1045 | .acquisition, |
| 1046 | CredentialAcquisition::ApiKeyOrOAuth |
| 1047 | ); |
| 1048 | assert_eq!( |
| 1049 | provider_for_kind(ProviderKind::Custom) |
| 1050 | .credential_help() |
| 1051 | .acquisition, |
| 1052 | CredentialAcquisition::Configuration |
| 1053 | ); |
| 1054 | } |
| 1055 | |
| 1056 | #[test] |
| 1057 | fn antigravity_registry_entry_is_a_non_runnable_legacy_tombstone() { |
| 1058 | let legacy = provider_for_kind(ProviderKind::Antigravity); |
| 1059 | assert_eq!(legacy.id(), "antigravity"); |
| 1060 | assert!(legacy.env_vars().is_empty()); |
| 1061 | assert!(legacy.default_base_url().ends_with(".invalid")); |
| 1062 | assert_eq!(legacy.default_model(), "legacy-antigravity-disabled"); |
| 1063 | |
| 1064 | let help = legacy.credential_help(); |
| 1065 | assert_eq!(help.acquisition, CredentialAcquisition::Configuration); |
| 1066 | assert_eq!(help.credential_url, None); |
| 1067 | assert_eq!(help.docs_url, None); |
| 1068 | assert!( |
| 1069 | help.guidance |
| 1070 | .contains("codewhale auth clear --provider antigravity") |
| 1071 | ); |
| 1072 | assert!(help.guidance.contains("provider `google`")); |
| 1073 | assert!(help.guidance.contains("GEMINI_API_KEY")); |
| 1074 | } |
| 1075 | |
| 1076 | #[test] |
| 1077 | fn live_verified_console_replacements_do_not_regress_to_404_links() { |
| 1078 | let openmodel = provider_for_kind(ProviderKind::Openmodel).credential_help(); |
| 1079 | assert_eq!( |
| 1080 | openmodel.credential_url, |
| 1081 | Some("https://console.openmodel.ai/") |
| 1082 | ); |
| 1083 | assert_eq!( |
| 1084 | openmodel.docs_url, |
| 1085 | Some("https://docs.openmodel.ai/en/docs/getting-started/authentication") |
| 1086 | ); |
| 1087 | |
| 1088 | let sakana = provider_for_kind(ProviderKind::Sakana).credential_help(); |
| 1089 | assert_eq!( |
| 1090 | sakana.credential_url, |
| 1091 | Some("https://console.sakana.ai/api-keys") |
| 1092 | ); |
| 1093 | assert_eq!( |
| 1094 | sakana.docs_url, |
| 1095 | Some("https://console.sakana.ai/get-started") |
| 1096 | ); |
| 1097 | } |
| 1098 | |
| 1099 | #[test] |
| 1100 | fn model_aware_wire_policy_resolves_only_supported_endpoint_keys() { |
| 1101 | let policy = WirePolicy::ModelAware; |
| 1102 | assert_eq!(policy.resolve("chat"), Some(WireFormat::ChatCompletions)); |
| 1103 | assert_eq!(policy.resolve("responses"), Some(WireFormat::Responses)); |
| 1104 | assert_eq!( |
| 1105 | policy.resolve("messages"), |
| 1106 | Some(WireFormat::AnthropicMessages) |
| 1107 | ); |
| 1108 | assert_eq!(policy.resolve("models/gemini-3.1-pro"), None); |
| 1109 | assert_eq!(policy.resolve(""), None); |
| 1110 | } |
| 1111 | |
| 1112 | #[test] |
| 1113 | fn fixed_wire_policy_ignores_catalog_endpoint_keys() { |
| 1114 | let policy = WirePolicy::Fixed(WireFormat::Responses); |
| 1115 | assert_eq!(policy.resolve("chat"), Some(WireFormat::Responses)); |
| 1116 | assert_eq!(policy.resolve("unknown"), Some(WireFormat::Responses)); |
| 1117 | } |
| 1118 | |
| 1119 | #[test] |
| 1120 | fn display_order_is_alphabetical_by_display_name() { |
| 1121 | let display = providers_sorted_for_display(); |
| 1122 | let names: Vec<String> = display |
| 1123 | .iter() |
| 1124 | .map(|p| p.display_name().to_ascii_lowercase()) |
| 1125 | .collect(); |
| 1126 | let mut sorted = names.clone(); |
| 1127 | sorted.sort(); |
| 1128 | assert_eq!( |
| 1129 | names, sorted, |
| 1130 | "providers_sorted_for_display must be alphabetical (case-insensitive) by display name" |
| 1131 | ); |
| 1132 | } |
| 1133 | |
| 1134 | #[test] |
| 1135 | fn display_order_differs_from_internal_all_order() { |
| 1136 | // The whole point of the helper is that UI ordering is NOT the |
| 1137 | // internal compatibility-registry insertion order. |
| 1138 | let display_ids: Vec<&str> = providers_sorted_for_display() |
| 1139 | .iter() |
| 1140 | .map(|p| p.id()) |
| 1141 | .collect(); |
| 1142 | let internal_ids: Vec<&str> = all_providers().iter().map(|p| p.id()).collect(); |
| 1143 | assert_ne!( |
| 1144 | display_ids, internal_ids, |
| 1145 | "display order should not match internal ALL order" |
| 1146 | ); |
| 1147 | } |
| 1148 | |
| 1149 | #[test] |
| 1150 | fn display_order_is_complete_and_unique() { |
| 1151 | // Every selectable provider is retained exactly once; legacy |
| 1152 | // configuration tombstones stay in the internal registry only. |
| 1153 | let display = providers_sorted_for_display(); |
| 1154 | assert_eq!( |
| 1155 | display.len(), |
| 1156 | all_providers().len() - 1, |
| 1157 | "display order must include every selectable built-in provider" |
| 1158 | ); |
| 1159 | assert!( |
| 1160 | all_providers() |
| 1161 | .iter() |
| 1162 | .any(|provider| provider.kind() == ProviderKind::Antigravity), |
| 1163 | "legacy config identity must remain in the internal registry" |
| 1164 | ); |
| 1165 | assert!( |
| 1166 | display |
| 1167 | .iter() |
| 1168 | .all(|provider| provider.kind() != ProviderKind::Antigravity), |
| 1169 | "legacy Antigravity tombstone must not appear in provider pickers" |
| 1170 | ); |
| 1171 | let mut ids: Vec<&str> = display.iter().map(|p| p.id()).collect(); |
| 1172 | ids.sort_unstable(); |
| 1173 | let before = ids.len(); |
| 1174 | ids.dedup(); |
| 1175 | assert_eq!( |
| 1176 | before, |
| 1177 | ids.len(), |
| 1178 | "display order must not contain duplicates" |
| 1179 | ); |
| 1180 | } |
| 1181 | |
| 1182 | #[test] |
| 1183 | fn deepseek_is_present_but_not_first_in_display_order() { |
| 1184 | // Acceptance: DeepSeek stays searchable but is no longer hard-coded |
| 1185 | // first in provider browsing UI. (It is first in internal ALL order.) |
| 1186 | let display = providers_sorted_for_display(); |
| 1187 | assert_eq!( |
| 1188 | all_providers()[0].kind(), |
| 1189 | ProviderKind::Deepseek, |
| 1190 | "DeepSeek is expected to remain first in the stable internal order" |
| 1191 | ); |
| 1192 | assert!( |
| 1193 | display.iter().any(|p| p.kind() == ProviderKind::Deepseek), |
| 1194 | "DeepSeek must remain present in display order" |
| 1195 | ); |
| 1196 | assert_ne!( |
| 1197 | display[0].kind(), |
| 1198 | ProviderKind::Deepseek, |
| 1199 | "DeepSeek must not be hard-coded first in display order" |
| 1200 | ); |
| 1201 | // Alibaba Cloud Model Studio sorts before 'Anthropic' and 'DeepSeek' |
| 1202 | // alphabetically, so it is a stable check that the neutral ordering |
| 1203 | // actually took effect. |
| 1204 | assert_eq!( |
| 1205 | display[0].display_name(), |
| 1206 | "Alibaba Cloud Model Studio", |
| 1207 | "alphabetical display order should lead with Alibaba Cloud Model Studio" |
| 1208 | ); |
| 1209 | } |
| 1210 | } |
| 1211 |