| 1 | //! HTTP client for the resolved provider route. |
| 2 | //! |
| 3 | //! Routes reach the provider through its OpenAI-compatible or native wire |
| 4 | //! surface; `/chat/completions` is the common primary endpoint. |
| 5 | |
| 6 | use std::collections::HashMap; |
| 7 | #[cfg(any( |
| 8 | test, |
| 9 | feature = "test-support", |
| 10 | all(feature = "test-thread-scoped-state", debug_assertions) |
| 11 | ))] |
| 12 | use std::sync::Mutex as StdMutex; |
| 13 | use std::sync::atomic::{AtomicUsize, Ordering}; |
| 14 | use std::sync::{Arc, OnceLock}; |
| 15 | use std::time::{Duration, Instant}; |
| 16 | |
| 17 | use anyhow::{Context, Result, bail}; |
| 18 | use base64::{Engine as _, engine::general_purpose}; |
| 19 | use futures_util::StreamExt; |
| 20 | use reqwest::header::{AUTHORIZATION, CONTENT_TYPE, HeaderMap, HeaderName, HeaderValue}; |
| 21 | use serde::{Deserialize, Serialize}; |
| 22 | use serde_json::{Value, json}; |
| 23 | use tokio::sync::{ |
| 24 | Mutex as AsyncMutex, OwnedRwLockReadGuard, OwnedRwLockWriteGuard, OwnedSemaphorePermit, RwLock, |
| 25 | Semaphore, |
| 26 | }; |
| 27 | |
| 28 | use codewhale_config::catalog::{ |
| 29 | CatalogOffering, CatalogRefreshError, CatalogSource, ProviderCatalogDelta, |
| 30 | base_url_fingerprint, now_unix, |
| 31 | }; |
| 32 | #[cfg(any(test, feature = "test-support"))] |
| 33 | use codewhale_config::catalog::{CatalogSnapshot, CatalogStatus, ProviderCatalogCache}; |
| 34 | use codewhale_config::provider::WireFormat; |
| 35 | use codewhale_config::responses_dialect::{ResponsesPathPolicy, ResponsesProfileId}; |
| 36 | use codewhale_config::route::{ |
| 37 | LogicalModelRef, ReadyRouteCandidate, RouteLimits, RouteRequest, RouteResolver, |
| 38 | }; |
| 39 | use codewhale_config::{auth_mode_disables_api_key, is_upstream_auth_header}; |
| 40 | |
| 41 | use crate::llm_client::{ |
| 42 | LlmClient, LlmError, OutboundWireObservation, RetryConfig as LlmRetryConfig, |
| 43 | ToolWireMeasurement, extract_retry_after, observe_outbound_wire, retry_delay_from_error_body, |
| 44 | sanitize_http_error_body, with_retry, |
| 45 | }; |
| 46 | use codewhale_config::ProviderKind; |
| 47 | use codewhale_runtime::config::{Config, ProviderIdentity, RetryPolicy, validate_route}; |
| 48 | #[cfg(test)] |
| 49 | #[path = "client/catalog_tests.rs"] |
| 50 | mod catalog_tests; |
| 51 | |
| 52 | use codewhale_models::Role; |
| 53 | use codewhale_models::{ |
| 54 | ContentBlock, Message, MessageRequest, MessageResponse, SystemPrompt, Usage, |
| 55 | }; |
| 56 | use codewhale_runtime::logging; |
| 57 | use codewhale_sanitize::sanitize::redact_url_for_display; |
| 58 | |
| 59 | /// Every provider request that can feed the interactive TUI's attached CWC run |
| 60 | /// takes a shared permit at this lowest common dispatch seam. Runtime Chat holds |
| 61 | /// the exclusive permit from native admission through durable terminal |
| 62 | /// acknowledgement. This covers ordinary turns, auto-route classification, |
| 63 | /// advisor calls, detached subagents, compaction, purge, and streaming without |
| 64 | /// serializing independent RuntimeThreadManager stores. |
| 65 | #[cfg(not(any( |
| 66 | test, |
| 67 | feature = "test-support", |
| 68 | all(feature = "test-thread-scoped-state", debug_assertions) |
| 69 | )))] |
| 70 | static RUNTIME_CHAT_INFERENCE_GATE: OnceLock<Arc<RwLock<()>>> = OnceLock::new(); |
| 71 | |
| 72 | /// Unit tests run many independent Tokio runtimes in one process. Keying the |
| 73 | /// otherwise-identical gate by runtime keeps unrelated libtest cases from |
| 74 | /// manufacturing contention while preserving exact read/write behavior among |
| 75 | /// tasks on the same current-thread or multi-thread runtime. |
| 76 | #[cfg(any( |
| 77 | test, |
| 78 | feature = "test-support", |
| 79 | all(feature = "test-thread-scoped-state", debug_assertions) |
| 80 | ))] |
| 81 | static RUNTIME_CHAT_INFERENCE_TEST_GATES: OnceLock< |
| 82 | StdMutex<HashMap<RuntimeChatInferenceTestScope, std::sync::Weak<RwLock<()>>>>, |
| 83 | > = OnceLock::new(); |
| 84 | |
| 85 | #[cfg(any( |
| 86 | test, |
| 87 | feature = "test-support", |
| 88 | all(feature = "test-thread-scoped-state", debug_assertions) |
| 89 | ))] |
| 90 | #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] |
| 91 | enum RuntimeChatInferenceTestScope { |
| 92 | Runtime(tokio::runtime::Id), |
| 93 | Thread(std::thread::ThreadId), |
| 94 | } |
| 95 | |
| 96 | #[cfg(not(any( |
| 97 | test, |
| 98 | feature = "test-support", |
| 99 | all(feature = "test-thread-scoped-state", debug_assertions) |
| 100 | )))] |
| 101 | fn runtime_chat_inference_gate() -> Arc<RwLock<()>> { |
| 102 | Arc::clone(RUNTIME_CHAT_INFERENCE_GATE.get_or_init(|| Arc::new(RwLock::new(())))) |
| 103 | } |
| 104 | |
| 105 | #[cfg(any( |
| 106 | test, |
| 107 | feature = "test-support", |
| 108 | all(feature = "test-thread-scoped-state", debug_assertions) |
| 109 | ))] |
| 110 | fn runtime_chat_inference_gate() -> Arc<RwLock<()>> { |
| 111 | let scope = tokio::runtime::Handle::try_current() |
| 112 | .map(|handle| RuntimeChatInferenceTestScope::Runtime(handle.id())) |
| 113 | .unwrap_or_else(|_| RuntimeChatInferenceTestScope::Thread(std::thread::current().id())); |
| 114 | let mut gates = RUNTIME_CHAT_INFERENCE_TEST_GATES |
| 115 | .get_or_init(|| StdMutex::new(HashMap::new())) |
| 116 | .lock() |
| 117 | .unwrap_or_else(std::sync::PoisonError::into_inner); |
| 118 | if let Some(gate) = gates.get(&scope).and_then(std::sync::Weak::upgrade) { |
| 119 | return gate; |
| 120 | } |
| 121 | let gate = Arc::new(RwLock::new(())); |
| 122 | gates.insert(scope, Arc::downgrade(&gate)); |
| 123 | gate |
| 124 | } |
| 125 | |
| 126 | /// Exclusive ownership retained by isolated Runtime Chat. |
| 127 | pub struct RuntimeChatInferenceOwnership { |
| 128 | _gate: OwnedRwLockWriteGuard<()>, |
| 129 | } |
| 130 | |
| 131 | /// Shared participation retained for the full provider-output lifecycle. |
| 132 | pub struct RemoteControlInferencePermit { |
| 133 | _gate: OwnedRwLockReadGuard<()>, |
| 134 | } |
| 135 | |
| 136 | #[cfg(any( |
| 137 | test, |
| 138 | feature = "test-support", |
| 139 | all(feature = "test-thread-scoped-state", debug_assertions) |
| 140 | ))] |
| 141 | pub async fn acquire_runtime_chat_inference_ownership() -> RuntimeChatInferenceOwnership { |
| 142 | let gate = runtime_chat_inference_gate().write_owned().await; |
| 143 | RuntimeChatInferenceOwnership { _gate: gate } |
| 144 | } |
| 145 | |
| 146 | pub fn try_acquire_runtime_chat_inference_ownership() -> Option<RuntimeChatInferenceOwnership> { |
| 147 | let gate = runtime_chat_inference_gate().try_write_owned().ok()?; |
| 148 | Some(RuntimeChatInferenceOwnership { _gate: gate }) |
| 149 | } |
| 150 | |
| 151 | /// Join the attached interactive CWC run as a provider-output participant. |
| 152 | /// Standalone background adapters that bypass `CodewhaleClient::create_message` |
| 153 | /// use this guard and retain it through response decoding. |
| 154 | pub async fn acquire_remote_control_inference_participant() -> RemoteControlInferencePermit { |
| 155 | let gate = runtime_chat_inference_gate().read_owned().await; |
| 156 | RemoteControlInferencePermit { _gate: gate } |
| 157 | } |
| 158 | |
| 159 | tokio::task_local! { |
| 160 | pub(crate) static OPENCODE_CONVERSATION: String; |
| 161 | } |
| 162 | |
| 163 | pub(crate) fn opencode_conversation_key(session: &str, child: Option<&str>) -> String { |
| 164 | let key = serde_json::to_vec(&(session, child)).expect("strings serialize to JSON"); |
| 165 | codewhale_runtime::hashing::sha256_hex(key) |
| 166 | } |
| 167 | |
| 168 | // === Types === |
| 169 | |
| 170 | /// Model descriptor returned by the provider's `/v1/models` endpoint. |
| 171 | #[derive(Debug, Clone, Serialize, PartialEq, Eq)] |
| 172 | pub struct AvailableModel { |
| 173 | pub id: String, |
| 174 | pub owned_by: Option<String>, |
| 175 | pub created: Option<u64>, |
| 176 | #[serde(skip_serializing_if = "Option::is_none")] |
| 177 | pub display_name: Option<String>, |
| 178 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 179 | pub context_window: Option<u32>, |
| 180 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 181 | pub effective_context_window_percent: Option<u8>, |
| 182 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 183 | pub reasoning: Option<bool>, |
| 184 | #[serde(default, skip_serializing_if = "Vec::is_empty")] |
| 185 | pub efforts: Vec<String>, |
| 186 | } |
| 187 | |
| 188 | /// Request payload for Xiaomi MiMo speech synthesis models. |
| 189 | /// |
| 190 | /// MiMo-V2.5-TTS / MiMo-V2-TTS use the OpenAI-compatible |
| 191 | /// `/v1/chat/completions` endpoint: the optional style/voice instruction is |
| 192 | /// sent as a `user` message, while the text to synthesize is sent as an |
| 193 | /// `assistant` message. |
| 194 | #[derive(Debug, Clone)] |
| 195 | pub struct SpeechSynthesisRequest { |
| 196 | pub model: String, |
| 197 | pub text: String, |
| 198 | pub instruction: Option<String>, |
| 199 | pub audio_format: String, |
| 200 | pub voice: Option<String>, |
| 201 | } |
| 202 | |
| 203 | /// Decoded speech synthesis result. |
| 204 | #[derive(Debug, Clone)] |
| 205 | pub struct SpeechSynthesisResponse { |
| 206 | pub model: String, |
| 207 | pub audio_format: String, |
| 208 | pub audio_bytes: Vec<u8>, |
| 209 | pub transcript: Option<String>, |
| 210 | pub voice: Option<String>, |
| 211 | } |
| 212 | |
| 213 | /// One decoded provider response from the auxiliary translation path. |
| 214 | /// |
| 215 | /// The immutable route and provider-reported usage travel beside the semantic |
| 216 | /// translation result so callers can account for a successful provider call |
| 217 | /// before rejecting an incomplete, empty, or otherwise unusable translation. |
| 218 | /// `usage == None` is distinct from a transport failure: the provider returned |
| 219 | /// a response, but omitted the receipt needed to price it exactly. |
| 220 | pub struct TranslationProviderResponse { |
| 221 | pub translated: Result<String>, |
| 222 | pub route: crate::cost_status::EffectiveRouteEnvelope, |
| 223 | pub usage: Option<Usage>, |
| 224 | pub accounting: Option<crate::cost_status::RuntimeUsageRecord>, |
| 225 | } |
| 226 | |
| 227 | /// Universal client for the resolved provider route. |
| 228 | #[must_use] |
| 229 | pub struct CodewhaleClient { |
| 230 | pub(super) http_client: reqwest::Client, |
| 231 | catalog_connection_base: Option<String>, |
| 232 | go_route: Option<(codewhale_config::route::CatalogConnection, String)>, |
| 233 | // Catalogs and probes must never forward frozen custom auth headers to a |
| 234 | // provider-supplied redirect destination. Inference keeps its own policy. |
| 235 | models_http_client: reqwest::Client, |
| 236 | /// HTTP/1.1-only twin of [`Self::http_client`], used for automatic |
| 237 | /// stream-header fallback when H2 stalls. Same auth and headers. |
| 238 | pub(super) http1_client: reqwest::Client, |
| 239 | api_key: String, |
| 240 | /// Where `api_key` came from (secret store slot, config file, env var |
| 241 | /// name, CLI, OAuth, …), named in authentication errors (#6528). |
| 242 | api_key_source: String, |
| 243 | /// For a subscription sign-in route (ChatGPT, xAI OAuth): which account |
| 244 | /// is signed in and how to switch, appended to plan-quota errors. Holds |
| 245 | /// an account label only, never token material. |
| 246 | subscription_limit_guidance: Option<String>, |
| 247 | resume_account_scope: Option<String>, |
| 248 | exec_plugin_grant: Option<uuid::Uuid>, |
| 249 | /// Reviewed runtime authority and OAuth descriptor travel with the frozen route. |
| 250 | plugin_provider: Option<Box<codewhale_runtime::config::ProviderConfig>>, |
| 251 | /// Read-only diagnostic probes must never migrate or refresh the grant. |
| 252 | plugin_oauth_read_only: bool, |
| 253 | claude_org: Option<Arc<claude_org::ClaudeOrgAuth>>, |
| 254 | session_provider_keys_only: bool, |
| 255 | automatic_opencode_session: Option<String>, |
| 256 | /// Exact configured credential values removed from model-bound tool |
| 257 | /// results. Structural redaction handles config/JSON assignments, while |
| 258 | /// this list closes the gap for bare provider tokens with no recognizable |
| 259 | /// prefix (for example token-plan and provider-specific keys). |
| 260 | model_bound_secret_values: Arc<Vec<String>>, |
| 261 | /// Exact values a catalog endpoint could echo back at us: the active API |
| 262 | /// key and every user-configured HTTP header value, plus everything in |
| 263 | /// `model_bound_secret_values`. |
| 264 | /// |
| 265 | /// Deliberately a second, wider list rather than a widening of that one: |
| 266 | /// they answer different questions at different trust boundaries. That |
| 267 | /// list is "what must never reach a *model*", which is why it covers only |
| 268 | /// auth-shaped headers and values of at least |
| 269 | /// `MIN_EXACT_SECRET_CHARS`. This one is "what must never come back out |
| 270 | /// of an endpoint the user typed during setup" (#6173), where a |
| 271 | /// three-character key is still a key and a custom header the user |
| 272 | /// configured is still theirs. |
| 273 | catalog_error_secret_values: Arc<Vec<String>>, |
| 274 | /// Whether credential-shaped tool output is masked before it is sent to an |
| 275 | /// upstream model. The safe default is `true`; it is `false` only after the |
| 276 | /// user disabled `[redaction] model_bound` and confirmed the opt-out on the |
| 277 | /// startup gate (see [`codewhale_config::redaction`]). Routing/classification |
| 278 | /// summaries and durable goal-state text keep their own always-on redaction |
| 279 | /// regardless of this flag. |
| 280 | model_bound_masking: bool, |
| 281 | pub(super) base_url: String, |
| 282 | pub(super) api_provider: ProviderKind, |
| 283 | /// Exact configured provider identity and billing mode frozen when this |
| 284 | /// client is built. Child/tool calls only carry the client at dispatch, so |
| 285 | /// these route facts must travel with it instead of being reconstructed |
| 286 | /// from the mutable parent session at completion time. |
| 287 | admitted_identity: ProviderIdentity, |
| 288 | openrouter_vendor: Option<String>, |
| 289 | billing_surface: Option<String>, |
| 290 | billing_mode: crate::cost_status::RouteBillingMode, |
| 291 | configured_models: Arc<Vec<codewhale_config::catalog::configured::ConfiguredModel>>, |
| 292 | context_window_override: Option<u32>, |
| 293 | model_context_windows: Option<std::collections::BTreeMap<String, u32>>, |
| 294 | /// Non-secret limits frozen from the same resolved candidate as the |
| 295 | /// endpoint and wire model. Auxiliary calls carry only this client, so |
| 296 | /// they must not reconstruct output caps with `None` and discard a custom |
| 297 | /// route's context window. |
| 298 | route_limits: Option<RouteLimits>, |
| 299 | context_window: Option<crate::route_runtime::ContextWindowResolution>, |
| 300 | route_facts: Option<Arc<codewhale_config::catalog::CatalogOffering>>, |
| 301 | /// Verified ChatGPT subject captured with Codewhale's own selected grant. |
| 302 | pub(super) codex_account_id: Option<String>, |
| 303 | /// Opaque reasoning is bound to this verified grant identity, stable across |
| 304 | /// token refresh and absent on custom API-key routes. |
| 305 | pub(super) chatgpt_reasoning_api: Option<String>, |
| 306 | wire_format: WireFormat, |
| 307 | /// Admitted Responses dialect. Empty for Chat, Messages, and catalog probes. |
| 308 | responses_profile_id: Option<ResponsesProfileId>, |
| 309 | retry: RetryPolicy, |
| 310 | /// Auxiliary inspection calls use the normal bounded retry schedule but |
| 311 | /// never publish retry/rate-limit state into process-global UI cells. |
| 312 | isolated_request_state: bool, |
| 313 | /// Whether this concrete client can contribute provider output to the |
| 314 | /// interactive TUI's attached CWC run. Isolated Runtime Chat executes under |
| 315 | /// the host's exclusive permit; independent RuntimeThreadManager stores do |
| 316 | /// not share that run and remain concurrent. |
| 317 | remote_control_inference_participant: bool, |
| 318 | default_model: String, |
| 319 | connection_health: Arc<AsyncMutex<ConnectionHealth>>, |
| 320 | rate_limiter: Arc<AsyncMutex<TokenBucket>>, |
| 321 | request_concurrency: Option<ProviderConcurrencyLimiter>, |
| 322 | path_suffix: Option<String>, |
| 323 | /// Unit tests keep the semantic route exact while sending the actual |
| 324 | /// production request through a local capture server. This field is |
| 325 | /// compiled out of release builds. |
| 326 | #[cfg(any(test, feature = "test-support"))] |
| 327 | test_chat_transport_base_url: Option<String>, |
| 328 | /// Messages equivalent of `test_chat_transport_base_url`; keeps exact |
| 329 | /// route shaping bound to the semantic endpoint while tests capture on a |
| 330 | /// local server. |
| 331 | #[cfg(any(test, feature = "test-support"))] |
| 332 | test_messages_transport_base_url: Option<String>, |
| 333 | pub(super) reasoning_stream_style: Option<String>, |
| 334 | pub(super) stream_idle_timeout: Duration, |
| 335 | /// Bounded wait for SSE response headers, resolved once from |
| 336 | /// `[stream].open_timeout_secs`, legacy `[tui]`, or the environment fallback. |
| 337 | pub(super) stream_open_timeout: Duration, |
| 338 | /// HTTP/1.1 pin resolved once from `Config::force_http1` (#6700); the |
| 339 | /// single source every client builder and stream open reads. |
| 340 | pub(super) force_http1: bool, |
| 341 | } |
| 342 | |
| 343 | const CONNECTION_FAILURE_THRESHOLD: u32 = 2; |
| 344 | const RECOVERY_PROBE_COOLDOWN: Duration = Duration::from_secs(15); |
| 345 | |
| 346 | const DEFAULT_CLIENT_RATE_LIMIT_RPS: f64 = 8.0; |
| 347 | const DEFAULT_CLIENT_RATE_LIMIT_BURST: f64 = 16.0; |
| 348 | const ALLOW_INSECURE_HTTP_ENV: &str = "CODEWHALE_ALLOW_INSECURE_HTTP"; |
| 349 | /// Legacy alias for [`ALLOW_INSECURE_HTTP_ENV`]. |
| 350 | const LEGACY_ALLOW_INSECURE_HTTP_ENV: &str = "DEEPSEEK_ALLOW_INSECURE_HTTP"; |
| 351 | |
| 352 | fn client_user_agent(_api_provider: ProviderKind) -> &'static str { |
| 353 | concat!( |
| 354 | "Mozilla/5.0 (compatible; codewhale/", |
| 355 | env!("CARGO_PKG_VERSION"), |
| 356 | "; +https://github.com/codewhale-hq/CodeWhale)" |
| 357 | ) |
| 358 | } |
| 359 | |
| 360 | /// Upper bound on a single sleep inside the provider-wide rate-limit pause |
| 361 | /// loop in `send_with_retry`. The pause window lives in process-global state |
| 362 | /// (`retry_status`), so waiting requests re-poll it on this cadence instead |
| 363 | /// of committing to the full remaining window up front. |
| 364 | const RATE_LIMIT_PAUSE_RECHECK_INTERVAL: Duration = Duration::from_millis(250); |
| 365 | |
| 366 | /// Total budget for one non-streaming request. Two layers use it: each |
| 367 | /// attempt carries it as a reqwest per-request total (connect through body |
| 368 | /// end, so a trickling body cannot extend forever), and the retry loop |
| 369 | /// through `send_with_retry` is wrapped in one outer envelope of the same |
| 370 | /// length (all attempts, backoff, and honored Retry-After included). The |
| 371 | /// shared client intentionally has no client-level total timeout, so without |
| 372 | /// these nothing bounds a non-streaming completion: a provider that accepts |
| 373 | /// the connection and then stalls — or a gateway answering 429 + |
| 374 | /// `Retry-After: 3600` forever — wedged the caller indefinitely. |
| 375 | /// |
| 376 | /// Streaming paths never carry it: their opens go through |
| 377 | /// `send_stream_open_with_retry`, which sets no per-request total (a total |
| 378 | /// would ride on the returned body and hard-cut a live stream), so a stream |
| 379 | /// stays bounded by its open cap and per-chunk idle checks only. |
| 380 | pub(super) const NON_STREAMING_REQUEST_ENVELOPE: Duration = Duration::from_secs(1800); |
| 381 | |
| 382 | #[cfg(any(test, feature = "test-support"))] |
| 383 | static TEST_NON_STREAMING_ENVELOPE_MS: std::sync::atomic::AtomicU64 = |
| 384 | std::sync::atomic::AtomicU64::new(0); |
| 385 | |
| 386 | fn non_streaming_request_envelope() -> Duration { |
| 387 | #[cfg(any(test, feature = "test-support"))] |
| 388 | { |
| 389 | let ms = TEST_NON_STREAMING_ENVELOPE_MS.load(std::sync::atomic::Ordering::SeqCst); |
| 390 | if ms > 0 { |
| 391 | return Duration::from_millis(ms); |
| 392 | } |
| 393 | } |
| 394 | NON_STREAMING_REQUEST_ENVELOPE |
| 395 | } |
| 396 | |
| 397 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 398 | enum ConnectionState { |
| 399 | Healthy, |
| 400 | Degraded, |
| 401 | Recovering, |
| 402 | } |
| 403 | |
| 404 | #[derive(Debug)] |
| 405 | struct ConnectionHealth { |
| 406 | state: ConnectionState, |
| 407 | consecutive_failures: u32, |
| 408 | last_failure: Option<Instant>, |
| 409 | last_success: Option<Instant>, |
| 410 | last_probe: Option<Instant>, |
| 411 | } |
| 412 | |
| 413 | impl Default for ConnectionHealth { |
| 414 | fn default() -> Self { |
| 415 | Self { |
| 416 | state: ConnectionState::Healthy, |
| 417 | consecutive_failures: 0, |
| 418 | last_failure: None, |
| 419 | last_success: None, |
| 420 | last_probe: None, |
| 421 | } |
| 422 | } |
| 423 | } |
| 424 | |
| 425 | #[derive(Debug)] |
| 426 | struct TokenBucket { |
| 427 | enabled: bool, |
| 428 | capacity: f64, |
| 429 | tokens: f64, |
| 430 | refill_per_sec: f64, |
| 431 | last_refill: Instant, |
| 432 | } |
| 433 | |
| 434 | #[derive(Debug, Clone)] |
| 435 | struct ProviderConcurrencyLimiter { |
| 436 | semaphore: Arc<Semaphore>, |
| 437 | active: Arc<AtomicUsize>, |
| 438 | limit: usize, |
| 439 | } |
| 440 | |
| 441 | struct ProviderRequestPermit { |
| 442 | _permit: OwnedSemaphorePermit, |
| 443 | active: Arc<AtomicUsize>, |
| 444 | } |
| 445 | |
| 446 | impl ProviderConcurrencyLimiter { |
| 447 | fn new(limit: usize) -> Self { |
| 448 | let limit = limit.max(1); |
| 449 | Self { |
| 450 | semaphore: Arc::new(Semaphore::new(limit)), |
| 451 | active: Arc::new(AtomicUsize::new(0)), |
| 452 | limit, |
| 453 | } |
| 454 | } |
| 455 | |
| 456 | async fn acquire(&self) -> Option<ProviderRequestPermit> { |
| 457 | let permit = Arc::clone(&self.semaphore).acquire_owned().await.ok()?; |
| 458 | self.active.fetch_add(1, Ordering::AcqRel); |
| 459 | Some(ProviderRequestPermit { |
| 460 | _permit: permit, |
| 461 | active: Arc::clone(&self.active), |
| 462 | }) |
| 463 | } |
| 464 | |
| 465 | fn active(&self) -> usize { |
| 466 | self.active.load(Ordering::Acquire) |
| 467 | } |
| 468 | |
| 469 | fn limit(&self) -> usize { |
| 470 | self.limit |
| 471 | } |
| 472 | } |
| 473 | |
| 474 | impl Drop for ProviderRequestPermit { |
| 475 | fn drop(&mut self) { |
| 476 | self.active.fetch_sub(1, Ordering::AcqRel); |
| 477 | } |
| 478 | } |
| 479 | |
| 480 | impl TokenBucket { |
| 481 | fn from_env() -> Self { |
| 482 | let rps = std::env::var("CODEWHALE_RATE_LIMIT_RPS") |
| 483 | .or_else(|_| std::env::var("DEEPSEEK_RATE_LIMIT_RPS")) |
| 484 | .ok() |
| 485 | .and_then(|v| v.parse::<f64>().ok()) |
| 486 | .unwrap_or(DEFAULT_CLIENT_RATE_LIMIT_RPS) |
| 487 | .max(0.0); |
| 488 | let burst = std::env::var("CODEWHALE_RATE_LIMIT_BURST") |
| 489 | .or_else(|_| std::env::var("DEEPSEEK_RATE_LIMIT_BURST")) |
| 490 | .ok() |
| 491 | .and_then(|v| v.parse::<f64>().ok()) |
| 492 | .unwrap_or(DEFAULT_CLIENT_RATE_LIMIT_BURST) |
| 493 | .max(1.0); |
| 494 | let enabled = rps > 0.0; |
| 495 | Self { |
| 496 | enabled, |
| 497 | capacity: burst, |
| 498 | tokens: burst, |
| 499 | refill_per_sec: rps, |
| 500 | last_refill: Instant::now(), |
| 501 | } |
| 502 | } |
| 503 | |
| 504 | fn refill(&mut self, now: Instant) { |
| 505 | if !self.enabled { |
| 506 | return; |
| 507 | } |
| 508 | let elapsed = now.duration_since(self.last_refill).as_secs_f64(); |
| 509 | self.last_refill = now; |
| 510 | self.tokens = (self.tokens + elapsed * self.refill_per_sec).min(self.capacity); |
| 511 | } |
| 512 | |
| 513 | /// Reserve `tokens` and report how long the caller must sleep first. |
| 514 | /// |
| 515 | /// The debt is *kept* (the balance is allowed to go negative) rather than |
| 516 | /// floored at zero. Callers release the bucket lock before sleeping, so a |
| 517 | /// floored balance would hand every queued waiter the same short delay and |
| 518 | /// they would all wake — and fire — at the same instant, which is the |
| 519 | /// burst the configured limit exists to prevent. Carrying the deficit |
| 520 | /// spaces successive waiters one refill interval apart, and `refill`'s |
| 521 | /// clamp to `capacity` still caps how much credit an idle bucket banks. |
| 522 | fn delay_until_available(&mut self, tokens: f64) -> Option<Duration> { |
| 523 | if !self.enabled { |
| 524 | return None; |
| 525 | } |
| 526 | let now = Instant::now(); |
| 527 | self.refill(now); |
| 528 | self.tokens -= tokens; |
| 529 | if self.tokens >= 0.0 { |
| 530 | return None; |
| 531 | } |
| 532 | if self.refill_per_sec <= 0.0 { |
| 533 | return Some(Duration::from_secs(1)); |
| 534 | } |
| 535 | Some( |
| 536 | Duration::try_from_secs_f64(-self.tokens / self.refill_per_sec) |
| 537 | .unwrap_or(Duration::MAX), |
| 538 | ) |
| 539 | } |
| 540 | } |
| 541 | |
| 542 | fn apply_request_success(health: &mut ConnectionHealth, now: Instant) -> bool { |
| 543 | let recovered = health.state != ConnectionState::Healthy; |
| 544 | health.state = ConnectionState::Healthy; |
| 545 | health.consecutive_failures = 0; |
| 546 | health.last_success = Some(now); |
| 547 | recovered |
| 548 | } |
| 549 | |
| 550 | fn apply_request_failure(health: &mut ConnectionHealth, now: Instant) { |
| 551 | health.consecutive_failures = health.consecutive_failures.saturating_add(1); |
| 552 | health.last_failure = Some(now); |
| 553 | if health.consecutive_failures >= CONNECTION_FAILURE_THRESHOLD { |
| 554 | health.state = ConnectionState::Degraded; |
| 555 | } |
| 556 | } |
| 557 | |
| 558 | fn mark_recovery_probe_if_due(health: &mut ConnectionHealth, now: Instant) -> bool { |
| 559 | if health.state == ConnectionState::Healthy { |
| 560 | return false; |
| 561 | } |
| 562 | if health |
| 563 | .last_probe |
| 564 | .is_some_and(|last| now.duration_since(last) < RECOVERY_PROBE_COOLDOWN) |
| 565 | { |
| 566 | return false; |
| 567 | } |
| 568 | health.last_probe = Some(now); |
| 569 | health.state = ConnectionState::Recovering; |
| 570 | true |
| 571 | } |
| 572 | |
| 573 | /// The one command that replaces a rejected key, by where it came from. |
| 574 | fn auth_fix_hint(route: &str, key_source: &str) -> String { |
| 575 | if key_source == codewhale_config::credentials::CLAUDE_ORG_KEY_SOURCE { |
| 576 | claude_org::relink_hint() |
| 577 | } else if key_source.starts_with("--api-key") { |
| 578 | "pass a valid --api-key".to_string() |
| 579 | } else if let Some(rest) = key_source.strip_prefix("env var ") |
| 580 | && rest.contains("api_key_env") |
| 581 | { |
| 582 | let name = rest.split_whitespace().next().unwrap_or(rest); |
| 583 | format!("set {name} to a valid key") |
| 584 | } else if key_source.contains("OAuth") || key_source.contains("login") { |
| 585 | format!("sign in again for {route}") |
| 586 | } else { |
| 587 | format!("codewhale auth set --provider {route}") |
| 588 | } |
| 589 | } |
| 590 | |
| 591 | impl Clone for CodewhaleClient { |
| 592 | fn clone(&self) -> Self { |
| 593 | Self { |
| 594 | http_client: self.http_client.clone(), |
| 595 | catalog_connection_base: self.catalog_connection_base.clone(), |
| 596 | go_route: self.go_route.clone(), |
| 597 | models_http_client: self.models_http_client.clone(), |
| 598 | http1_client: self.http1_client.clone(), |
| 599 | api_key: self.api_key.clone(), |
| 600 | api_key_source: self.api_key_source.clone(), |
| 601 | subscription_limit_guidance: self.subscription_limit_guidance.clone(), |
| 602 | resume_account_scope: self.resume_account_scope.clone(), |
| 603 | exec_plugin_grant: self.exec_plugin_grant, |
| 604 | plugin_provider: self.plugin_provider.clone(), |
| 605 | plugin_oauth_read_only: self.plugin_oauth_read_only, |
| 606 | claude_org: self.claude_org.clone(), |
| 607 | session_provider_keys_only: self.session_provider_keys_only, |
| 608 | automatic_opencode_session: self.automatic_opencode_session.clone(), |
| 609 | model_bound_secret_values: Arc::clone(&self.model_bound_secret_values), |
| 610 | catalog_error_secret_values: Arc::clone(&self.catalog_error_secret_values), |
| 611 | model_bound_masking: self.model_bound_masking, |
| 612 | base_url: self.base_url.clone(), |
| 613 | api_provider: self.api_provider, |
| 614 | admitted_identity: self.admitted_identity.clone(), |
| 615 | openrouter_vendor: self.openrouter_vendor.clone(), |
| 616 | billing_surface: self.billing_surface.clone(), |
| 617 | billing_mode: self.billing_mode, |
| 618 | configured_models: Arc::clone(&self.configured_models), |
| 619 | context_window_override: self.context_window_override, |
| 620 | model_context_windows: self.model_context_windows.clone(), |
| 621 | route_limits: self.route_limits, |
| 622 | context_window: self.context_window, |
| 623 | route_facts: self.route_facts.clone(), |
| 624 | codex_account_id: self.codex_account_id.clone(), |
| 625 | chatgpt_reasoning_api: self.chatgpt_reasoning_api.clone(), |
| 626 | wire_format: self.wire_format, |
| 627 | responses_profile_id: self.responses_profile_id, |
| 628 | retry: self.retry.clone(), |
| 629 | isolated_request_state: self.isolated_request_state, |
| 630 | remote_control_inference_participant: self.remote_control_inference_participant, |
| 631 | default_model: self.default_model.clone(), |
| 632 | connection_health: self.connection_health.clone(), |
| 633 | rate_limiter: self.rate_limiter.clone(), |
| 634 | request_concurrency: self.request_concurrency.clone(), |
| 635 | path_suffix: self.path_suffix.clone(), |
| 636 | #[cfg(any(test, feature = "test-support"))] |
| 637 | test_chat_transport_base_url: self.test_chat_transport_base_url.clone(), |
| 638 | #[cfg(any(test, feature = "test-support"))] |
| 639 | test_messages_transport_base_url: self.test_messages_transport_base_url.clone(), |
| 640 | reasoning_stream_style: self.reasoning_stream_style.clone(), |
| 641 | stream_idle_timeout: self.stream_idle_timeout, |
| 642 | stream_open_timeout: self.stream_open_timeout, |
| 643 | force_http1: self.force_http1, |
| 644 | } |
| 645 | } |
| 646 | } |
| 647 | |
| 648 | const MIN_EXACT_SECRET_CHARS: usize = 8; |
| 649 | |
| 650 | pub use codewhale_config::apply_openrouter_vendor; |
| 651 | |
| 652 | fn push_model_bound_secret(values: &mut Vec<String>, value: Option<&str>) { |
| 653 | let Some(value) = value |
| 654 | .map(str::trim) |
| 655 | .filter(|value| !value.is_empty() && value.chars().count() >= MIN_EXACT_SECRET_CHARS) |
| 656 | else { |
| 657 | return; |
| 658 | }; |
| 659 | if !values.iter().any(|existing| existing == value) { |
| 660 | values.push(value.to_string()); |
| 661 | } |
| 662 | } |
| 663 | |
| 664 | fn model_bound_secret_store_slot(provider: ProviderKind) -> Option<&'static str> { |
| 665 | (provider != ProviderKind::Custom).then(|| provider.secret_store_slot()) |
| 666 | } |
| 667 | |
| 668 | fn push_file_backed_model_bound_secrets(values: &mut Vec<String>) { |
| 669 | // Unit tests must never inspect the developer's real credential store. |
| 670 | // The isolated regression below opts in with a temporary CODEWHALE_HOME, |
| 671 | // matching Config's existing secret-store test discipline. |
| 672 | #[cfg(any(test, feature = "test-support"))] |
| 673 | if !codewhale_paths::codewhale_home_is_explicit() |
| 674 | || std::env::var_os("CODEWHALE_SECRET_BACKEND").is_none() |
| 675 | { |
| 676 | return; |
| 677 | } |
| 678 | |
| 679 | // Redaction needs only a best-effort view of inactive file-backed |
| 680 | // credentials. It must not cause a legacy-store migration merely because a |
| 681 | // client is being constructed (notably for `doctor`'s live probe). Keep |
| 682 | // this file-only to avoid a burst of OS-keychain prompts for inactive |
| 683 | // providers; the active credential is already supplied by the route |
| 684 | // resolver. |
| 685 | let secrets = codewhale_secrets::Secrets::file_backed_read_only(); |
| 686 | let mut slots = Vec::new(); |
| 687 | for provider in codewhale_config::descriptors::provider_compatibility() |
| 688 | .iter() |
| 689 | .map(|row| row.kind) |
| 690 | { |
| 691 | let Some(slot) = model_bound_secret_store_slot(provider) else { |
| 692 | continue; |
| 693 | }; |
| 694 | if !slots.contains(&slot) { |
| 695 | slots.push(slot); |
| 696 | } |
| 697 | } |
| 698 | // The legacy literal `provider = "custom"` route owns this durable slot. |
| 699 | slots.push("custom"); |
| 700 | |
| 701 | for slot in slots { |
| 702 | if let Ok(Some(secret)) = secrets.get(slot) { |
| 703 | push_model_bound_secret(values, Some(&secret)); |
| 704 | } |
| 705 | } |
| 706 | } |
| 707 | |
| 708 | pub fn active_model_bound_secret_values(config: &Config) -> Vec<String> { |
| 709 | let active_key = config.active_route_api_key_read_only().unwrap_or_default(); |
| 710 | configured_model_bound_secret_values(config, &active_key) |
| 711 | } |
| 712 | |
| 713 | fn capture_file_backed_model_bound_secret_values() -> Vec<String> { |
| 714 | let mut values = Vec::new(); |
| 715 | push_file_backed_model_bound_secrets(&mut values); |
| 716 | values |
| 717 | } |
| 718 | |
| 719 | pub fn configured_model_bound_secret_values(config: &Config, active_api_key: &str) -> Vec<String> { |
| 720 | configured_model_bound_secret_values_with( |
| 721 | config, |
| 722 | active_api_key, |
| 723 | capture_file_backed_model_bound_secret_values(), |
| 724 | ) |
| 725 | } |
| 726 | |
| 727 | fn configured_model_bound_secret_values_with( |
| 728 | config: &Config, |
| 729 | active_api_key: &str, |
| 730 | file_backed: Vec<String>, |
| 731 | ) -> Vec<String> { |
| 732 | let mut values = Vec::new(); |
| 733 | push_model_bound_secret(&mut values, Some(active_api_key)); |
| 734 | for (_, credential) in config.session_provider_keys.read().values() { |
| 735 | push_model_bound_secret(&mut values, Some(credential.expose_secret())); |
| 736 | } |
| 737 | push_model_bound_secret(&mut values, config.sandbox_api_key.as_deref()); |
| 738 | push_model_bound_secret( |
| 739 | &mut values, |
| 740 | config |
| 741 | .search |
| 742 | .as_ref() |
| 743 | .and_then(|search| search.api_key.as_deref()), |
| 744 | ); |
| 745 | push_model_bound_secret( |
| 746 | &mut values, |
| 747 | config |
| 748 | .vision_model |
| 749 | .as_ref() |
| 750 | .and_then(|vision| vision.api_key.as_deref()), |
| 751 | ); |
| 752 | |
| 753 | if let Some(headers) = config.http_headers.as_ref() { |
| 754 | for (name, value) in headers { |
| 755 | if is_upstream_auth_header(name) { |
| 756 | push_model_bound_secret(&mut values, Some(value)); |
| 757 | } |
| 758 | } |
| 759 | } |
| 760 | |
| 761 | for row in codewhale_config::descriptors::provider_compatibility() |
| 762 | .iter() |
| 763 | .filter(|row| row.kind != ProviderKind::Custom) |
| 764 | { |
| 765 | for env_name in row.kind.provider().env_vars() { |
| 766 | if let Ok(value) = std::env::var(env_name) { |
| 767 | push_model_bound_secret(&mut values, Some(&value)); |
| 768 | } |
| 769 | } |
| 770 | let Some(provider_config) = config |
| 771 | .providers |
| 772 | .as_ref() |
| 773 | .and_then(|tables| codewhale_config::provider_config_table!(@read tables, row.id)) |
| 774 | else { |
| 775 | continue; |
| 776 | }; |
| 777 | push_model_bound_secret(&mut values, provider_config.api_key.as_deref()); |
| 778 | if let Some(headers) = provider_config.http_headers.as_ref() { |
| 779 | for (name, value) in headers { |
| 780 | if is_upstream_auth_header(name) { |
| 781 | push_model_bound_secret(&mut values, Some(value)); |
| 782 | } |
| 783 | } |
| 784 | } |
| 785 | } |
| 786 | |
| 787 | if let Some(providers) = config.providers.as_ref() { |
| 788 | for provider_config in providers.custom.values() { |
| 789 | push_model_bound_secret(&mut values, provider_config.api_key.as_deref()); |
| 790 | if let Some(env_name) = provider_config |
| 791 | .api_key_env |
| 792 | .as_deref() |
| 793 | .map(str::trim) |
| 794 | .filter(|name| !name.is_empty()) |
| 795 | && let Ok(value) = std::env::var(env_name) |
| 796 | { |
| 797 | push_model_bound_secret(&mut values, Some(&value)); |
| 798 | } |
| 799 | if let Some(headers) = provider_config.http_headers.as_ref() { |
| 800 | for (name, value) in headers { |
| 801 | if is_upstream_auth_header(name) { |
| 802 | push_model_bound_secret(&mut values, Some(value)); |
| 803 | } |
| 804 | } |
| 805 | } |
| 806 | } |
| 807 | } |
| 808 | |
| 809 | // The decision router's TypeSafe key is no chat provider's key; its env |
| 810 | // form must still never reach a model. (`for_decision_route` adds the key |
| 811 | // from every source to its own client.) |
| 812 | if let Ok(value) = std::env::var(system_one::TYPESAFE_API_KEY_ENV) { |
| 813 | push_model_bound_secret(&mut values, Some(&value)); |
| 814 | } |
| 815 | |
| 816 | for secret in file_backed { |
| 817 | push_model_bound_secret(&mut values, Some(&secret)); |
| 818 | } |
| 819 | |
| 820 | // Replace longer values first in case one credential happens to contain |
| 821 | // another as a prefix. |
| 822 | values.sort_by_key(|value| std::cmp::Reverse(value.len())); |
| 823 | values |
| 824 | } |
| 825 | |
| 826 | /// Everything a catalog probe could have sent that must not come back. |
| 827 | /// |
| 828 | /// Longest first, so a value that contains another is masked whole. |
| 829 | fn catalog_error_secret_values( |
| 830 | active_api_key: &str, |
| 831 | http_headers: &HashMap<String, String>, |
| 832 | model_bound: &[String], |
| 833 | ) -> Vec<String> { |
| 834 | let mut values: Vec<String> = Vec::new(); |
| 835 | let mut push = |value: &str| { |
| 836 | let value = value.trim(); |
| 837 | if !value.is_empty() && !values.iter().any(|existing| existing == value) { |
| 838 | values.push(value.to_string()); |
| 839 | } |
| 840 | }; |
| 841 | // No length floor here, unlike `push_model_bound_secret`: a short key |
| 842 | // echoed back by an untrusted endpoint is still a leaked key. The cost of |
| 843 | // being wrong is a suppressed message, which is what this path did before. |
| 844 | push(active_api_key); |
| 845 | for value in http_headers.values() { |
| 846 | push(value); |
| 847 | } |
| 848 | for value in model_bound { |
| 849 | push(value); |
| 850 | } |
| 851 | values.sort_by_key(|value| std::cmp::Reverse(value.len())); |
| 852 | values |
| 853 | } |
| 854 | |
| 855 | /// The opaque values in a request's URL query — the pagination cursor. |
| 856 | /// |
| 857 | /// Collected in both forms: decoded, as a provider that parsed the cursor |
| 858 | /// would echo it, and raw, as one that quoted the URL back would. |
| 859 | fn request_query_secret_values(url: &reqwest::Url) -> Vec<String> { |
| 860 | let mut values: Vec<String> = Vec::new(); |
| 861 | let mut push = |value: String| { |
| 862 | if !value.trim().is_empty() && !values.contains(&value) { |
| 863 | values.push(value); |
| 864 | } |
| 865 | }; |
| 866 | for (_, value) in url.query_pairs() { |
| 867 | push(value.into_owned()); |
| 868 | } |
| 869 | for pair in url.query().unwrap_or_default().split('&') { |
| 870 | if let Some((_, value)) = pair.split_once('=') { |
| 871 | push(value.to_string()); |
| 872 | } |
| 873 | } |
| 874 | values.sort_by_key(|value| std::cmp::Reverse(value.len())); |
| 875 | values |
| 876 | } |
| 877 | |
| 878 | pub fn redact_model_bound_text(text: &str, exact_secret_values: &[String]) -> String { |
| 879 | let mut redacted = text.to_string(); |
| 880 | for secret in exact_secret_values { |
| 881 | redacted = redacted.replace(secret, codewhale_config::persistence::REDACTED); |
| 882 | } |
| 883 | // Tool results feed exact-match edits, so only credential-shaped values |
| 884 | // are masked here; key-only hits (`password: credentials?.password`) stay |
| 885 | // byte-exact. Logs and previews keep the broad key-based scrubber. |
| 886 | codewhale_config::persistence::redact_model_bound_secrets(&redacted) |
| 887 | } |
| 888 | |
| 889 | pub fn redact_json_model_bound_text( |
| 890 | value: &serde_json::Value, |
| 891 | secrets: &[String], |
| 892 | ) -> serde_json::Value { |
| 893 | fn mask_exact_values(value: &mut serde_json::Value, secrets: &[String]) { |
| 894 | match value { |
| 895 | serde_json::Value::String(text) => *text = redact_model_bound_text(text, secrets), |
| 896 | serde_json::Value::Array(values) => { |
| 897 | for value in values { |
| 898 | mask_exact_values(value, secrets); |
| 899 | } |
| 900 | } |
| 901 | serde_json::Value::Object(values) => { |
| 902 | for value in values.values_mut() { |
| 903 | mask_exact_values(value, secrets); |
| 904 | } |
| 905 | } |
| 906 | _ => {} |
| 907 | } |
| 908 | } |
| 909 | // Preserve sensitive-key masking and the existing recursion-depth bound. |
| 910 | let mut redacted = codewhale_config::persistence::redact_json_model_bound_secrets(value); |
| 911 | mask_exact_values(&mut redacted, secrets); |
| 912 | redacted |
| 913 | } |
| 914 | |
| 915 | // === Helpers === |
| 916 | |
| 917 | /// How much of a provider's HTTP error body may be shown to the user. |
| 918 | /// |
| 919 | /// The catalog probe is the one request that contacts a `base_url` the user |
| 920 | /// typed during setup, and its URL carries an opaque pagination cursor, so a |
| 921 | /// provider — or anything answering at that URL — can echo a key, a custom |
| 922 | /// header value or the cursor back inside an error body. #3385 answered that |
| 923 | /// by discarding the body entirely, and the cost of the blunt version was |
| 924 | /// #6173: Gemini's real reason ("User location is not supported for the API |
| 925 | /// use") reached the user as `Invalid request (400): ` with nothing after the |
| 926 | /// colon, so a geo-block, a bad key and a wrong endpoint were indistinguishable. |
| 927 | pub(super) enum ErrorBodyDisclosure { |
| 928 | /// The endpoint is already established. Surface the provider's message. |
| 929 | Full, |
| 930 | /// Untrusted endpoint. Surface only what survives redaction — and nothing |
| 931 | /// at all if a known secret is still in the result. |
| 932 | Guarded { request_secrets: Vec<String> }, |
| 933 | } |
| 934 | |
| 935 | /// Read/overall timeout for the shared client's non-streaming requests |
| 936 | /// (`/models` listing, catalog refresh, health probes). Streaming requests |
| 937 | /// keep their own idle-timeout envelope; without this, a provider that accepts |
| 938 | /// the connection and never answers hangs model-list, catalog refresh, and |
| 939 | /// health checks forever (ops R4). |
| 940 | pub(super) const NON_STREAMING_HTTP_TIMEOUT: Duration = Duration::from_secs(30); |
| 941 | pub const PROVIDER_CATALOG_MAX_RESPONSE_BYTES: usize = 8 * 1024 * 1024; |
| 942 | pub const PROVIDER_CATALOG_MAX_ROWS: usize = 10_000; |
| 943 | |
| 944 | #[derive(Clone, Copy)] |
| 945 | struct ModelsFetchLimits { |
| 946 | bytes: usize, |
| 947 | rows: usize, |
| 948 | pages: usize, |
| 949 | cursor_bytes: usize, |
| 950 | timeout: Duration, |
| 951 | } |
| 952 | |
| 953 | const MODELS_FETCH_LIMITS: ModelsFetchLimits = ModelsFetchLimits { |
| 954 | bytes: PROVIDER_CATALOG_MAX_RESPONSE_BYTES, |
| 955 | rows: PROVIDER_CATALOG_MAX_ROWS, |
| 956 | pages: 1_000, |
| 957 | cursor_bytes: 4_096, |
| 958 | timeout: NON_STREAMING_HTTP_TIMEOUT, |
| 959 | }; |
| 960 | |
| 961 | #[derive(Clone, Copy)] |
| 962 | enum ModelsRequestMode { |
| 963 | Interactive, |
| 964 | Refresh, |
| 965 | } |
| 966 | |
| 967 | #[derive(Debug)] |
| 968 | enum ModelsFetchError { |
| 969 | Catalog(CatalogRefreshError), |
| 970 | Interactive(anyhow::Error), |
| 971 | } |
| 972 | |
| 973 | impl ModelsFetchError { |
| 974 | fn into_interactive(self) -> anyhow::Error { |
| 975 | match self { |
| 976 | Self::Catalog(reason) => anyhow::anyhow!("Failed to list models: {reason:?}"), |
| 977 | Self::Interactive(error) => error, |
| 978 | } |
| 979 | } |
| 980 | |
| 981 | fn into_catalog(self) -> CatalogRefreshError { |
| 982 | match self { |
| 983 | Self::Catalog(reason) => reason, |
| 984 | Self::Interactive(_) => CatalogRefreshError::Network, |
| 985 | } |
| 986 | } |
| 987 | } |
| 988 | |
| 989 | impl From<CatalogRefreshError> for ModelsFetchError { |
| 990 | fn from(reason: CatalogRefreshError) -> Self { |
| 991 | Self::Catalog(reason) |
| 992 | } |
| 993 | } |
| 994 | |
| 995 | // Keep row bytes intact: a Value round trip would silently accept duplicate |
| 996 | // fields that the existing typed provider parsers reject. |
| 997 | #[derive(Deserialize)] |
| 998 | struct ModelsPage<'a> { |
| 999 | #[serde(borrow)] |
| 1000 | data: Option<&'a serde_json::value::RawValue>, |
| 1001 | #[serde(borrow)] |
| 1002 | models: Option<&'a serde_json::value::RawValue>, |
| 1003 | #[serde(default)] |
| 1004 | has_more: bool, |
| 1005 | last_id: Option<String>, |
| 1006 | } |
| 1007 | |
| 1008 | impl<'a> ModelsPage<'a> { |
| 1009 | fn rows(&self) -> Result<&'a serde_json::value::RawValue, CatalogRefreshError> { |
| 1010 | self.data |
| 1011 | .or(self.models) |
| 1012 | .ok_or(CatalogRefreshError::InvalidResponse) |
| 1013 | } |
| 1014 | } |
| 1015 | |
| 1016 | struct BoundedModelsRows(usize); |
| 1017 | |
| 1018 | impl<'de> serde::de::Visitor<'de> for BoundedModelsRows { |
| 1019 | type Value = Vec<Box<serde_json::value::RawValue>>; |
| 1020 | |
| 1021 | fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 1022 | formatter.write_str("a bounded model array") |
| 1023 | } |
| 1024 | |
| 1025 | fn visit_seq<A: serde::de::SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> { |
| 1026 | let mut rows = Vec::new(); |
| 1027 | while rows.len() < self.0 { |
| 1028 | let Some(row) = seq.next_element()? else { |
| 1029 | return Ok(rows); |
| 1030 | }; |
| 1031 | rows.push(row); |
| 1032 | } |
| 1033 | if seq.next_element::<serde::de::IgnoredAny>()?.is_some() { |
| 1034 | return Err(serde::de::Error::custom("model row limit exceeded")); |
| 1035 | } |
| 1036 | Ok(rows) |
| 1037 | } |
| 1038 | } |
| 1039 | |
| 1040 | impl<'de> serde::de::DeserializeSeed<'de> for BoundedModelsRows { |
| 1041 | type Value = Vec<Box<serde_json::value::RawValue>>; |
| 1042 | |
| 1043 | fn deserialize<D: serde::Deserializer<'de>>( |
| 1044 | self, |
| 1045 | deserializer: D, |
| 1046 | ) -> Result<Self::Value, D::Error> { |
| 1047 | deserializer.deserialize_seq(self) |
| 1048 | } |
| 1049 | } |
| 1050 | |
| 1051 | /// One complete traversal, independent of provider row parsing and transport |
| 1052 | /// retry policy. Only a verified endpoint contract supplies a cursor query key; |
| 1053 | /// generation wire format alone does not prove a model-list dialect. |
| 1054 | async fn collect_models_document<F, Fut>( |
| 1055 | endpoint: reqwest::Url, |
| 1056 | cursor_query: Option<&str>, |
| 1057 | limits: ModelsFetchLimits, |
| 1058 | mut fetch: F, |
| 1059 | ) -> Result<(String, tokio::time::Instant), ModelsFetchError> |
| 1060 | where |
| 1061 | F: FnMut(reqwest::Url) -> Fut, |
| 1062 | Fut: std::future::Future<Output = Result<reqwest::Response, ModelsFetchError>>, |
| 1063 | { |
| 1064 | use serde::de::DeserializeSeed; |
| 1065 | let deadline = tokio::time::Instant::now() + limits.timeout; |
| 1066 | let body = tokio::time::timeout_at(deadline, async { |
| 1067 | let mut rows = Vec::new(); |
| 1068 | let mut bytes = 0usize; |
| 1069 | let mut cursor: Option<String> = None; |
| 1070 | let mut seen = std::collections::HashSet::new(); |
| 1071 | for page_index in 0..limits.pages { |
| 1072 | let mut url = endpoint.clone(); |
| 1073 | if let (Some(key), Some(value)) = (cursor_query, cursor.as_deref()) { |
| 1074 | let query: Vec<_> = url |
| 1075 | .query_pairs() |
| 1076 | .filter(|(name, _)| name != key) |
| 1077 | .map(|(name, value)| (name.into_owned(), value.into_owned())) |
| 1078 | .collect(); |
| 1079 | url.query_pairs_mut() |
| 1080 | .clear() |
| 1081 | .extend_pairs(query) |
| 1082 | .append_pair(key, value); |
| 1083 | } |
| 1084 | let response = fetch(url).await?; |
| 1085 | let body = |
| 1086 | bounded_provider_catalog_text(response, limits.bytes.saturating_sub(bytes)).await?; |
| 1087 | bytes += body.len(); |
| 1088 | let page: ModelsPage<'_> = |
| 1089 | serde_json::from_str(&body).map_err(|_| CatalogRefreshError::InvalidResponse)?; |
| 1090 | let page_rows = BoundedModelsRows(limits.rows.saturating_sub(rows.len())) |
| 1091 | .deserialize(&mut serde_json::Deserializer::from_str(page.rows()?.get())) |
| 1092 | .map_err(|_| CatalogRefreshError::InvalidResponse)?; |
| 1093 | rows.extend(page_rows); |
| 1094 | if !page.has_more { |
| 1095 | if tokio::time::Instant::now() >= deadline { |
| 1096 | return Err(CatalogRefreshError::Network.into()); |
| 1097 | } |
| 1098 | if page_index == 0 { |
| 1099 | return Ok(body); |
| 1100 | } |
| 1101 | #[derive(Serialize)] |
| 1102 | struct Document { |
| 1103 | data: Vec<Box<serde_json::value::RawValue>>, |
| 1104 | } |
| 1105 | return serde_json::to_string(&Document { data: rows }) |
| 1106 | .map_err(|_| CatalogRefreshError::InvalidResponse.into()); |
| 1107 | } |
| 1108 | let next = page |
| 1109 | .last_id |
| 1110 | .filter(|value| !value.is_empty() && value.len() <= limits.cursor_bytes) |
| 1111 | .ok_or(CatalogRefreshError::InvalidResponse)?; |
| 1112 | if cursor_query.is_none() || !seen.insert(next.clone()) { |
| 1113 | return Err(CatalogRefreshError::InvalidResponse.into()); |
| 1114 | } |
| 1115 | cursor = Some(next); |
| 1116 | } |
| 1117 | Err(ModelsFetchError::Catalog( |
| 1118 | CatalogRefreshError::InvalidResponse, |
| 1119 | )) |
| 1120 | }) |
| 1121 | .await |
| 1122 | .map_err(|_| CatalogRefreshError::Network)??; |
| 1123 | Ok((body, deadline)) |
| 1124 | } |
| 1125 | |
| 1126 | pub async fn bounded_provider_catalog_text( |
| 1127 | response: reqwest::Response, |
| 1128 | max_bytes: usize, |
| 1129 | ) -> Result<String, CatalogRefreshError> { |
| 1130 | if response |
| 1131 | .content_length() |
| 1132 | .is_some_and(|length| length > max_bytes as u64) |
| 1133 | { |
| 1134 | return Err(CatalogRefreshError::InvalidResponse); |
| 1135 | } |
| 1136 | let mut stream = response.bytes_stream(); |
| 1137 | let mut body = Vec::new(); |
| 1138 | while let Some(chunk) = stream.next().await { |
| 1139 | let chunk = chunk.map_err(|_| CatalogRefreshError::Network)?; |
| 1140 | if body.len().saturating_add(chunk.len()) > max_bytes { |
| 1141 | return Err(CatalogRefreshError::InvalidResponse); |
| 1142 | } |
| 1143 | body.extend_from_slice(&chunk); |
| 1144 | } |
| 1145 | String::from_utf8(body).map_err(|_| CatalogRefreshError::InvalidResponse) |
| 1146 | } |
| 1147 | |
| 1148 | fn validate_base_url_security(base_url: &str, provider_allows_insecure_http: bool) -> Result<()> { |
| 1149 | let display_base_url = redact_url_for_display(base_url); |
| 1150 | let parsed = reqwest::Url::parse(base_url) |
| 1151 | .map_err(|_| anyhow::anyhow!("Refusing invalid base URL '{display_base_url}'"))?; |
| 1152 | let loopback = parsed.host_str().is_some_and(|host| { |
| 1153 | host.eq_ignore_ascii_case("localhost") |
| 1154 | || host |
| 1155 | .trim_matches(['[', ']']) |
| 1156 | .parse::<std::net::IpAddr>() |
| 1157 | .is_ok_and(|address| address.is_loopback()) |
| 1158 | }); |
| 1159 | if parsed.scheme() == "https" || (parsed.scheme() == "http" && loopback) { |
| 1160 | return Ok(()); |
| 1161 | } |
| 1162 | |
| 1163 | if parsed.scheme() == "http" && provider_allows_insecure_http { |
| 1164 | logging::warn( |
| 1165 | "Using insecure HTTP base URL because this provider sets allow_insecure_http = true in config.toml", |
| 1166 | ); |
| 1167 | return Ok(()); |
| 1168 | } |
| 1169 | |
| 1170 | if parsed.scheme() == "http" |
| 1171 | && std::env::var(ALLOW_INSECURE_HTTP_ENV) |
| 1172 | .or_else(|_| std::env::var(LEGACY_ALLOW_INSECURE_HTTP_ENV)) |
| 1173 | .ok() |
| 1174 | .as_deref() |
| 1175 | .is_some_and(|v| v == "1" || v.eq_ignore_ascii_case("true")) |
| 1176 | { |
| 1177 | logging::warn(format!( |
| 1178 | "Using insecure HTTP base URL because {ALLOW_INSECURE_HTTP_ENV} is set" |
| 1179 | )); |
| 1180 | return Ok(()); |
| 1181 | } |
| 1182 | |
| 1183 | if parsed.scheme() == "http" { |
| 1184 | anyhow::bail!( |
| 1185 | "Refusing insecure base URL '{display_base_url}'.\n\ |
| 1186 | \n\ |
| 1187 | Loopback hosts (localhost, 127.0.0.1, [::1]) are auto-allowed.\n\ |
| 1188 | For one trusted local provider (LAN, llama.cpp on a private IP, etc.) set\n\ |
| 1189 | `allow_insecure_http = true` under its `[providers.<name>]` table in config.toml.\n\ |
| 1190 | To allow it for every provider in this shell instead, set the env var\n\ |
| 1191 | `{ALLOW_INSECURE_HTTP_ENV}=1` and re-run.", |
| 1192 | ); |
| 1193 | } |
| 1194 | |
| 1195 | anyhow::bail!( |
| 1196 | "Refusing base URL '{display_base_url}': only HTTPS (or explicitly allowed HTTP) URLs are supported.", |
| 1197 | ) |
| 1198 | } |
| 1199 | |
| 1200 | pub(super) fn versioned_base_url(base_url: &str) -> String { |
| 1201 | let trimmed = base_url.trim_end_matches('/'); |
| 1202 | if base_url_has_version_suffix(trimmed) { |
| 1203 | trimmed.to_string() |
| 1204 | } else { |
| 1205 | format!("{trimmed}/v1") |
| 1206 | } |
| 1207 | } |
| 1208 | |
| 1209 | fn unversioned_base_url(base_url: &str) -> String { |
| 1210 | let trimmed = base_url.trim_end_matches('/'); |
| 1211 | trimmed |
| 1212 | .rsplit_once('/') |
| 1213 | .filter(|(_, segment)| is_version_segment(segment)) |
| 1214 | .map(|(base, _)| base) |
| 1215 | .unwrap_or(trimmed) |
| 1216 | .to_string() |
| 1217 | } |
| 1218 | |
| 1219 | fn base_url_has_version_suffix(trimmed: &str) -> bool { |
| 1220 | let mut segments = trimmed.rsplit('/'); |
| 1221 | let Some(last) = segments.next() else { |
| 1222 | return false; |
| 1223 | }; |
| 1224 | if is_version_segment(last) { |
| 1225 | return true; |
| 1226 | } |
| 1227 | (last.eq_ignore_ascii_case("openai") || last.eq_ignore_ascii_case("compat")) |
| 1228 | && segments.next().is_some_and(is_version_segment) |
| 1229 | } |
| 1230 | |
| 1231 | fn is_version_segment(segment: &str) -> bool { |
| 1232 | if segment.eq_ignore_ascii_case("beta") { |
| 1233 | return true; |
| 1234 | } |
| 1235 | let Some(rest) = segment |
| 1236 | .strip_prefix('v') |
| 1237 | .or_else(|| segment.strip_prefix('V')) |
| 1238 | else { |
| 1239 | return false; |
| 1240 | }; |
| 1241 | let digits = rest |
| 1242 | .strip_suffix("beta") |
| 1243 | .or_else(|| rest.strip_suffix("BETA")) |
| 1244 | .or_else(|| rest.strip_suffix("alpha")) |
| 1245 | .or_else(|| rest.strip_suffix("ALPHA")) |
| 1246 | .unwrap_or(rest); |
| 1247 | !digits.is_empty() && digits.chars().all(|ch| ch.is_ascii_digit()) |
| 1248 | } |
| 1249 | |
| 1250 | pub fn api_url(base_url: &str, path: &str) -> String { |
| 1251 | api_url_with_suffix(base_url, path, None) |
| 1252 | } |
| 1253 | |
| 1254 | fn responses_api_url(base_url: &str, path: ResponsesPathPolicy) -> String { |
| 1255 | match path { |
| 1256 | ResponsesPathPolicy::UnversionedResponses => { |
| 1257 | format!("{}/responses", unversioned_base_url(base_url)) |
| 1258 | } |
| 1259 | ResponsesPathPolicy::VersionedResponses => api_url(base_url, "responses"), |
| 1260 | } |
| 1261 | } |
| 1262 | |
| 1263 | pub(super) fn api_url_with_suffix(base_url: &str, path: &str, path_suffix: Option<&str>) -> String { |
| 1264 | let path = path.trim_start_matches('/'); |
| 1265 | if path.starts_with("beta/") { |
| 1266 | return format!("{}/{}", unversioned_base_url(base_url), path); |
| 1267 | } |
| 1268 | if let ("chat/completions", Some(suffix)) = (path, path_suffix) { |
| 1269 | return format!( |
| 1270 | "{}/{}", |
| 1271 | unversioned_base_url(base_url), |
| 1272 | suffix.trim_start_matches('/') |
| 1273 | ); |
| 1274 | } |
| 1275 | let mut versioned = versioned_base_url(base_url); |
| 1276 | // The /beta suffix is not a real API version — it is an |
| 1277 | // opt-in surface for beta features. Only paths with an |
| 1278 | // explicit `beta/` prefix should hit the beta surface; |
| 1279 | // everything else (models, chat/completions, health, …) |
| 1280 | // must go to the standard /v1 surface. |
| 1281 | if versioned.ends_with("/beta") { |
| 1282 | versioned = format!("{}/v1", unversioned_base_url(base_url)); |
| 1283 | } |
| 1284 | format!("{}/{}", versioned.trim_end_matches('/'), path) |
| 1285 | } |
| 1286 | |
| 1287 | /// Route strict DeepSeek tool requests through the beta Chat Completions |
| 1288 | /// surface while keeping every ordinary request on the canonical `/v1` path. |
| 1289 | /// |
| 1290 | /// DeepSeek requires its `/beta` base URL when a function opts into |
| 1291 | /// `strict: true`. The configured route URL remains semantic here because |
| 1292 | /// unit tests may replace only the transport origin with a local capture |
| 1293 | /// server. |
| 1294 | /// |
| 1295 | /// Source: <https://api-docs.deepseek.com/guides/tool_calls/> (verified 2026-07-22). |
| 1296 | fn chat_completions_url( |
| 1297 | transport_base_url: &str, |
| 1298 | route_base_url: &str, |
| 1299 | provider: ProviderKind, |
| 1300 | path_suffix: Option<&str>, |
| 1301 | body: &Value, |
| 1302 | ) -> String { |
| 1303 | let uses_deepseek_beta = matches!(provider, ProviderKind::Deepseek) |
| 1304 | && is_official_deepseek_beta_base_url(route_base_url) |
| 1305 | && body_uses_strict_tools(body) |
| 1306 | && path_suffix.is_none(); |
| 1307 | let path = if uses_deepseek_beta { |
| 1308 | "beta/chat/completions" |
| 1309 | } else { |
| 1310 | "chat/completions" |
| 1311 | }; |
| 1312 | api_url_with_suffix(transport_base_url, path, path_suffix) |
| 1313 | } |
| 1314 | |
| 1315 | fn is_official_deepseek_beta_base_url(base_url: &str) -> bool { |
| 1316 | matches!( |
| 1317 | base_url.trim_end_matches('/').to_ascii_lowercase().as_str(), |
| 1318 | "https://api.deepseek.com/beta" | "https://api.deepseeki.com/beta" |
| 1319 | ) |
| 1320 | } |
| 1321 | |
| 1322 | fn body_uses_strict_tools(body: &Value) -> bool { |
| 1323 | body.get("tools") |
| 1324 | .and_then(Value::as_array) |
| 1325 | .is_some_and(|tools| { |
| 1326 | tools |
| 1327 | .iter() |
| 1328 | .any(|tool| tool.pointer("/function/strict").and_then(Value::as_bool) == Some(true)) |
| 1329 | }) |
| 1330 | } |
| 1331 | |
| 1332 | fn normalize_audio_format(format: &str) -> String { |
| 1333 | let normalized = format.trim().to_ascii_lowercase(); |
| 1334 | if normalized.is_empty() { |
| 1335 | "wav".to_string() |
| 1336 | } else { |
| 1337 | normalized |
| 1338 | } |
| 1339 | } |
| 1340 | |
| 1341 | fn parse_speech_audio_response(payload: &Value) -> Result<(Vec<u8>, Option<String>)> { |
| 1342 | let audio = payload |
| 1343 | .get("choices") |
| 1344 | .and_then(Value::as_array) |
| 1345 | .and_then(|choices| choices.first()) |
| 1346 | .and_then(|choice| { |
| 1347 | choice |
| 1348 | .get("message") |
| 1349 | .and_then(|message| message.get("audio")) |
| 1350 | .or_else(|| choice.get("delta").and_then(|delta| delta.get("audio"))) |
| 1351 | }) |
| 1352 | .or_else(|| payload.get("audio")) |
| 1353 | .context("Speech synthesis response did not include choices[0].message.audio")?; |
| 1354 | |
| 1355 | let data = audio |
| 1356 | .get("data") |
| 1357 | .and_then(Value::as_str) |
| 1358 | .context("Speech synthesis response did not include audio.data")? |
| 1359 | .trim(); |
| 1360 | let data = data |
| 1361 | .split_once(',') |
| 1362 | .map(|(_, base64)| base64.trim()) |
| 1363 | .unwrap_or(data); |
| 1364 | let audio_bytes = general_purpose::STANDARD |
| 1365 | .decode(data) |
| 1366 | .context("Failed to decode speech audio base64 data")?; |
| 1367 | let transcript = audio |
| 1368 | .get("transcript") |
| 1369 | .and_then(Value::as_str) |
| 1370 | .map(str::to_string); |
| 1371 | |
| 1372 | Ok((audio_bytes, transcript)) |
| 1373 | } |
| 1374 | |
| 1375 | fn build_speech_synthesis_body( |
| 1376 | model: &str, |
| 1377 | text: &str, |
| 1378 | instruction: Option<&str>, |
| 1379 | audio: Value, |
| 1380 | ) -> Value { |
| 1381 | let mut messages = Vec::new(); |
| 1382 | if let Some(instruction) = instruction.map(str::trim).filter(|value| !value.is_empty()) { |
| 1383 | messages.push(json!({ |
| 1384 | "role": "user", |
| 1385 | "content": instruction, |
| 1386 | })); |
| 1387 | } |
| 1388 | messages.push(json!({ |
| 1389 | "role": "assistant", |
| 1390 | "content": text, |
| 1391 | })); |
| 1392 | |
| 1393 | json!({ |
| 1394 | "model": model, |
| 1395 | "messages": messages, |
| 1396 | "audio": audio, |
| 1397 | }) |
| 1398 | } |
| 1399 | |
| 1400 | // === CodewhaleClient === |
| 1401 | |
| 1402 | struct CapturedRootCert { |
| 1403 | path: String, |
| 1404 | bytes: std::io::Result<Vec<u8>>, |
| 1405 | } |
| 1406 | |
| 1407 | enum CapturedRouteCredentials { |
| 1408 | Codex(codewhale_runtime::oauth::OwnedOAuthCredentials), |
| 1409 | Xai(codewhale_runtime::oauth::OwnedOAuthCredentials), |
| 1410 | ApiKey { |
| 1411 | api_key: String, |
| 1412 | api_key_source: String, |
| 1413 | account_owner: Option<String>, |
| 1414 | }, |
| 1415 | } |
| 1416 | |
| 1417 | pub(crate) struct CapturedClientPreflight { |
| 1418 | identity: ProviderIdentity, |
| 1419 | base_url: String, |
| 1420 | credentials: CapturedRouteCredentials, |
| 1421 | model_bound_secrets: Vec<String>, |
| 1422 | root_cert: Option<CapturedRootCert>, |
| 1423 | } |
| 1424 | |
| 1425 | struct AdmittedClientRoute { |
| 1426 | go_route: Option<(codewhale_config::route::CatalogConnection, String)>, |
| 1427 | identity: ProviderIdentity, |
| 1428 | plugin_provider: Option<Box<codewhale_runtime::config::ProviderConfig>>, |
| 1429 | base_url: String, |
| 1430 | openrouter_vendor: Option<String>, |
| 1431 | } |
| 1432 | |
| 1433 | /// Read `SSL_CERT_FILE` and add its contents as extra root |
| 1434 | /// certificates on the reqwest builder (#418). Tries the PEM-bundle |
| 1435 | /// parser first (covers single-cert files too), then falls back to |
| 1436 | /// DER. All failures log a warning and return the builder unchanged |
| 1437 | /// so a malformed env var degrades gracefully. |
| 1438 | fn capture_ssl_cert_file() -> Option<CapturedRootCert> { |
| 1439 | let cert_path = std::env::var("SSL_CERT_FILE").ok()?; |
| 1440 | if cert_path.is_empty() { |
| 1441 | return None; |
| 1442 | } |
| 1443 | let bytes = std::fs::read(&cert_path); |
| 1444 | Some(CapturedRootCert { |
| 1445 | path: cert_path, |
| 1446 | bytes, |
| 1447 | }) |
| 1448 | } |
| 1449 | |
| 1450 | fn add_captured_root_cert( |
| 1451 | mut builder: reqwest::ClientBuilder, |
| 1452 | cert: &CapturedRootCert, |
| 1453 | ) -> reqwest::ClientBuilder { |
| 1454 | let bytes = match &cert.bytes { |
| 1455 | Ok(bytes) => bytes, |
| 1456 | Err(err) => { |
| 1457 | logging::warn(format!( |
| 1458 | "SSL_CERT_FILE={} could not be read: {err}", |
| 1459 | cert.path |
| 1460 | )); |
| 1461 | return builder; |
| 1462 | } |
| 1463 | }; |
| 1464 | |
| 1465 | if let Ok(certs) = reqwest::Certificate::from_pem_bundle(bytes) { |
| 1466 | let added = certs.len(); |
| 1467 | for root in certs { |
| 1468 | builder = builder.add_root_certificate(root); |
| 1469 | } |
| 1470 | logging::info(format!( |
| 1471 | "SSL_CERT_FILE={} loaded ({added} cert(s))", |
| 1472 | cert.path |
| 1473 | )); |
| 1474 | return builder; |
| 1475 | } |
| 1476 | |
| 1477 | match reqwest::Certificate::from_der(bytes) { |
| 1478 | Ok(root) => { |
| 1479 | builder = builder.add_root_certificate(root); |
| 1480 | logging::info(format!("SSL_CERT_FILE={} loaded (1 DER cert)", cert.path)); |
| 1481 | } |
| 1482 | Err(err) => { |
| 1483 | logging::warn(format!( |
| 1484 | "SSL_CERT_FILE={} could not be parsed as PEM bundle or DER: {err}", |
| 1485 | cert.path |
| 1486 | )); |
| 1487 | } |
| 1488 | } |
| 1489 | builder |
| 1490 | } |
| 1491 | |
| 1492 | /// Admit a complete response's tool pairing ids before hooks, approvals or |
| 1493 | /// replayable history. Use the protocol frozen with the actual request. |
| 1494 | pub fn validate_tool_call_ids_for_protocol<'a>( |
| 1495 | protocol: WireFormat, |
| 1496 | ids: impl IntoIterator<Item = &'a str>, |
| 1497 | ) -> Result<()> { |
| 1498 | let mut seen = std::collections::HashSet::new(); |
| 1499 | for id in ids { |
| 1500 | let pairing_id = if protocol == WireFormat::Responses { |
| 1501 | responses::parse_tool_use_id(id).0 |
| 1502 | } else { |
| 1503 | id.to_string() |
| 1504 | }; |
| 1505 | if pairing_id.trim().is_empty() { |
| 1506 | anyhow::bail!("Provider returned a tool call without a pairing id"); |
| 1507 | } |
| 1508 | if !seen.insert(pairing_id) { |
| 1509 | anyhow::bail!("Provider returned duplicate tool call pairing ids in one response"); |
| 1510 | } |
| 1511 | } |
| 1512 | Ok(()) |
| 1513 | } |
| 1514 | |
| 1515 | impl CodewhaleClient { |
| 1516 | pub fn wire_format(&self) -> WireFormat { |
| 1517 | self.wire_format |
| 1518 | } |
| 1519 | |
| 1520 | #[cfg(any(test, feature = "test-support"))] |
| 1521 | pub fn validate_tool_call_ids<'a>(&self, ids: impl IntoIterator<Item = &'a str>) -> Result<()> { |
| 1522 | validate_tool_call_ids_for_protocol(self.wire_format, ids) |
| 1523 | } |
| 1524 | |
| 1525 | fn is_local_ds4_model(&self, model: &str) -> bool { |
| 1526 | self.api_provider == ProviderKind::Custom |
| 1527 | && self |
| 1528 | .admitted_identity |
| 1529 | .key |
| 1530 | .as_str() |
| 1531 | .eq_ignore_ascii_case("ds4") |
| 1532 | && codewhale_runtime::config::base_url_uses_local_host(&self.base_url) |
| 1533 | && matches!( |
| 1534 | model.trim().to_ascii_lowercase().as_str(), |
| 1535 | "deepseek-v4-flash" | "deepseek-v4-pro" |
| 1536 | ) |
| 1537 | } |
| 1538 | |
| 1539 | /// DS4 is configured as a named custom route so its endpoint and billing |
| 1540 | /// identity remain exact, but its chat payload deliberately speaks the |
| 1541 | /// first-party DeepSeek reasoning/tool dialect that DS4 implements. |
| 1542 | fn chat_shape_provider(&self, model: &str) -> ProviderKind { |
| 1543 | if self.is_local_ds4_model(model) { |
| 1544 | ProviderKind::Deepseek |
| 1545 | } else { |
| 1546 | self.api_provider |
| 1547 | } |
| 1548 | } |
| 1549 | |
| 1550 | /// Create a DeepSeek client from CLI configuration. |
| 1551 | pub fn new(config: &Config) -> Result<Self> { |
| 1552 | let identity = config |
| 1553 | .active_provider_identity() |
| 1554 | .map_err(anyhow::Error::msg)?; |
| 1555 | let api_provider = identity.provider; |
| 1556 | let model_aware = api_provider.provider().wire_policy() |
| 1557 | == codewhale_config::provider::WirePolicy::ModelAware; |
| 1558 | let default_model = config.default_model(); |
| 1559 | let unresolved_local_model = api_provider == ProviderKind::Ollama |
| 1560 | && matches!(default_model.trim(), "" | "auto" | "unknown"); |
| 1561 | if model_aware || unresolved_local_model { |
| 1562 | let route = |
| 1563 | crate::route_runtime::resolve_runtime_route_for_identity(config, &identity, None) |
| 1564 | .map_err(anyhow::Error::msg)?; |
| 1565 | return Self::from_candidate(&route.config, &route.candidate) |
| 1566 | .map(|client| client.with_context_window(route.context_window)); |
| 1567 | } |
| 1568 | let wire_format = provider_wire_format_for_config(&identity, Some(config)); |
| 1569 | let resolved = match crate::route_runtime::resolve_runtime_route_for_identity( |
| 1570 | config, |
| 1571 | &identity, |
| 1572 | Some(&default_model), |
| 1573 | ) { |
| 1574 | Ok(route) => Some(route), |
| 1575 | Err(error) if wire_format == WireFormat::Responses => { |
| 1576 | return Err(anyhow::Error::msg(error)); |
| 1577 | } |
| 1578 | Err(_) => None, |
| 1579 | }; |
| 1580 | let route_limits = resolved |
| 1581 | .as_ref() |
| 1582 | .and_then(|route| crate::route_budget::known_route_limits(route.candidate.limits())); |
| 1583 | let responses_profile_id = resolved |
| 1584 | .as_ref() |
| 1585 | .and_then(|route| route.candidate.responses_profile_id()); |
| 1586 | Self::from_parts( |
| 1587 | config.active_route_base_url(), |
| 1588 | default_model, |
| 1589 | wire_format, |
| 1590 | route_limits, |
| 1591 | responses_profile_id, |
| 1592 | false, |
| 1593 | config, |
| 1594 | ) |
| 1595 | .map(|mut client| { |
| 1596 | client.context_window = resolved.map(|route| route.context_window); |
| 1597 | client |
| 1598 | }) |
| 1599 | } |
| 1600 | |
| 1601 | /// Construct only the model-list probe before a route has a concrete model. |
| 1602 | /// Catalog bootstrap must not depend on the catalog it is about to fetch. |
| 1603 | pub fn for_catalog_refresh(config: &Config) -> Result<Self> { |
| 1604 | let identity = config |
| 1605 | .active_provider_identity() |
| 1606 | .map_err(anyhow::Error::msg)?; |
| 1607 | let public_config; |
| 1608 | let config = if Self::public_catalog_for_route(config, &identity) { |
| 1609 | let mut anonymous = config.clone(); |
| 1610 | anonymous.http_headers = None; |
| 1611 | let entry = anonymous.provider_config_for_mut(&identity)?; |
| 1612 | entry.auth_mode = Some("none".into()); |
| 1613 | entry.http_headers = None; |
| 1614 | public_config = anonymous; |
| 1615 | &public_config |
| 1616 | } else { |
| 1617 | config |
| 1618 | }; |
| 1619 | Self::from_parts( |
| 1620 | config.active_route_base_url(), |
| 1621 | if identity.provider == ProviderKind::OpencodeGo { |
| 1622 | identity.provider.provider().default_model().to_owned() |
| 1623 | } else { |
| 1624 | config.default_model() |
| 1625 | }, |
| 1626 | provider_wire_format_for_config(&identity, Some(config)), |
| 1627 | None, |
| 1628 | None, |
| 1629 | true, |
| 1630 | config, |
| 1631 | ) |
| 1632 | } |
| 1633 | |
| 1634 | pub(crate) fn public_catalog_for_route( |
| 1635 | config: &Config, |
| 1636 | identity: &codewhale_runtime::config::ProviderIdentity, |
| 1637 | ) -> bool { |
| 1638 | identity.provider == ProviderKind::Custom |
| 1639 | && !config.session_provider_keys_only |
| 1640 | && config.required_account_model_owner.is_none() |
| 1641 | && config |
| 1642 | .provider_config_for(identity) |
| 1643 | .is_some_and(|entry| entry.plugin_authority.is_none() && entry.oauth.is_none()) |
| 1644 | && model_listing_is_public(&config.base_url_for_route(identity)) |
| 1645 | } |
| 1646 | |
| 1647 | /// Create a DeepSeek client whose transport is bound to a runtime-resolved |
| 1648 | /// route (#3384). |
| 1649 | /// |
| 1650 | /// The base URL and default model come from the executable `candidate`, so |
| 1651 | /// the client talks to exactly the endpoint and wire model the resolver |
| 1652 | /// chose instead of re-deriving them from `Config`. Secrets stay in |
| 1653 | /// `Config`: `ReadyRouteCandidate` is secret-free by design (it carries only |
| 1654 | /// an auth-source *class*), so the API key and provider are still read from |
| 1655 | /// `config`. |
| 1656 | pub fn from_candidate(config: &Config, candidate: &ReadyRouteCandidate) -> Result<Self> { |
| 1657 | let admitted = Self::admit_candidate_route(config, candidate)?; |
| 1658 | let captured = |
| 1659 | Self::capture_route_preflight_inputs(config, &admitted.identity, &admitted.base_url)?; |
| 1660 | Self::from_admitted( |
| 1661 | config, |
| 1662 | admitted, |
| 1663 | captured, |
| 1664 | candidate.wire_model_id().as_str().to_string(), |
| 1665 | candidate.protocol(), |
| 1666 | crate::route_budget::known_route_limits(candidate.limits()), |
| 1667 | candidate.responses_profile_id(), |
| 1668 | false, |
| 1669 | ) |
| 1670 | } |
| 1671 | |
| 1672 | pub(crate) fn from_candidate_captured( |
| 1673 | config: &Config, |
| 1674 | candidate: &ReadyRouteCandidate, |
| 1675 | captured: CapturedClientPreflight, |
| 1676 | ) -> Result<Self> { |
| 1677 | let admitted = Self::admit_candidate_route(config, candidate)?; |
| 1678 | Self::from_admitted( |
| 1679 | config, |
| 1680 | admitted, |
| 1681 | captured, |
| 1682 | candidate.wire_model_id().as_str().to_string(), |
| 1683 | candidate.protocol(), |
| 1684 | crate::route_budget::known_route_limits(candidate.limits()), |
| 1685 | candidate.responses_profile_id(), |
| 1686 | false, |
| 1687 | ) |
| 1688 | } |
| 1689 | |
| 1690 | pub(crate) async fn capture_candidate_preflight( |
| 1691 | config: Box<Config>, |
| 1692 | candidate: &ReadyRouteCandidate, |
| 1693 | ) -> Result<(Box<Config>, CapturedClientPreflight)> { |
| 1694 | let admitted = Self::admit_candidate_route(&config, candidate)?; |
| 1695 | codewhale_runtime::runtime_control::owner_work(move || { |
| 1696 | let captured = Self::capture_route_preflight_inputs( |
| 1697 | &config, |
| 1698 | &admitted.identity, |
| 1699 | &admitted.base_url, |
| 1700 | )?; |
| 1701 | Ok((config, captured)) |
| 1702 | }) |
| 1703 | .await |
| 1704 | .map_err(|error| anyhow::anyhow!("route preflight worker failed: {error}")) |
| 1705 | } |
| 1706 | |
| 1707 | fn capture_route_preflight_inputs( |
| 1708 | config: &Config, |
| 1709 | identity: &ProviderIdentity, |
| 1710 | base_url: &str, |
| 1711 | ) -> Result<CapturedClientPreflight> { |
| 1712 | Ok(CapturedClientPreflight { |
| 1713 | identity: identity.clone(), |
| 1714 | base_url: base_url.to_string(), |
| 1715 | credentials: Self::capture_route_credentials(config, identity, base_url)?, |
| 1716 | model_bound_secrets: capture_file_backed_model_bound_secret_values(), |
| 1717 | root_cert: capture_ssl_cert_file(), |
| 1718 | }) |
| 1719 | } |
| 1720 | |
| 1721 | fn admit_candidate_route( |
| 1722 | config: &Config, |
| 1723 | candidate: &ReadyRouteCandidate, |
| 1724 | ) -> Result<AdmittedClientRoute> { |
| 1725 | let identity = config |
| 1726 | .active_provider_identity() |
| 1727 | .map_err(anyhow::Error::msg)?; |
| 1728 | anyhow::ensure!( |
| 1729 | candidate.provider_kind() == identity.provider, |
| 1730 | "resolved candidate does not match admitted provider kind" |
| 1731 | ); |
| 1732 | let endpoint = candidate.endpoint(); |
| 1733 | let model = candidate.wire_model_id().as_str(); |
| 1734 | if let Some(connection) = &endpoint.catalog_connection { |
| 1735 | let base = config.base_url_for_route(&identity); |
| 1736 | anyhow::ensure!( |
| 1737 | identity.provider == ProviderKind::OpencodeGo |
| 1738 | && identity.key.as_str() == connection.identity |
| 1739 | && base == connection.base_url, |
| 1740 | "Model catalog connection changed" |
| 1741 | ); |
| 1742 | let (binding, _) = crate::provider_catalog_live::inventory_scope(config, &identity) |
| 1743 | .map_err(anyhow::Error::msg)?; |
| 1744 | anyhow::ensure!( |
| 1745 | binding == connection.binding, |
| 1746 | "Go connection credentials changed. Refresh models and reselect this route." |
| 1747 | ); |
| 1748 | anyhow::ensure!( |
| 1749 | crate::provider_catalog_live::go_route_is_current( |
| 1750 | connection, |
| 1751 | model, |
| 1752 | &endpoint.endpoint_key, |
| 1753 | &endpoint.base_url, |
| 1754 | ), |
| 1755 | "Refresh the authenticated Go models for this connection" |
| 1756 | ); |
| 1757 | } |
| 1758 | let mut admitted = Self::admit_client_route(config, endpoint.base_url.clone())?; |
| 1759 | admitted.go_route = endpoint |
| 1760 | .catalog_connection |
| 1761 | .as_ref() |
| 1762 | .map(|connection| (connection.clone(), endpoint.endpoint_key.clone())); |
| 1763 | Self::validate_admitted_route( |
| 1764 | config, |
| 1765 | &admitted, |
| 1766 | model, |
| 1767 | endpoint.catalog_connection.is_some(), |
| 1768 | )?; |
| 1769 | Ok(admitted) |
| 1770 | } |
| 1771 | |
| 1772 | fn validate_admitted_route( |
| 1773 | config: &Config, |
| 1774 | admitted: &AdmittedClientRoute, |
| 1775 | default_model: &str, |
| 1776 | authenticated_model: bool, |
| 1777 | ) -> Result<()> { |
| 1778 | let api_provider = admitted.identity.provider; |
| 1779 | let base_url = admitted.base_url.as_str(); |
| 1780 | if api_provider == ProviderKind::OpenaiCodex { |
| 1781 | anyhow::ensure!( |
| 1782 | !reqwest::Url::parse(base_url) |
| 1783 | .ok() |
| 1784 | .is_some_and(|url| url.host_str() == Some("chatgpt.com")), |
| 1785 | "The legacy ChatGPT backend route is retired. Use https://api.openai.com/v1 and run codewhale auth chatgpt." |
| 1786 | ); |
| 1787 | } |
| 1788 | if api_provider == ProviderKind::OpencodeGo && !authenticated_model { |
| 1789 | validate_route(api_provider, default_model).map_err(anyhow::Error::msg)?; |
| 1790 | } |
| 1791 | anyhow::ensure!( |
| 1792 | api_provider != ProviderKind::OpenaiCodex |
| 1793 | || crate::pricing::is_official_chatgpt_api(base_url) |
| 1794 | || config.provider_uses_custom_endpoint(&admitted.identity), |
| 1795 | "Refusing to send an official ChatGPT grant to a different endpoint" |
| 1796 | ); |
| 1797 | Ok(()) |
| 1798 | } |
| 1799 | |
| 1800 | fn admit_client_route(config: &Config, base_url: String) -> Result<AdmittedClientRoute> { |
| 1801 | let admitted_identity = config |
| 1802 | .active_provider_identity() |
| 1803 | .map_err(anyhow::Error::msg)?; |
| 1804 | let api_provider = admitted_identity.provider; |
| 1805 | anyhow::ensure!( |
| 1806 | api_provider != ProviderKind::Antigravity, |
| 1807 | codewhale_config::LEGACY_ANTIGRAVITY_TOMBSTONE_MESSAGE |
| 1808 | ); |
| 1809 | config |
| 1810 | .verify_provider_identity(&admitted_identity) |
| 1811 | .map_err(anyhow::Error::msg)?; |
| 1812 | let plugin_provider = config |
| 1813 | .provider_config_for(&admitted_identity) |
| 1814 | .filter(|entry| entry.plugin_authority.is_some()) |
| 1815 | .cloned() |
| 1816 | .map(Box::new); |
| 1817 | if let Some(entry) = &plugin_provider { |
| 1818 | anyhow::ensure!( |
| 1819 | !config.session_provider_keys_only, |
| 1820 | "Stored plugin authorization is unavailable under session-only provider key policy" |
| 1821 | ); |
| 1822 | anyhow::ensure!( |
| 1823 | entry.oauth.is_some() |
| 1824 | && config.auth_mode_for_provider(&admitted_identity).as_deref() |
| 1825 | == Some("oauth"), |
| 1826 | "plugin provider requires host-managed OAuth" |
| 1827 | ); |
| 1828 | } |
| 1829 | let base_url = if plugin_provider.is_some() { |
| 1830 | let reviewed = config.base_url_for_route(&admitted_identity); |
| 1831 | anyhow::ensure!( |
| 1832 | reqwest::Url::parse(&base_url)? == reqwest::Url::parse(&reviewed)?, |
| 1833 | "plugin candidate changed its reviewed provider endpoint" |
| 1834 | ); |
| 1835 | reviewed |
| 1836 | } else { |
| 1837 | base_url |
| 1838 | }; |
| 1839 | let openrouter_vendor = config.openrouter_vendor()?; |
| 1840 | Ok(AdmittedClientRoute { |
| 1841 | go_route: None, |
| 1842 | identity: admitted_identity, |
| 1843 | plugin_provider, |
| 1844 | base_url, |
| 1845 | openrouter_vendor, |
| 1846 | }) |
| 1847 | } |
| 1848 | |
| 1849 | fn capture_route_credentials( |
| 1850 | config: &Config, |
| 1851 | identity: &ProviderIdentity, |
| 1852 | base_url: &str, |
| 1853 | ) -> Result<CapturedRouteCredentials> { |
| 1854 | if identity.provider == ProviderKind::OpenaiCodex |
| 1855 | && crate::pricing::is_official_chatgpt_api(base_url) |
| 1856 | { |
| 1857 | return Ok(CapturedRouteCredentials::Codex(config.codex_credentials()?)); |
| 1858 | } |
| 1859 | if let Some(credentials) = config.xai_oauth_route_credentials() { |
| 1860 | return Ok(CapturedRouteCredentials::Xai(credentials?)); |
| 1861 | } |
| 1862 | let ((api_key, api_key_source), account_owner) = |
| 1863 | config.active_route_api_key_with_owner()?; |
| 1864 | Ok(CapturedRouteCredentials::ApiKey { |
| 1865 | api_key, |
| 1866 | api_key_source, |
| 1867 | account_owner, |
| 1868 | }) |
| 1869 | } |
| 1870 | |
| 1871 | fn from_parts( |
| 1872 | base_url: String, |
| 1873 | default_model: String, |
| 1874 | wire_format: WireFormat, |
| 1875 | route_limits: Option<RouteLimits>, |
| 1876 | responses_profile_id: Option<ResponsesProfileId>, |
| 1877 | catalog_probe: bool, |
| 1878 | config: &Config, |
| 1879 | ) -> Result<Self> { |
| 1880 | let admitted = Self::admit_client_route(config, base_url)?; |
| 1881 | Self::validate_admitted_route(config, &admitted, &default_model, false)?; |
| 1882 | let captured = |
| 1883 | Self::capture_route_preflight_inputs(config, &admitted.identity, &admitted.base_url)?; |
| 1884 | Self::from_admitted( |
| 1885 | config, |
| 1886 | admitted, |
| 1887 | captured, |
| 1888 | default_model, |
| 1889 | wire_format, |
| 1890 | route_limits, |
| 1891 | responses_profile_id, |
| 1892 | catalog_probe, |
| 1893 | ) |
| 1894 | } |
| 1895 | |
| 1896 | /// Shared constructor body for every admitted route. |
| 1897 | /// |
| 1898 | /// Auth, provider, retry, headers, and timeouts come from `config`. |
| 1899 | /// The route, wire format, and Responses profile are the entry point's inputs. |
| 1900 | fn from_admitted( |
| 1901 | config: &Config, |
| 1902 | admitted: AdmittedClientRoute, |
| 1903 | captured: CapturedClientPreflight, |
| 1904 | default_model: String, |
| 1905 | wire_format: WireFormat, |
| 1906 | route_limits: Option<RouteLimits>, |
| 1907 | responses_profile_id: Option<ResponsesProfileId>, |
| 1908 | catalog_probe: bool, |
| 1909 | ) -> Result<Self> { |
| 1910 | anyhow::ensure!( |
| 1911 | admitted.identity == captured.identity && admitted.base_url == captured.base_url, |
| 1912 | "captured route preflight inputs do not match the admitted route" |
| 1913 | ); |
| 1914 | let credentials = captured.credentials; |
| 1915 | let model_bound_secrets = captured.model_bound_secrets; |
| 1916 | let root_cert = captured.root_cert; |
| 1917 | let admitted_identity = admitted.identity; |
| 1918 | let api_provider = admitted_identity.provider; |
| 1919 | let responses_profile_id = admit_responses_profile( |
| 1920 | api_provider, |
| 1921 | wire_format, |
| 1922 | responses_profile_id, |
| 1923 | catalog_probe, |
| 1924 | )?; |
| 1925 | let context_window_override = config.context_window_for_provider_config(&admitted_identity); |
| 1926 | let model_context_windows = config |
| 1927 | .model_context_windows_for(&admitted_identity) |
| 1928 | .cloned(); |
| 1929 | let plugin_provider = admitted.plugin_provider; |
| 1930 | let base_url = admitted.base_url; |
| 1931 | let openrouter_vendor = admitted.openrouter_vendor; |
| 1932 | let billing_surface = crate::route_billing::billing_surface_for_dispatch( |
| 1933 | Some(config), |
| 1934 | &admitted_identity, |
| 1935 | Some(&base_url), |
| 1936 | ) |
| 1937 | .map(str::to_string); |
| 1938 | let billing_mode = |
| 1939 | crate::route_billing::for_route_with_endpoint(config, &admitted_identity, &base_url) |
| 1940 | .into(); |
| 1941 | // Guidance and opaque-reasoning scope come from the exact owned |
| 1942 | // credential snapshot this client sends, never a second store read. |
| 1943 | let ( |
| 1944 | (api_key, api_key_source), |
| 1945 | codex_account_id, |
| 1946 | subscription_limit_guidance, |
| 1947 | chatgpt_reasoning_api, |
| 1948 | resume_account_scope, |
| 1949 | ) = match credentials { |
| 1950 | CapturedRouteCredentials::Codex(credentials) => { |
| 1951 | let guidance = codewhale_runtime::oauth::usage_limit_guidance( |
| 1952 | codewhale_runtime::oauth::OAuthProvider::Chatgpt, |
| 1953 | credentials.account_label.as_deref(), |
| 1954 | ); |
| 1955 | let identity = serde_json::to_vec(&( |
| 1956 | credentials.issuer.as_str(), |
| 1957 | credentials.client_id.as_str(), |
| 1958 | credentials |
| 1959 | .account_id |
| 1960 | .as_deref() |
| 1961 | .context("Verified ChatGPT subject is missing")?, |
| 1962 | ))?; |
| 1963 | let reasoning_api = format!( |
| 1964 | "openai-responses-siwc-v1:{}", |
| 1965 | codewhale_runtime::hashing::sha256_hex(&identity), |
| 1966 | ); |
| 1967 | ( |
| 1968 | (credentials.access_token, "ChatGPT sign-in".to_string()), |
| 1969 | credentials.account_id, |
| 1970 | Some(guidance), |
| 1971 | Some(reasoning_api.clone()), |
| 1972 | Some(reasoning_api), |
| 1973 | ) |
| 1974 | } |
| 1975 | CapturedRouteCredentials::Xai(credentials) => { |
| 1976 | let guidance = codewhale_runtime::oauth::usage_limit_guidance( |
| 1977 | codewhale_runtime::oauth::OAuthProvider::Xai, |
| 1978 | credentials.account_label.as_deref(), |
| 1979 | ); |
| 1980 | let scope = credentials |
| 1981 | .account_id |
| 1982 | .as_deref() |
| 1983 | .map(|account| { |
| 1984 | serde_json::to_string(&( |
| 1985 | "xai", |
| 1986 | &credentials.issuer, |
| 1987 | &credentials.client_id, |
| 1988 | account, |
| 1989 | )) |
| 1990 | }) |
| 1991 | .transpose()?; |
| 1992 | ( |
| 1993 | ( |
| 1994 | codewhale_secrets::normalize_api_key(&credentials.access_token), |
| 1995 | codewhale_runtime::config::XAI_OAUTH_KEY_SOURCE.to_string(), |
| 1996 | ), |
| 1997 | None, |
| 1998 | Some(guidance), |
| 1999 | None, |
| 2000 | scope, |
| 2001 | ) |
| 2002 | } |
| 2003 | CapturedRouteCredentials::ApiKey { |
| 2004 | api_key, |
| 2005 | api_key_source, |
| 2006 | account_owner, |
| 2007 | } => ((api_key, api_key_source), None, None, None, account_owner), |
| 2008 | }; |
| 2009 | let model_bound_secret_values = Arc::new(configured_model_bound_secret_values_with( |
| 2010 | config, |
| 2011 | &api_key, |
| 2012 | model_bound_secrets, |
| 2013 | )); |
| 2014 | // The opt-out is effective only after an explicit startup confirmation; |
| 2015 | // every unconfirmed or absent request stays on the safe default. |
| 2016 | let model_bound_masking = !codewhale_config::redaction::effective_masking( |
| 2017 | config.model_bound_redaction(), |
| 2018 | config.loaded_config_path.as_deref(), |
| 2019 | ) |
| 2020 | .is_disabled(); |
| 2021 | validate_base_url_security(&base_url, config.allow_insecure_http())?; |
| 2022 | let retry = config.retry_policy(); |
| 2023 | let stream_idle_timeout = Duration::from_secs(config.stream_chunk_timeout_secs()); |
| 2024 | let stream_open_timeout = config.stream_open_timeout(); |
| 2025 | let force_http1 = config.force_http1(); |
| 2026 | if force_http1 { |
| 2027 | logging::info( |
| 2028 | "HTTP/1.1 pinned (stream configuration or environment) — HTTP/2 disabled", |
| 2029 | ); |
| 2030 | } |
| 2031 | // A newly reviewed plugin destination must not inherit credentials or |
| 2032 | // routing headers from unrelated, global provider configuration. |
| 2033 | let mut http_headers = plugin_provider.as_ref().map_or_else( |
| 2034 | || config.http_headers(), |
| 2035 | |entry| entry.http_headers.clone().unwrap_or_default(), |
| 2036 | ); |
| 2037 | let needs_session = matches!( |
| 2038 | api_provider, |
| 2039 | ProviderKind::OpencodeGo | ProviderKind::OpencodeZen |
| 2040 | ) && !http_headers.iter().any(|(name, value)| { |
| 2041 | name.trim().eq_ignore_ascii_case("x-opencode-session") && !value.trim().is_empty() |
| 2042 | }); |
| 2043 | let automatic_opencode_session = needs_session.then(|| uuid::Uuid::new_v4().to_string()); |
| 2044 | if let Some(session) = &automatic_opencode_session { |
| 2045 | http_headers.insert("x-opencode-session".to_owned(), session.clone()); |
| 2046 | } |
| 2047 | let auth_mode = config.auth_mode_for_provider(&admitted_identity); |
| 2048 | let claude_org = if api_provider == ProviderKind::Anthropic |
| 2049 | && api_key_source == codewhale_config::credentials::CLAUDE_ORG_KEY_SOURCE |
| 2050 | { |
| 2051 | anyhow::ensure!( |
| 2052 | !config.session_provider_keys_only, |
| 2053 | "Claude organization billing is unavailable under session-only provider key policy" |
| 2054 | ); |
| 2055 | Some(Arc::new(claude_org::ClaudeOrgAuth::for_profile( |
| 2056 | config.account_profile.clone(), |
| 2057 | http_headers |
| 2058 | .iter() |
| 2059 | .find(|(name, _)| name.eq_ignore_ascii_case("anthropic-beta")) |
| 2060 | .map(|(_, value)| value.clone()), |
| 2061 | ))) |
| 2062 | } else { |
| 2063 | None |
| 2064 | }; |
| 2065 | let auth_disabled = |
| 2066 | auth_mode_disables_api_key(auth_mode.as_deref()) || claude_org.is_some(); |
| 2067 | if api_provider == ProviderKind::OpencodeGo |
| 2068 | && opencode_catalog::official_listing(&config.base_url_for_route(&admitted_identity)) |
| 2069 | && (auth_disabled || api_key.trim().is_empty()) |
| 2070 | { |
| 2071 | bail!("An authenticated OpenCode Go connection is required"); |
| 2072 | } |
| 2073 | let insecure_skip_tls_verify = config.insecure_skip_tls_verify(); |
| 2074 | let path_suffix = config |
| 2075 | .provider_config_for(&admitted_identity) |
| 2076 | .and_then(|p| p.path_suffix.clone()); |
| 2077 | let reasoning_stream_style = config |
| 2078 | .provider_config_for(&admitted_identity) |
| 2079 | .and_then(|p| p.reasoning_stream_style.clone()); |
| 2080 | let request_concurrency_limit = config.provider_max_concurrency(&admitted_identity); |
| 2081 | |
| 2082 | logging::info(format!("API provider: {}", api_provider.as_str())); |
| 2083 | logging::info(format!( |
| 2084 | "API base URL: {}", |
| 2085 | redact_url_for_display(&base_url) |
| 2086 | )); |
| 2087 | if let Some(suffix) = &path_suffix { |
| 2088 | logging::info(format!("API path suffix override: {suffix}")); |
| 2089 | } |
| 2090 | if !http_headers.is_empty() { |
| 2091 | logging::info(format!( |
| 2092 | "{} custom HTTP header(s) configured", |
| 2093 | http_headers.len() |
| 2094 | )); |
| 2095 | } |
| 2096 | if insecure_skip_tls_verify { |
| 2097 | logging::warn(format!( |
| 2098 | "TLS certificate verification cannot be disabled for provider {}; use SSL_CERT_FILE with a trusted custom CA bundle instead", |
| 2099 | api_provider.as_str() |
| 2100 | )); |
| 2101 | bail!( |
| 2102 | "TLS certificate verification cannot be disabled for provider {}; configure SSL_CERT_FILE with a trusted custom CA bundle instead", |
| 2103 | api_provider.as_str() |
| 2104 | ); |
| 2105 | } |
| 2106 | logging::info(format!( |
| 2107 | "Retry policy: enabled={}, max_retries={}, initial_delay={}s, max_delay={}s", |
| 2108 | retry.enabled, retry.max_retries, retry.initial_delay, retry.max_delay |
| 2109 | )); |
| 2110 | if let Some(limit) = request_concurrency_limit { |
| 2111 | logging::info(format!( |
| 2112 | "Provider request concurrency cap: {} in-flight request(s)", |
| 2113 | limit |
| 2114 | )); |
| 2115 | } |
| 2116 | |
| 2117 | let http_client = Self::http_client_builder_with_auth_mode( |
| 2118 | &api_key, |
| 2119 | &http_headers, |
| 2120 | api_provider, |
| 2121 | &base_url, |
| 2122 | wire_format, |
| 2123 | auth_disabled, |
| 2124 | force_http1, |
| 2125 | config, |
| 2126 | AuthHeaderSurface::Inference, |
| 2127 | root_cert.as_ref(), |
| 2128 | )?; |
| 2129 | let http_client = http_client |
| 2130 | .redirect(reqwest::redirect::Policy::none()) |
| 2131 | .build()?; |
| 2132 | let models_http_client = Self::http_client_builder_with_auth_mode( |
| 2133 | &api_key, |
| 2134 | &http_headers, |
| 2135 | api_provider, |
| 2136 | &base_url, |
| 2137 | wire_format, |
| 2138 | auth_disabled, |
| 2139 | force_http1, |
| 2140 | config, |
| 2141 | AuthHeaderSurface::Listing, |
| 2142 | root_cert.as_ref(), |
| 2143 | )? |
| 2144 | .redirect(reqwest::redirect::Policy::none()) |
| 2145 | .build()?; |
| 2146 | // The HTTP/1.1 twin is eligible only after a proven pre-dispatch failure. |
| 2147 | // A stalled request may already have been accepted by the provider. |
| 2148 | let http1_client = Self::http_client_builder_with_auth_mode( |
| 2149 | &api_key, |
| 2150 | &http_headers, |
| 2151 | api_provider, |
| 2152 | &base_url, |
| 2153 | wire_format, |
| 2154 | auth_disabled, |
| 2155 | true, |
| 2156 | config, |
| 2157 | AuthHeaderSurface::Inference, |
| 2158 | root_cert.as_ref(), |
| 2159 | )?; |
| 2160 | let http1_client = http1_client |
| 2161 | .redirect(reqwest::redirect::Policy::none()) |
| 2162 | .build()?; |
| 2163 | |
| 2164 | let catalog_connection_base = (api_provider == ProviderKind::OpencodeGo) |
| 2165 | .then(|| config.base_url_for_route(&admitted_identity)); |
| 2166 | let route_facts = crate::provider_lake::configured_catalog_offering_for_route( |
| 2167 | config, |
| 2168 | api_provider, |
| 2169 | admitted_identity.key.as_str(), |
| 2170 | catalog_connection_base.as_deref().unwrap_or(&base_url), |
| 2171 | &default_model, |
| 2172 | ) |
| 2173 | .map(Arc::new); |
| 2174 | let catalog_error_secret_values = Arc::new(catalog_error_secret_values( |
| 2175 | &api_key, |
| 2176 | &http_headers, |
| 2177 | &model_bound_secret_values, |
| 2178 | )); |
| 2179 | Ok(Self { |
| 2180 | http_client, |
| 2181 | catalog_connection_base, |
| 2182 | go_route: admitted.go_route, |
| 2183 | models_http_client, |
| 2184 | http1_client, |
| 2185 | api_key, |
| 2186 | api_key_source, |
| 2187 | subscription_limit_guidance, |
| 2188 | resume_account_scope, |
| 2189 | exec_plugin_grant: None, |
| 2190 | plugin_provider, |
| 2191 | plugin_oauth_read_only: config.plugin_oauth_read_only, |
| 2192 | claude_org, |
| 2193 | session_provider_keys_only: config.session_provider_keys_only, |
| 2194 | automatic_opencode_session, |
| 2195 | model_bound_secret_values, |
| 2196 | catalog_error_secret_values, |
| 2197 | model_bound_masking, |
| 2198 | base_url, |
| 2199 | api_provider, |
| 2200 | admitted_identity, |
| 2201 | openrouter_vendor, |
| 2202 | billing_surface, |
| 2203 | billing_mode, |
| 2204 | configured_models: Arc::new(config.custom_models.clone().unwrap_or_default()), |
| 2205 | context_window_override, |
| 2206 | model_context_windows, |
| 2207 | route_limits, |
| 2208 | context_window: None, |
| 2209 | route_facts, |
| 2210 | codex_account_id, |
| 2211 | chatgpt_reasoning_api, |
| 2212 | wire_format, |
| 2213 | responses_profile_id, |
| 2214 | retry, |
| 2215 | isolated_request_state: false, |
| 2216 | remote_control_inference_participant: !config.runtime_chat_isolated |
| 2217 | && !config.runtime_thread_inference_unrelated, |
| 2218 | default_model, |
| 2219 | connection_health: Arc::new(AsyncMutex::new(ConnectionHealth::default())), |
| 2220 | rate_limiter: Arc::new(AsyncMutex::new(TokenBucket::from_env())), |
| 2221 | request_concurrency: request_concurrency_limit.map(ProviderConcurrencyLimiter::new), |
| 2222 | path_suffix, |
| 2223 | #[cfg(any(test, feature = "test-support"))] |
| 2224 | test_chat_transport_base_url: None, |
| 2225 | #[cfg(any(test, feature = "test-support"))] |
| 2226 | test_messages_transport_base_url: None, |
| 2227 | reasoning_stream_style, |
| 2228 | stream_idle_timeout, |
| 2229 | stream_open_timeout, |
| 2230 | force_http1, |
| 2231 | }) |
| 2232 | } |
| 2233 | |
| 2234 | /// Revalidate revocation and refresh host-owned OAuth before each actual send. |
| 2235 | /// Plugin code receives neither the access token nor the refresh token. |
| 2236 | pub(super) async fn authorize_plugin_request( |
| 2237 | &self, |
| 2238 | request: reqwest::RequestBuilder, |
| 2239 | ) -> Result<reqwest::RequestBuilder> { |
| 2240 | anyhow::ensure!( |
| 2241 | !self.session_provider_keys_only || self.plugin_provider.is_none(), |
| 2242 | "Stored OAuth authorization is unavailable under session-only provider key policy" |
| 2243 | ); |
| 2244 | if let Some(claude_org) = &self.claude_org { |
| 2245 | anyhow::ensure!( |
| 2246 | !self.session_provider_keys_only, |
| 2247 | "Claude organization billing is unavailable under session-only provider key policy" |
| 2248 | ); |
| 2249 | return claude_org |
| 2250 | .authorize(request, self.claude_org_test_transport_base()) |
| 2251 | .await |
| 2252 | .map(|(request, _)| request) |
| 2253 | .map_err(anyhow::Error::new); |
| 2254 | } |
| 2255 | if self.plugin_provider.is_none() { |
| 2256 | return Ok(request); |
| 2257 | } |
| 2258 | let destination = request |
| 2259 | .try_clone() |
| 2260 | .context("plugin request cannot be inspected")? |
| 2261 | .build()?; |
| 2262 | let base = reqwest::Url::parse(&self.base_url)?; |
| 2263 | anyhow::ensure!( |
| 2264 | destination.url().origin() == base.origin(), |
| 2265 | "plugin request escaped its reviewed provider origin" |
| 2266 | ); |
| 2267 | let read_only = self.plugin_oauth_read_only; |
| 2268 | let grant = self.exec_plugin_grant; |
| 2269 | let token = self |
| 2270 | .with_plugin_authority(move |name, base_url, descriptor| { |
| 2271 | codewhale_runtime::oauth::plugin_oauth_access_token_for_grant( |
| 2272 | name, base_url, descriptor, read_only, grant, |
| 2273 | ) |
| 2274 | }) |
| 2275 | .await?; |
| 2276 | Ok(request.bearer_auth(token)) |
| 2277 | } |
| 2278 | |
| 2279 | async fn with_plugin_authority<T: Send + 'static>( |
| 2280 | &self, |
| 2281 | authorize: impl FnOnce(&str, &str, &codewhale_runtime::oauth::PluginOAuthConfig) -> Result<T> |
| 2282 | + Send |
| 2283 | + 'static, |
| 2284 | ) -> Result<T> { |
| 2285 | let provider = self |
| 2286 | .plugin_provider |
| 2287 | .clone() |
| 2288 | .context("plugin provider is unavailable")?; |
| 2289 | let authority = provider |
| 2290 | .plugin_authority |
| 2291 | .clone() |
| 2292 | .context("plugin provider has no authority")?; |
| 2293 | let name = self.admitted_identity.key.to_string(); |
| 2294 | let base_url = self.base_url.clone(); |
| 2295 | let policy = codewhale_plugins::activation::extension_host_policy_enabled(); |
| 2296 | tokio::task::spawn_blocking(move || -> Result<T> { |
| 2297 | let _scope = codewhale_plugins::activation::PolicyScope::propagate(policy); |
| 2298 | let descriptor = provider |
| 2299 | .oauth |
| 2300 | .as_ref() |
| 2301 | .context("plugin provider requires host-managed OAuth")?; |
| 2302 | let empty_headers = std::collections::HashMap::new(); |
| 2303 | codewhale_plugins::providers::verify_provider_binding( |
| 2304 | &authority, |
| 2305 | &name, |
| 2306 | &base_url, |
| 2307 | descriptor, |
| 2308 | Some(provider.http_headers.as_ref().unwrap_or(&empty_headers)), |
| 2309 | ) |
| 2310 | .map_err(anyhow::Error::msg)?; |
| 2311 | let authorization = authorize(&name, &base_url, descriptor)?; |
| 2312 | // Refresh may wait on the issuer. Do not send a model request if |
| 2313 | // the review was revoked while that HTTP request was in flight. |
| 2314 | codewhale_plugins::registry::verify_plugin_component_authority( |
| 2315 | &authority, |
| 2316 | codewhale_plugins::activation::PluginActivationCapability::Providers, |
| 2317 | ) |
| 2318 | .map_err(anyhow::Error::msg)?; |
| 2319 | Ok(authorization) |
| 2320 | }) |
| 2321 | .await? |
| 2322 | } |
| 2323 | |
| 2324 | fn claude_org_test_transport_base(&self) -> Option<&str> { |
| 2325 | #[cfg(any(test, feature = "test-support"))] |
| 2326 | if let Some(base_url) = self.test_messages_transport_base_url.as_deref() { |
| 2327 | return Some(base_url); |
| 2328 | } |
| 2329 | None |
| 2330 | } |
| 2331 | |
| 2332 | /// Map a failed HTTP response, naming the route, host and key source on |
| 2333 | /// authentication and unknown-model failures (#6528) so a rejected key |
| 2334 | /// explains which credential was sent where and how to replace it. |
| 2335 | fn http_error_with_route_context( |
| 2336 | &self, |
| 2337 | status: u16, |
| 2338 | body: &str, |
| 2339 | retry_after: Option<Duration>, |
| 2340 | body_retry_after: Option<Duration>, |
| 2341 | ) -> LlmError { |
| 2342 | let route = self.admitted_identity.key.as_str(); |
| 2343 | if self.wire_format == WireFormat::GenerateContent { |
| 2344 | let mapped = gemini::map_gemini_error(status, body); |
| 2345 | if matches!(mapped, LlmError::AuthenticationError(_)) && !matches!(status, 401 | 403) { |
| 2346 | return mapped; |
| 2347 | } |
| 2348 | if matches!( |
| 2349 | mapped, |
| 2350 | LlmError::RateLimited { .. } | LlmError::QuotaExhausted(_) |
| 2351 | ) && status != 429 |
| 2352 | { |
| 2353 | return LlmError::from_http_response_with_retry_hints( |
| 2354 | 429, |
| 2355 | body, |
| 2356 | retry_after, |
| 2357 | body_retry_after, |
| 2358 | ); |
| 2359 | } |
| 2360 | } |
| 2361 | let error = match status { |
| 2362 | 401 | 403 => LlmError::from_http_response_with_auth_context( |
| 2363 | status, |
| 2364 | body, |
| 2365 | Some( |
| 2366 | crate::llm_client::AuthenticationErrorContext::from_parts( |
| 2367 | Some(route), |
| 2368 | Some(&self.base_url), |
| 2369 | None, |
| 2370 | Some(&self.api_key_source), |
| 2371 | Some(&self.api_key), |
| 2372 | ) |
| 2373 | .with_fix(auth_fix_hint(route, &self.api_key_source)), |
| 2374 | ), |
| 2375 | ), |
| 2376 | _ => LlmError::from_http_response_with_retry_hints( |
| 2377 | status, |
| 2378 | body, |
| 2379 | retry_after, |
| 2380 | body_retry_after, |
| 2381 | ), |
| 2382 | }; |
| 2383 | match error { |
| 2384 | LlmError::ModelError(message) => LlmError::ModelError(format!( |
| 2385 | "{message} (provider route: {route}, host: {}; run `codewhale model resolve` or /model to pick a model this route serves)", |
| 2386 | crate::llm_client::base_url_authority(&self.base_url) |
| 2387 | .unwrap_or_else(|| redact_url_for_display(&self.base_url)) |
| 2388 | )), |
| 2389 | LlmError::QuotaExhausted(error) => match self.subscription_limit_guidance.as_deref() { |
| 2390 | Some(guidance) => LlmError::QuotaExhausted(error.with_guidance(guidance)), |
| 2391 | None => LlmError::QuotaExhausted(error), |
| 2392 | }, |
| 2393 | other => other, |
| 2394 | } |
| 2395 | } |
| 2396 | |
| 2397 | /// Transport destination for Chat Completions requests. |
| 2398 | /// |
| 2399 | /// Production always uses the semantic route base URL. Unit tests may |
| 2400 | /// substitute a local capture server without changing the endpoint/model |
| 2401 | /// identity used by exact-route request shaping. |
| 2402 | pub(super) fn chat_transport_base_url(&self) -> &str { |
| 2403 | #[cfg(any(test, feature = "test-support"))] |
| 2404 | if let Some(base_url) = self.test_chat_transport_base_url.as_deref() { |
| 2405 | return base_url; |
| 2406 | } |
| 2407 | &self.base_url |
| 2408 | } |
| 2409 | |
| 2410 | /// Redirect Chat Completions *transport* to a local capture server while |
| 2411 | /// the semantic route (`base_url`, model, endpoint identity) stays exact. |
| 2412 | /// |
| 2413 | /// Test-only, and compiled out of release builds. Route shaping reads |
| 2414 | /// [`Self::base_url`], so an exact-route matrix can capture the real |
| 2415 | /// first-turn body for `api.z.ai`, `api.moonshot.ai`, `api.kimi.com`, or |
| 2416 | /// `api.minimax.io` without ever making a live provider call. |
| 2417 | #[cfg(any(test, feature = "test-support"))] |
| 2418 | pub fn set_test_chat_transport_base_url(&mut self, base_url: String) { |
| 2419 | self.test_chat_transport_base_url = Some(base_url); |
| 2420 | } |
| 2421 | |
| 2422 | /// Transport destination for a prepared Anthropic-compatible request. |
| 2423 | /// Production sends the exact prepared endpoint; tests may redirect the |
| 2424 | /// transport while preserving that immutable endpoint for route shaping. |
| 2425 | pub(super) fn messages_transport_url(&self, prepared_url: &str) -> String { |
| 2426 | #[cfg(any(test, feature = "test-support"))] |
| 2427 | if let Some(base_url) = self.test_messages_transport_base_url.as_deref() { |
| 2428 | return anthropic::anthropic_messages_url(base_url); |
| 2429 | } |
| 2430 | prepared_url.to_string() |
| 2431 | } |
| 2432 | |
| 2433 | /// Return a request whose tool results are safe to send to an upstream |
| 2434 | /// model provider. |
| 2435 | /// |
| 2436 | /// Tool output is untrusted model-bound data: it can contain a whole |
| 2437 | /// config file, a bare credential emitted by a shell command, or a |
| 2438 | /// spillover receipt whose backing content is later persisted by the chat |
| 2439 | /// adapter. Keep this boundary above all protocol adapters so Chat, |
| 2440 | /// Anthropic Messages, and OpenAI Responses — streaming and non-streaming |
| 2441 | /// alike — receive the same sanitized payload. |
| 2442 | fn prepare_model_bound_request(&self, mut request: MessageRequest) -> MessageRequest { |
| 2443 | let repair = codewhale_runtime::tool_history_repair::repair_tool_call_pairs_for_provider( |
| 2444 | &mut request.messages, |
| 2445 | ); |
| 2446 | if !repair.is_empty() { |
| 2447 | tracing::warn!( |
| 2448 | repaired_call_ids = ?repair.repaired_call_ids, |
| 2449 | duplicate_result_ids = ?repair.duplicate_result_ids, |
| 2450 | orphan_result_ids = ?repair.orphan_result_ids, |
| 2451 | "repaired tool call/result history before provider projection" |
| 2452 | ); |
| 2453 | } |
| 2454 | for message in &mut request.messages { |
| 2455 | for block in &mut message.content { |
| 2456 | if let ContentBlock::ToolResult { content, .. } = block |
| 2457 | && self.model_bound_masking |
| 2458 | { |
| 2459 | *content = redact_model_bound_text(content, &self.model_bound_secret_values); |
| 2460 | } |
| 2461 | } |
| 2462 | } |
| 2463 | request |
| 2464 | } |
| 2465 | |
| 2466 | /// Redact configured credentials from text that has been flattened into a |
| 2467 | /// normal model-bound text block. Unlike `prepare_model_bound_request`, |
| 2468 | /// this path always redacts: routing/classification prompts (which may |
| 2469 | /// summarize tool output) and durable goal-state text are not covered by |
| 2470 | /// the `[redaction] model_bound` opt-out, which exists so the model can |
| 2471 | /// quote file bytes back for exact edits — never to relax storage or |
| 2472 | /// routing summaries. |
| 2473 | pub fn redact_model_bound_text(&self, text: &str) -> String { |
| 2474 | redact_model_bound_text(text, &self.model_bound_secret_values) |
| 2475 | } |
| 2476 | |
| 2477 | /// Redact tool output as it enters the transcript. Unlike the request |
| 2478 | /// boundary, this path always redacts: the `[redaction] model_bound` |
| 2479 | /// opt-out exists so the model can quote file bytes back for exact edits, |
| 2480 | /// never to write a live credential to disk. |
| 2481 | pub fn redact_tool_output_for_transcript(&self, text: &str) -> String { |
| 2482 | redact_model_bound_text(text, &self.model_bound_secret_values) |
| 2483 | } |
| 2484 | |
| 2485 | /// Alternate models share this client's frozen endpoint and declarations. |
| 2486 | /// Resolution still owns protocol admission, including closed rosters. |
| 2487 | pub fn resolve_model_route(&self, model: &str) -> Result<ReadyRouteCandidate> { |
| 2488 | // Pin the transport's own wire: a custom-table client constructed |
| 2489 | // from a wire-true candidate keeps speaking that wire even when this |
| 2490 | // internal re-resolution runs config-free (an engine-internal model |
| 2491 | // switch must not silently downgrade the table's dialect). |
| 2492 | let request = RouteRequest { |
| 2493 | explicit_provider: Some(self.api_provider), |
| 2494 | model_selector: Some(LogicalModelRef::from(model)), |
| 2495 | saved_provider_model: None, |
| 2496 | base_url_override: Some(self.catalog_base_url().to_owned()), |
| 2497 | limit_overrides: Vec::new(), |
| 2498 | wire_override: (self.api_provider == ProviderKind::Custom).then_some(self.wire_format), |
| 2499 | responses_profile_override: (self.api_provider == ProviderKind::Custom) |
| 2500 | .then(|| self.responses_profile_id.map(|id| id.as_str().to_string())) |
| 2501 | .flatten(), |
| 2502 | }; |
| 2503 | if self.api_provider == ProviderKind::OpenaiCodex { |
| 2504 | static CODEX_RESOLVER: OnceLock<RouteResolver> = OnceLock::new(); |
| 2505 | return CODEX_RESOLVER |
| 2506 | .get_or_init(RouteResolver::new) |
| 2507 | .resolve(&request) |
| 2508 | .map_err(anyhow::Error::msg); |
| 2509 | } |
| 2510 | // A mid-session model switch must resolve against the same catalog |
| 2511 | // facts its route was minted from. The bundled resolver alone cannot |
| 2512 | // see a model published after this build, so a picker row the live |
| 2513 | // catalog knows would fail here instead of switching. |
| 2514 | let identity = self.admitted_identity.key.as_str(); |
| 2515 | let mut catalog = crate::provider_lake::runtime_catalog_resolver_for_identity( |
| 2516 | self.api_provider, |
| 2517 | Some(identity), |
| 2518 | self.catalog_base_url(), |
| 2519 | crate::provider_catalog_live::status_for_route( |
| 2520 | self.api_provider, |
| 2521 | identity, |
| 2522 | self.catalog_base_url(), |
| 2523 | ), |
| 2524 | ); |
| 2525 | catalog.resolver = catalog.resolver.with_configured_models( |
| 2526 | &self.configured_models, |
| 2527 | identity, |
| 2528 | self.api_provider, |
| 2529 | self.catalog_base_url(), |
| 2530 | ); |
| 2531 | let resolver = &catalog.resolver; |
| 2532 | if catalog.endpoint_catalog_authoritative { |
| 2533 | resolver.resolve_with_endpoint_catalog_authority(&request) |
| 2534 | } else { |
| 2535 | resolver.resolve(&request) |
| 2536 | } |
| 2537 | .map_err(anyhow::Error::msg) |
| 2538 | } |
| 2539 | |
| 2540 | fn declared_wire_model<'a>(&self, model: &'a str) -> Option<&'a str> { |
| 2541 | if self.api_provider == ProviderKind::OpenaiCodex |
| 2542 | || !self.configured_models.iter().any(|row| { |
| 2543 | row.id == model |
| 2544 | && row.matches_route(self.admitted_identity.key.as_str(), &self.base_url) |
| 2545 | }) |
| 2546 | { |
| 2547 | return None; |
| 2548 | } |
| 2549 | // A declaration cannot admit a new model to a closed protocol roster, |
| 2550 | // or defeat a required protocol alias such as OpenCode Go's allowlist. |
| 2551 | self.resolve_model_route(model) |
| 2552 | .ok() |
| 2553 | .filter(|candidate| candidate.wire_model_id().as_str() == model) |
| 2554 | .map(|_| model) |
| 2555 | } |
| 2556 | |
| 2557 | fn wire_model_for_route(&self, model: &str) -> String { |
| 2558 | self.declared_wire_model(model) |
| 2559 | .map(str::to_string) |
| 2560 | .unwrap_or_else(|| { |
| 2561 | codewhale_config::route::resolve_model( |
| 2562 | self.api_provider, |
| 2563 | model, |
| 2564 | Some(self.catalog_base_url()), |
| 2565 | ) |
| 2566 | .map_or_else(|_| model.trim().to_string(), |resolved| resolved.wire_id) |
| 2567 | }) |
| 2568 | } |
| 2569 | |
| 2570 | fn catalog_facts_for_model( |
| 2571 | &self, |
| 2572 | model: &str, |
| 2573 | ) -> Option<Arc<codewhale_config::catalog::CatalogOffering>> { |
| 2574 | let mut config = Config::default(); |
| 2575 | let _ = config |
| 2576 | .custom_models |
| 2577 | .replace(self.configured_models.as_ref().clone()); |
| 2578 | crate::provider_lake::configured_catalog_offering_for_route( |
| 2579 | &config, |
| 2580 | self.api_provider, |
| 2581 | self.admitted_identity.key.as_str(), |
| 2582 | self.catalog_base_url(), |
| 2583 | model, |
| 2584 | ) |
| 2585 | .map(Arc::new) |
| 2586 | } |
| 2587 | |
| 2588 | /// Resolve `model` through the central route resolver and rebuild this |
| 2589 | /// client whenever its exact wire identity, limits, or protocol differs |
| 2590 | /// from the route bound at construction (#5042). `Ok(None)` means the |
| 2591 | /// existing binding is already exact for `model`. This includes |
| 2592 | /// same-protocol switches: an OpenAI-compatible client for model A must not |
| 2593 | /// carry A's route limits into model B merely because both speak Chat. |
| 2594 | pub fn rebound_for_model_protocol( |
| 2595 | &self, |
| 2596 | config: Option<&Config>, |
| 2597 | model: &str, |
| 2598 | ) -> Result<Option<Self>> { |
| 2599 | // The bound model already owns its admitted protocol and limits, |
| 2600 | // including exact live-catalog facts absent from the offline catalog. |
| 2601 | if model == self.default_model { |
| 2602 | return Ok(None); |
| 2603 | } |
| 2604 | let candidate = self.resolve_model_route(model)?; |
| 2605 | if self.api_provider == ProviderKind::OpencodeGo |
| 2606 | && self.go_route.as_ref().map(|(connection, _)| connection) |
| 2607 | != candidate.endpoint().catalog_connection.as_ref() |
| 2608 | { |
| 2609 | anyhow::bail!("Go account binding changed. Refresh and reselect the route."); |
| 2610 | } |
| 2611 | let resolved = crate::route_runtime::resolve_declared_model_candidate_with_wire_override( |
| 2612 | self.api_provider, |
| 2613 | self.admitted_identity.key.as_str(), |
| 2614 | model, |
| 2615 | self.catalog_base_url(), |
| 2616 | self.context_window_override, |
| 2617 | self.model_context_windows.as_ref(), |
| 2618 | &self.configured_models, |
| 2619 | (self.api_provider == ProviderKind::Custom).then_some(self.wire_format), |
| 2620 | None, |
| 2621 | ) |
| 2622 | .ok() |
| 2623 | .filter(|route| { |
| 2624 | route.candidate.wire_model_id() == candidate.wire_model_id() |
| 2625 | && route.candidate.protocol() == candidate.protocol() |
| 2626 | && route.candidate.endpoint().base_url == candidate.endpoint().base_url |
| 2627 | && route.candidate.endpoint().endpoint_key == candidate.endpoint().endpoint_key |
| 2628 | }); |
| 2629 | let candidate_limits = resolved.as_ref().map_or_else( |
| 2630 | || crate::route_budget::known_route_limits(candidate.limits()), |
| 2631 | |route| crate::route_budget::known_route_limits(route.candidate.limits()), |
| 2632 | ); |
| 2633 | let context_window = resolved.map(|route| route.context_window).or_else(|| { |
| 2634 | (candidate.wire_model_id().as_str() == self.default_model |
| 2635 | && candidate_limits == self.route_limits) |
| 2636 | .then_some(self.context_window) |
| 2637 | .flatten() |
| 2638 | }); |
| 2639 | if candidate.endpoint().base_url == self.base_url |
| 2640 | && candidate.protocol() == self.wire_format |
| 2641 | && candidate.wire_model_id().as_str() == self.default_model |
| 2642 | && candidate_limits == self.route_limits |
| 2643 | && context_window == self.context_window |
| 2644 | { |
| 2645 | return Ok(None); |
| 2646 | } |
| 2647 | if candidate.endpoint().base_url == self.base_url |
| 2648 | && candidate.protocol() == self.wire_format |
| 2649 | { |
| 2650 | // Same-protocol model switches keep the already-authenticated, |
| 2651 | // endpoint-bound transport but must freeze the alternate model's |
| 2652 | // exact wire identity and limits. This path is also what makes a |
| 2653 | // model-aware client usable in embedded/test runtimes that do not |
| 2654 | // retain the original Config after construction. |
| 2655 | let mut rebound = self.clone(); |
| 2656 | rebound.go_route = candidate |
| 2657 | .endpoint() |
| 2658 | .catalog_connection |
| 2659 | .clone() |
| 2660 | .map(|connection| (connection, candidate.endpoint().endpoint_key.clone())); |
| 2661 | rebound.default_model = candidate.wire_model_id().as_str().to_string(); |
| 2662 | rebound.route_limits = candidate_limits; |
| 2663 | rebound.context_window = context_window; |
| 2664 | rebound.route_facts = rebound.catalog_facts_for_model(&rebound.default_model); |
| 2665 | return Ok(Some(rebound)); |
| 2666 | } |
| 2667 | let config = config.ok_or_else(|| { |
| 2668 | anyhow::anyhow!( |
| 2669 | "{} model {:?} uses {:?}, but this client is bound to {:?} and no configuration is available to rebuild it", |
| 2670 | self.api_provider.provider().display_name(), |
| 2671 | model, |
| 2672 | candidate.protocol(), |
| 2673 | self.wire_format |
| 2674 | ) |
| 2675 | })?; |
| 2676 | let mut rebound = Self::from_candidate(config, &candidate)?; |
| 2677 | if rebound.automatic_opencode_session.is_some() && self.automatic_opencode_session.is_some() |
| 2678 | { |
| 2679 | rebound |
| 2680 | .automatic_opencode_session |
| 2681 | .clone_from(&self.automatic_opencode_session); |
| 2682 | } |
| 2683 | rebound.route_limits = candidate_limits; |
| 2684 | rebound.context_window = context_window; |
| 2685 | rebound.configured_models = Arc::clone(&self.configured_models); |
| 2686 | rebound.context_window_override = self.context_window_override; |
| 2687 | rebound.model_context_windows = self.model_context_windows.clone(); |
| 2688 | rebound.route_facts = rebound.catalog_facts_for_model(&rebound.default_model); |
| 2689 | Ok(Some(rebound)) |
| 2690 | } |
| 2691 | |
| 2692 | fn bind_request_to_protocol( |
| 2693 | &self, |
| 2694 | mut request: MessageRequest, |
| 2695 | ) -> Result<(MessageRequest, Option<RouteLimits>)> { |
| 2696 | let model_aware = self.api_provider.provider().wire_policy() |
| 2697 | == codewhale_config::provider::WirePolicy::ModelAware; |
| 2698 | // Preserve the exact binding for model-aware providers too. Looking |
| 2699 | // up this same model in the offline catalog would discard protocol |
| 2700 | // and limit facts already admitted from an exact provider catalog. |
| 2701 | if request.model == self.default_model |
| 2702 | || (!model_aware && request.model.trim() == self.default_model) |
| 2703 | { |
| 2704 | return Ok((request, self.route_limits)); |
| 2705 | } |
| 2706 | |
| 2707 | let candidate = match self.resolve_model_route(&request.model) { |
| 2708 | Ok(candidate) => candidate, |
| 2709 | Err(error) if model_aware || self.api_provider == ProviderKind::OpencodeGo => { |
| 2710 | return Err(error); |
| 2711 | } |
| 2712 | Err(_) => { |
| 2713 | // A fixed-protocol gateway may legitimately accept an id that |
| 2714 | // is newer than our offline catalog. Preserve the caller's |
| 2715 | // model, but fail closed on limits instead of reusing the |
| 2716 | // bound default model's envelope. |
| 2717 | return Ok((request, None)); |
| 2718 | } |
| 2719 | }; |
| 2720 | if candidate.endpoint().catalog_connection.is_some() || self.go_route.is_some() { |
| 2721 | bail!("Rebind this client to the selected Go model before sending"); |
| 2722 | } |
| 2723 | if candidate.protocol() != self.wire_format |
| 2724 | || candidate.endpoint().base_url != self.base_url |
| 2725 | { |
| 2726 | bail!( |
| 2727 | "{} model {:?} uses {:?}, but this client is bound to {:?}; resolve a new model route before sending", |
| 2728 | self.api_provider.provider().display_name(), |
| 2729 | request.model, |
| 2730 | candidate.protocol(), |
| 2731 | self.wire_format |
| 2732 | ); |
| 2733 | } |
| 2734 | request.model = candidate.wire_model_id().as_str().to_string(); |
| 2735 | let route_limits = crate::route_budget::known_route_limits(candidate.limits()); |
| 2736 | Ok((request, route_limits)) |
| 2737 | } |
| 2738 | |
| 2739 | #[cfg(test)] |
| 2740 | fn build_http_client( |
| 2741 | api_key: &str, |
| 2742 | extra_headers: &HashMap<String, String>, |
| 2743 | api_provider: ProviderKind, |
| 2744 | base_url: &str, |
| 2745 | ) -> Result<reqwest::Client> { |
| 2746 | Self::http_client_builder_with_auth_mode( |
| 2747 | api_key, |
| 2748 | extra_headers, |
| 2749 | api_provider, |
| 2750 | base_url, |
| 2751 | provider_default_wire_format(api_provider), |
| 2752 | false, |
| 2753 | false, |
| 2754 | &Config::default(), |
| 2755 | AuthHeaderSurface::Inference, |
| 2756 | None, |
| 2757 | )? |
| 2758 | .build() |
| 2759 | .map_err(Into::into) |
| 2760 | } |
| 2761 | |
| 2762 | fn http_client_builder_with_auth_mode( |
| 2763 | api_key: &str, |
| 2764 | extra_headers: &HashMap<String, String>, |
| 2765 | api_provider: ProviderKind, |
| 2766 | base_url: &str, |
| 2767 | wire_format: WireFormat, |
| 2768 | auth_disabled: bool, |
| 2769 | force_http1: bool, |
| 2770 | config: &Config, |
| 2771 | surface: AuthHeaderSurface, |
| 2772 | root_cert: Option<&CapturedRootCert>, |
| 2773 | ) -> Result<reqwest::ClientBuilder> { |
| 2774 | let filtered_headers; |
| 2775 | let extra_headers = if config.session_provider_keys_only { |
| 2776 | filtered_headers = extra_headers |
| 2777 | .iter() |
| 2778 | .filter(|(name, _)| !is_upstream_auth_header(name)) |
| 2779 | .map(|(name, value)| (name.clone(), value.clone())) |
| 2780 | .collect(); |
| 2781 | &filtered_headers |
| 2782 | } else { |
| 2783 | extra_headers |
| 2784 | }; |
| 2785 | let headers = build_default_headers( |
| 2786 | api_key, |
| 2787 | extra_headers, |
| 2788 | api_provider, |
| 2789 | base_url, |
| 2790 | wire_format, |
| 2791 | auth_disabled, |
| 2792 | surface, |
| 2793 | )?; |
| 2794 | let transport = if api_provider == ProviderKind::Custom |
| 2795 | && codewhale_config::descriptors::is_registry_admitted_base_url(base_url) |
| 2796 | { |
| 2797 | codewhale_net::guard::public_address_reqwest_client_builder() |
| 2798 | } else { |
| 2799 | crate::platform_client_builder() |
| 2800 | }; |
| 2801 | let mut builder = transport |
| 2802 | .default_headers(headers) |
| 2803 | .user_agent(client_user_agent(api_provider)) |
| 2804 | .connect_timeout(config.connect_timeout()) |
| 2805 | .tcp_keepalive(config.tcp_keepalive()) |
| 2806 | .http2_keep_alive_interval(config.http2_keep_alive_interval()) |
| 2807 | .http2_keep_alive_timeout(config.http2_keep_alive_timeout()) |
| 2808 | .min_tls_version(reqwest::tls::Version::TLS_1_2) |
| 2809 | .retry(reqwest::retry::never()); |
| 2810 | if api_provider == ProviderKind::OpenaiCodex { |
| 2811 | builder = builder.redirect(reqwest::redirect::Policy::none()); |
| 2812 | } |
| 2813 | if force_http1 { |
| 2814 | builder = builder.http1_only(); |
| 2815 | } |
| 2816 | if let Some(cert) = root_cert { |
| 2817 | builder = add_captured_root_cert(builder, cert); |
| 2818 | } |
| 2819 | match config.model_http_policy.as_ref() { |
| 2820 | Some(policy) => policy.configure(builder, base_url), |
| 2821 | None => Ok(builder), |
| 2822 | } |
| 2823 | } |
| 2824 | |
| 2825 | /// HTTP/1.1 client for automatic stream-header fallback. |
| 2826 | #[must_use] |
| 2827 | pub fn http1_fallback_client(&self) -> &reqwest::Client { |
| 2828 | &self.http1_client |
| 2829 | } |
| 2830 | |
| 2831 | #[cfg(test)] |
| 2832 | fn default_headers( |
| 2833 | api_key: &str, |
| 2834 | extra_headers: &HashMap<String, String>, |
| 2835 | ) -> Result<HeaderMap> { |
| 2836 | build_default_headers( |
| 2837 | api_key, |
| 2838 | extra_headers, |
| 2839 | ProviderKind::Deepseek, |
| 2840 | codewhale_config::descriptors::defaults::DEFAULT_DEEPSEEK_BASE_URL, |
| 2841 | WireFormat::ChatCompletions, |
| 2842 | false, |
| 2843 | AuthHeaderSurface::Inference, |
| 2844 | ) |
| 2845 | } |
| 2846 | |
| 2847 | #[cfg(test)] |
| 2848 | fn default_headers_for_provider( |
| 2849 | api_key: &str, |
| 2850 | extra_headers: &HashMap<String, String>, |
| 2851 | api_provider: ProviderKind, |
| 2852 | base_url: &str, |
| 2853 | ) -> Result<HeaderMap> { |
| 2854 | build_default_headers( |
| 2855 | api_key, |
| 2856 | extra_headers, |
| 2857 | api_provider, |
| 2858 | base_url, |
| 2859 | provider_default_wire_format(api_provider), |
| 2860 | false, |
| 2861 | AuthHeaderSurface::Inference, |
| 2862 | ) |
| 2863 | } |
| 2864 | |
| 2865 | #[cfg(test)] |
| 2866 | fn default_headers_for_provider_with_auth_disabled( |
| 2867 | api_key: &str, |
| 2868 | extra_headers: &HashMap<String, String>, |
| 2869 | api_provider: ProviderKind, |
| 2870 | base_url: &str, |
| 2871 | ) -> Result<HeaderMap> { |
| 2872 | build_default_headers( |
| 2873 | api_key, |
| 2874 | extra_headers, |
| 2875 | api_provider, |
| 2876 | base_url, |
| 2877 | provider_default_wire_format(api_provider), |
| 2878 | true, |
| 2879 | AuthHeaderSurface::Inference, |
| 2880 | ) |
| 2881 | } |
| 2882 | } |
| 2883 | |
| 2884 | /// Which request surface a client's default auth header is built for. |
| 2885 | /// |
| 2886 | /// Anthropic's `x-api-key` convention belongs to Anthropic's own service, not |
| 2887 | /// to the Messages wire format by itself. A custom table speaks Messages |
| 2888 | /// because its host does, but it is still reached through the |
| 2889 | /// OpenAI-compatible config surface, and its listing follows the OpenAI |
| 2890 | /// convention: a relay can answer `/v1/messages` on either header while |
| 2891 | /// answering `/v1/models` only on `Authorization: Bearer`. Keeping the two |
| 2892 | /// surfaces apart stops a listing from inheriting a header chosen for the |
| 2893 | /// Messages endpoint. |
| 2894 | #[derive(Clone, Copy, PartialEq, Eq)] |
| 2895 | enum AuthHeaderSurface { |
| 2896 | /// Chat, Messages and Responses requests: the wire dialect decides. |
| 2897 | Inference, |
| 2898 | /// The provider's own `/models` listing. |
| 2899 | Listing, |
| 2900 | } |
| 2901 | |
| 2902 | fn build_default_headers( |
| 2903 | api_key: &str, |
| 2904 | extra_headers: &HashMap<String, String>, |
| 2905 | api_provider: ProviderKind, |
| 2906 | base_url: &str, |
| 2907 | wire_format: WireFormat, |
| 2908 | auth_disabled: bool, |
| 2909 | surface: AuthHeaderSurface, |
| 2910 | ) -> Result<HeaderMap> { |
| 2911 | let mut headers = HeaderMap::new(); |
| 2912 | headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json")); |
| 2913 | let api_key = api_key.trim(); |
| 2914 | let uses_anthropic_messages = wire_format == WireFormat::AnthropicMessages; |
| 2915 | let uses_generate_content = wire_format == WireFormat::GenerateContent; |
| 2916 | if uses_anthropic_messages { |
| 2917 | // #3014: most Messages API routes authenticate with `x-api-key`. |
| 2918 | // OpenModel also supports Bearer auth for Messages, and its `/models` |
| 2919 | // endpoint requires it, so the header chooser below keeps OpenModel on |
| 2920 | // Bearer while still pinning the Anthropic wire contract here. The |
| 2921 | // Codewhale API is the same shape: its Anthropic passthrough |
| 2922 | // authenticates the account key with `Authorization: Bearer` on every |
| 2923 | // protocol and does not accept `x-api-key`. |
| 2924 | headers.insert( |
| 2925 | HeaderName::from_static("anthropic-version"), |
| 2926 | HeaderValue::from_static("2023-06-01"), |
| 2927 | ); |
| 2928 | } |
| 2929 | // A custom host's listing never inherits the Messages choice. Its |
| 2930 | // `kind = "openai-compatible"` surface means Bearer, and a relay that |
| 2931 | // accepts Messages on either header may still reject `x-api-key` on |
| 2932 | // `/v1/models` with `401 missing_api_key`. |
| 2933 | let listing_on_custom_host = |
| 2934 | surface == AuthHeaderSurface::Listing && api_provider == ProviderKind::Custom; |
| 2935 | let auth_header_name = if auth_disabled { |
| 2936 | None |
| 2937 | } else if !api_key.is_empty() |
| 2938 | && uses_anthropic_messages |
| 2939 | && !listing_on_custom_host |
| 2940 | && !matches!( |
| 2941 | api_provider, |
| 2942 | ProviderKind::Openmodel | ProviderKind::Codewhale |
| 2943 | ) |
| 2944 | { |
| 2945 | Some(HeaderName::from_static("x-api-key")) |
| 2946 | } else if !api_key.is_empty() |
| 2947 | && uses_generate_content |
| 2948 | && !listing_on_custom_host |
| 2949 | && !matches!( |
| 2950 | api_provider, |
| 2951 | ProviderKind::OpencodeGo | ProviderKind::OpencodeZen | ProviderKind::Codewhale |
| 2952 | ) |
| 2953 | { |
| 2954 | Some(HeaderName::from_static("x-goog-api-key")) |
| 2955 | } else if !api_key.is_empty() |
| 2956 | && api_provider == ProviderKind::XiaomiMimo |
| 2957 | && (xiaomi_mimo_base_url_uses_token_plan(base_url) |
| 2958 | || xiaomi_mimo_api_key_uses_token_plan(api_key)) |
| 2959 | { |
| 2960 | Some(HeaderName::from_static("api-key")) |
| 2961 | } else if !api_key.is_empty() { |
| 2962 | Some(AUTHORIZATION) |
| 2963 | } else { |
| 2964 | None |
| 2965 | }; |
| 2966 | if let Some(header_name) = auth_header_name.as_ref() { |
| 2967 | let header_value = if *header_name == AUTHORIZATION { |
| 2968 | HeaderValue::from_str(&format!("Bearer {api_key}"))? |
| 2969 | } else { |
| 2970 | HeaderValue::from_str(api_key)? |
| 2971 | }; |
| 2972 | headers.insert(header_name.clone(), header_value); |
| 2973 | } |
| 2974 | // OpenRouter app attribution: these two headers are how apps appear on |
| 2975 | // openrouter.ai's app rankings — there is no manual submission. They |
| 2976 | // identify the app, never the user, and a user-configured header of the |
| 2977 | // same name below still wins (the extra-header loop overwrites). |
| 2978 | if api_provider == ProviderKind::Openrouter { |
| 2979 | // `HTTP-Referer` is the only required header: it is the app's unique |
| 2980 | // identifier, and without it OpenRouter creates no app page at all. |
| 2981 | headers.insert( |
| 2982 | HeaderName::from_static("http-referer"), |
| 2983 | HeaderValue::from_static("https://codewhale.net"), |
| 2984 | ); |
| 2985 | // `X-OpenRouter-Title` is the current display-name header. `X-Title` |
| 2986 | // is only kept for backwards compatibility — OpenRouter still honours |
| 2987 | // it, and a base-URL override can point this provider at an |
| 2988 | // OpenRouter-compatible gateway that knows the old name and not the |
| 2989 | // new one. Two bytes of redundancy is cheaper than losing attribution. |
| 2990 | // |
| 2991 | // Both names carry one display title. A user who configures either |
| 2992 | // one (a fork, say, setting only the legacy `X-Title`) must control |
| 2993 | // the name on both, or the default left on the other header would |
| 2994 | // silently override theirs on OpenRouter. |
| 2995 | let user_title = |wanted: &str| { |
| 2996 | extra_headers.iter().find_map(|(name, value)| { |
| 2997 | let value = value.trim(); |
| 2998 | (name.trim().eq_ignore_ascii_case(wanted) && !value.is_empty()).then_some(value) |
| 2999 | }) |
| 3000 | }; |
| 3001 | let title = HeaderValue::from_str( |
| 3002 | user_title("x-openrouter-title") |
| 3003 | .or_else(|| user_title("x-title")) |
| 3004 | .unwrap_or("Codewhale"), |
| 3005 | )?; |
| 3006 | headers.insert(HeaderName::from_static("x-openrouter-title"), title.clone()); |
| 3007 | headers.insert(HeaderName::from_static("x-title"), title); |
| 3008 | // Marketplace categories, at most two per request. These place the app |
| 3009 | // under Coding → CLI Agents and Productivity → Personal Agents on |
| 3010 | // openrouter.ai/apps, which is how the rankings page groups entries. |
| 3011 | // Unrecognised values are dropped silently, so these must stay exactly |
| 3012 | // as OpenRouter spells them. |
| 3013 | headers.insert( |
| 3014 | HeaderName::from_static("x-openrouter-categories"), |
| 3015 | HeaderValue::from_static("cli-agent,personal-agent"), |
| 3016 | ); |
| 3017 | } |
| 3018 | for (name, value) in extra_headers { |
| 3019 | let name = name.trim(); |
| 3020 | let value = value.trim(); |
| 3021 | if name.is_empty() || value.is_empty() { |
| 3022 | continue; |
| 3023 | } |
| 3024 | if auth_disabled && is_upstream_auth_header(name) { |
| 3025 | continue; |
| 3026 | } |
| 3027 | let header_name = HeaderName::from_bytes(name.as_bytes())?; |
| 3028 | if header_name == AUTHORIZATION |
| 3029 | || header_name == CONTENT_TYPE |
| 3030 | || auth_header_name.as_ref() == Some(&header_name) |
| 3031 | || (auth_header_name.is_some() && is_auth_dialect_header(&header_name)) |
| 3032 | { |
| 3033 | continue; |
| 3034 | } |
| 3035 | headers.insert(header_name, HeaderValue::from_str(value)?); |
| 3036 | } |
| 3037 | Ok(headers) |
| 3038 | } |
| 3039 | |
| 3040 | fn is_auth_dialect_header(header_name: &HeaderName) -> bool { |
| 3041 | header_name == AUTHORIZATION |
| 3042 | || header_name == HeaderName::from_static("api-key") |
| 3043 | || header_name == HeaderName::from_static("x-api-key") |
| 3044 | } |
| 3045 | |
| 3046 | fn admit_responses_profile( |
| 3047 | provider: ProviderKind, |
| 3048 | wire_format: WireFormat, |
| 3049 | profile: Option<ResponsesProfileId>, |
| 3050 | catalog_probe: bool, |
| 3051 | ) -> Result<Option<ResponsesProfileId>> { |
| 3052 | if catalog_probe { |
| 3053 | anyhow::ensure!( |
| 3054 | profile.is_none(), |
| 3055 | "catalog refresh cannot carry a responses profile" |
| 3056 | ); |
| 3057 | return Ok(None); |
| 3058 | } |
| 3059 | if wire_format == WireFormat::Responses { |
| 3060 | let Some(profile) = profile else { |
| 3061 | bail!( |
| 3062 | "responses client for {} requires a dialect profile", |
| 3063 | provider.as_str() |
| 3064 | ); |
| 3065 | }; |
| 3066 | return Ok(Some(profile)); |
| 3067 | } |
| 3068 | anyhow::ensure!( |
| 3069 | profile.is_none(), |
| 3070 | "client for {} cannot carry a responses profile on {wire_format:?}", |
| 3071 | provider.as_str() |
| 3072 | ); |
| 3073 | Ok(None) |
| 3074 | } |
| 3075 | |
| 3076 | #[cfg(test)] |
| 3077 | fn standard_responses_profile() -> ResponsesProfileId { |
| 3078 | codewhale_config::responses_dialect::builtin_profiles() |
| 3079 | .iter() |
| 3080 | .find(|profile| profile.id.as_str() == "standard") |
| 3081 | .expect("standard responses profile") |
| 3082 | .id |
| 3083 | } |
| 3084 | |
| 3085 | fn provider_default_wire_format(provider: ProviderKind) -> WireFormat { |
| 3086 | provider |
| 3087 | .provider() |
| 3088 | .wire_policy() |
| 3089 | .fixed() |
| 3090 | .unwrap_or_else(|| { |
| 3091 | if provider == ProviderKind::OpencodeZen { |
| 3092 | WireFormat::Responses |
| 3093 | } else { |
| 3094 | WireFormat::ChatCompletions |
| 3095 | } |
| 3096 | }) |
| 3097 | } |
| 3098 | |
| 3099 | /// Resolve the wire dialect for a dual-protocol vendor. |
| 3100 | /// |
| 3101 | /// Power-user toggle: `providers.<id>.wire = "openai" | "anthropic" | "responses"`. |
| 3102 | /// Legacy dialect kinds (`*Anthropic`) still force Messages. Custom providers |
| 3103 | /// honor `wire = "responses" | "anthropic" | "chat"` per-config (see |
| 3104 | /// `crates/config/src/provider.rs:Custom`). Everyone else keeps the descriptor's |
| 3105 | /// fixed policy (or Chat Completions). |
| 3106 | fn provider_wire_format_for_config( |
| 3107 | identity: &ProviderIdentity, |
| 3108 | config: Option<&codewhale_runtime::config::Config>, |
| 3109 | ) -> WireFormat { |
| 3110 | let api_provider = identity.provider; |
| 3111 | let wire = config.and_then(|cfg| cfg.provider_wire_dialect(identity)); |
| 3112 | let prefers_anthropic = matches!( |
| 3113 | api_provider, |
| 3114 | ProviderKind::DeepseekAnthropic |
| 3115 | | ProviderKind::MinimaxAnthropic |
| 3116 | | ProviderKind::ModelstudioTokenPlanAnthropic |
| 3117 | | ProviderKind::ModelstudioCodingPlanAnthropic |
| 3118 | ) || wire_config_prefers_anthropic(wire); |
| 3119 | |
| 3120 | if prefers_anthropic |
| 3121 | && matches!( |
| 3122 | api_provider, |
| 3123 | ProviderKind::Deepseek |
| 3124 | | ProviderKind::Minimax |
| 3125 | | ProviderKind::ModelstudioTokenPlan |
| 3126 | | ProviderKind::DeepseekAnthropic |
| 3127 | | ProviderKind::MinimaxAnthropic |
| 3128 | | ProviderKind::ModelstudioTokenPlanAnthropic |
| 3129 | | ProviderKind::ModelstudioCodingPlan |
| 3130 | | ProviderKind::ModelstudioCodingPlanAnthropic |
| 3131 | ) |
| 3132 | { |
| 3133 | return WireFormat::AnthropicMessages; |
| 3134 | } |
| 3135 | |
| 3136 | // Custom providers honor `wire = "anthropic"` / `wire = "responses"` explicitly. |
| 3137 | // The static `Custom::wire_policy()` remains `Chat` as a safe default; the |
| 3138 | // per-config override lives here (and in `provider_capability`) so existing |
| 3139 | // `[providers.<name>]` tables gain the three-way switch without changing the |
| 3140 | // provider registry trait. Supported aliases: |
| 3141 | // anthropic: "anthropic" | "messages" | "claude" | "anthropic-messages" | ... |
| 3142 | // responses: "responses" | "responses-api" | "openai-responses" | "openai_responses" | ... |
| 3143 | if api_provider == ProviderKind::Custom { |
| 3144 | if wire_config_prefers_anthropic(wire) { |
| 3145 | return WireFormat::AnthropicMessages; |
| 3146 | } |
| 3147 | if wire_config_prefers_responses(wire) { |
| 3148 | return WireFormat::Responses; |
| 3149 | } |
| 3150 | if codewhale_config::provider::wire_dialect_prefers_generate_content(wire) { |
| 3151 | return WireFormat::GenerateContent; |
| 3152 | } |
| 3153 | } |
| 3154 | |
| 3155 | provider_default_wire_format(api_provider) |
| 3156 | } |
| 3157 | |
| 3158 | fn wire_config_prefers_anthropic(wire: Option<&str>) -> bool { |
| 3159 | codewhale_config::provider::wire_dialect_prefers_anthropic(wire) |
| 3160 | } |
| 3161 | |
| 3162 | fn wire_config_prefers_responses(wire: Option<&str>) -> bool { |
| 3163 | codewhale_config::provider::wire_dialect_prefers_responses(wire) |
| 3164 | } |
| 3165 | |
| 3166 | fn model_listing_url(provider: ProviderKind, base_url: &str) -> String { |
| 3167 | let base = if provider == ProviderKind::OpencodeGo { |
| 3168 | codewhale_config::opencode_go_listing_base_url(base_url) |
| 3169 | } else { |
| 3170 | base_url |
| 3171 | }; |
| 3172 | api_url(base, "models") |
| 3173 | } |
| 3174 | |
| 3175 | fn model_listing_is_public(base_url: &str) -> bool { |
| 3176 | codewhale_config::descriptors::bundled_provider_descriptors() |
| 3177 | .iter() |
| 3178 | .any(|row| { |
| 3179 | row.discovery |
| 3180 | == codewhale_config::descriptors::DescriptorDiscovery::PublicModelsEndpoint |
| 3181 | && row.base_url == base_url.trim_end_matches('/') |
| 3182 | }) |
| 3183 | } |
| 3184 | |
| 3185 | pub(crate) fn model_listing_unavailable(api_provider: ProviderKind, base_url: &str) -> bool { |
| 3186 | if api_provider != ProviderKind::Custom { |
| 3187 | return false; |
| 3188 | } |
| 3189 | let Ok(url) = reqwest::Url::parse(base_url) else { |
| 3190 | return false; |
| 3191 | }; |
| 3192 | if !url.username().is_empty() |
| 3193 | || url.password().is_some() |
| 3194 | || url.query().is_some() |
| 3195 | || url.fragment().is_some() |
| 3196 | { |
| 3197 | return false; |
| 3198 | } |
| 3199 | codewhale_config::descriptors::bundled_provider_descriptors() |
| 3200 | .iter() |
| 3201 | .filter(|row| row.discovery == codewhale_config::descriptors::DescriptorDiscovery::None) |
| 3202 | .filter_map(|row| reqwest::Url::parse(&row.base_url).ok()) |
| 3203 | .any(|known| { |
| 3204 | known.scheme() == url.scheme() |
| 3205 | && known.host_str() == url.host_str() |
| 3206 | && known.port_or_known_default() == url.port_or_known_default() |
| 3207 | && known.path().trim_end_matches('/') == url.path().trim_end_matches('/') |
| 3208 | }) |
| 3209 | } |
| 3210 | |
| 3211 | fn api_provider_skips_models_probe(api_provider: ProviderKind) -> bool { |
| 3212 | // Concentrate's `GET /v1/models` is explicitly unauthenticated |
| 3213 | // (docs/PROVIDERS.md): a 2xx proves nothing about the key, so guided |
| 3214 | // setup must not count it as verification — the key is observed on the |
| 3215 | // first authenticated call instead. |
| 3216 | matches!( |
| 3217 | api_provider, |
| 3218 | ProviderKind::DeepseekAnthropic | ProviderKind::Concentrate |
| 3219 | ) |
| 3220 | } |
| 3221 | |
| 3222 | #[must_use] |
| 3223 | pub fn provider_api_key_verification_is_observed(api_provider: ProviderKind) -> bool { |
| 3224 | !api_provider_skips_models_probe(api_provider) |
| 3225 | } |
| 3226 | |
| 3227 | #[must_use] |
| 3228 | pub fn provider_api_key_verification_is_observed_for_route( |
| 3229 | api_provider: ProviderKind, |
| 3230 | base_url: &str, |
| 3231 | ) -> bool { |
| 3232 | provider_api_key_verification_is_observed(api_provider) |
| 3233 | && !model_listing_is_public(base_url) |
| 3234 | && !model_listing_unavailable(api_provider, base_url) |
| 3235 | } |
| 3236 | |
| 3237 | /// Verify a provider API key by hitting the `/models` endpoint |
| 3238 | /// (#3875). Builds a minimal HTTP client with the canonical auth |
| 3239 | /// headers for `provider`, issues a single GET, and returns |
| 3240 | /// `Ok(roster)` on a 2xx response or `Err(reason)` on any failure. |
| 3241 | /// |
| 3242 | /// `roster` is the listing that 2xx already carried, projected by the same |
| 3243 | /// rules as a catalog refresh and scoped to `provider`'s own id: the caller |
| 3244 | /// rescopes it to the exact route identity and publishes it, so guided setup |
| 3245 | /// offers the models this key can call today rather than bundled or |
| 3246 | /// Models.dev rows the provider may have retired. It is `None` when the body |
| 3247 | /// is not one complete, valid roster (a paginated first page, malformed or |
| 3248 | /// empty JSON); a valid 2xx still verifies the key, and the existing rows stay. |
| 3249 | /// |
| 3250 | /// This is intentionally a one-shot call — no retry, no rate-limit |
| 3251 | /// wait — so a bad key is surfaced immediately. |
| 3252 | pub async fn verify_provider_api_key( |
| 3253 | provider: ProviderKind, |
| 3254 | api_key: &str, |
| 3255 | base_url: &str, |
| 3256 | ) -> Result<Option<ProviderCatalogDelta>, String> { |
| 3257 | if !provider_api_key_verification_is_observed_for_route(provider, base_url) { |
| 3258 | // Providers without a /models endpoint can't be verified this |
| 3259 | // way; accept the key optimistically (same as health_check). |
| 3260 | return Ok(None); |
| 3261 | } |
| 3262 | let headers = build_default_headers( |
| 3263 | api_key, |
| 3264 | &Default::default(), |
| 3265 | provider, |
| 3266 | base_url, |
| 3267 | provider_default_wire_format(provider), |
| 3268 | false, |
| 3269 | AuthHeaderSurface::Listing, |
| 3270 | ) |
| 3271 | .map_err(|err| format!("failed to build auth headers: {err:#}"))?; |
| 3272 | let client = crate::platform_client_builder() |
| 3273 | .default_headers(headers) |
| 3274 | .redirect(reqwest::redirect::Policy::none()) |
| 3275 | .user_agent(concat!( |
| 3276 | "Mozilla/5.0 (compatible; codewhale/", |
| 3277 | env!("CARGO_PKG_VERSION"), |
| 3278 | "; +https://github.com/codewhale-hq/CodeWhale)" |
| 3279 | )) |
| 3280 | .connect_timeout(Duration::from_secs(10)) |
| 3281 | .timeout(Duration::from_secs(15)) |
| 3282 | .build() |
| 3283 | .map_err(|err| format!("failed to build HTTP client: {err:#}"))?; |
| 3284 | let url = model_listing_url(provider, base_url); |
| 3285 | let response = client |
| 3286 | .get(&url) |
| 3287 | .send() |
| 3288 | .await |
| 3289 | .map_err(|err| format!("request failed: {}", err.without_url()))?; |
| 3290 | let status = response.status(); |
| 3291 | if status.is_success() { |
| 3292 | // A valid 2xx verifies the key even when the body is not a usable |
| 3293 | // roster; failure-preserving catalog semantics then keep the |
| 3294 | // existing rows. |
| 3295 | let body = bounded_provider_catalog_text(response, PROVIDER_CATALOG_MAX_RESPONSE_BYTES) |
| 3296 | .await |
| 3297 | .unwrap_or_default(); |
| 3298 | let complete = |
| 3299 | serde_json::from_str::<ModelsPage<'_>>(&body).is_ok_and(|page| !page.has_more); |
| 3300 | let secrets = [api_key.trim().to_string()]; |
| 3301 | Ok(complete |
| 3302 | .then(|| { |
| 3303 | catalog_delta_from_models_body( |
| 3304 | provider, |
| 3305 | provider.as_str().to_string(), |
| 3306 | base_url, |
| 3307 | &body, |
| 3308 | &secrets, |
| 3309 | ) |
| 3310 | .ok() |
| 3311 | }) |
| 3312 | .flatten()) |
| 3313 | } else { |
| 3314 | let body = bounded_error_text(response, ERROR_BODY_MAX_BYTES).await; |
| 3315 | let body = if api_key.trim().is_empty() { |
| 3316 | body |
| 3317 | } else { |
| 3318 | redact_model_bound_text(&body, &[api_key.trim().to_string()]) |
| 3319 | }; |
| 3320 | let summary = if body.chars().count() > 200 { |
| 3321 | format!("{}...", body.chars().take(200).collect::<String>()) |
| 3322 | } else { |
| 3323 | body |
| 3324 | }; |
| 3325 | Err(format!("HTTP {status}: {summary}")) |
| 3326 | } |
| 3327 | } |
| 3328 | |
| 3329 | fn translation_system_prompt(target_language: &str) -> String { |
| 3330 | format!( |
| 3331 | "You are a professional translator. Your ONLY task is to translate text to {target_language}. \ |
| 3332 | Rules:\n\ |
| 3333 | 1. Output ONLY the translation, nothing else — no explanations, no notes, no quotes.\n\ |
| 3334 | 2. Preserve all code blocks (```...```), URLs, file paths, command names, \ |
| 3335 | and technical terms like API names, function names, and library names untranslated.\n\ |
| 3336 | 3. Keep Markdown formatting (headings, lists, bold, italics, links) intact.\n\ |
| 3337 | 4. Translate all natural-language prose naturally and professionally.\n\ |
| 3338 | 5. Do NOT add any prefix, suffix, or commentary.\n\ |
| 3339 | 6. If the input is already in {target_language} or contains no prose to translate, \ |
| 3340 | return it as-is." |
| 3341 | ) |
| 3342 | } |
| 3343 | |
| 3344 | fn translation_message_request( |
| 3345 | text: &str, |
| 3346 | model: String, |
| 3347 | target_language: &str, |
| 3348 | max_tokens: u32, |
| 3349 | ) -> MessageRequest { |
| 3350 | MessageRequest { |
| 3351 | model, |
| 3352 | messages: vec![Message { |
| 3353 | role: Role::User, |
| 3354 | content: vec![ContentBlock::Text { |
| 3355 | text: text.to_string(), |
| 3356 | cache_control: None, |
| 3357 | }], |
| 3358 | }], |
| 3359 | max_tokens, |
| 3360 | system: Some(SystemPrompt::Text(translation_system_prompt( |
| 3361 | target_language, |
| 3362 | ))), |
| 3363 | tools: None, |
| 3364 | tool_choice: None, |
| 3365 | metadata: None, |
| 3366 | thinking: None, |
| 3367 | reasoning_effort: Some("off".to_string()), |
| 3368 | stream: Some(false), |
| 3369 | temperature: None, |
| 3370 | top_p: None, |
| 3371 | safety_check: None, |
| 3372 | title: None, |
| 3373 | } |
| 3374 | } |
| 3375 | |
| 3376 | fn translation_text_from_response(response: &MessageResponse) -> Result<String> { |
| 3377 | let translated = response |
| 3378 | .content |
| 3379 | .iter() |
| 3380 | .filter_map(|block| match block { |
| 3381 | ContentBlock::Text { text, .. } => Some(text.as_str()), |
| 3382 | _ => None, |
| 3383 | }) |
| 3384 | .collect::<Vec<_>>() |
| 3385 | .join("") |
| 3386 | .trim() |
| 3387 | .to_string(); |
| 3388 | if translated.is_empty() { |
| 3389 | bail!("translate: Anthropic Messages response did not contain text content"); |
| 3390 | } |
| 3391 | Ok(translated) |
| 3392 | } |
| 3393 | |
| 3394 | fn xiaomi_mimo_base_url_uses_token_plan(base_url: &str) -> bool { |
| 3395 | let normalized = base_url.trim().to_ascii_lowercase(); |
| 3396 | let without_scheme = normalized |
| 3397 | .strip_prefix("https://") |
| 3398 | .or_else(|| normalized.strip_prefix("http://")) |
| 3399 | .unwrap_or(&normalized); |
| 3400 | let host = without_scheme |
| 3401 | .split(['/', '?', '#']) |
| 3402 | .next() |
| 3403 | .unwrap_or_default(); |
| 3404 | let host = host.split(':').next().unwrap_or(host); |
| 3405 | host.starts_with("token-plan-") && host.ends_with(".xiaomimimo.com") |
| 3406 | } |
| 3407 | |
| 3408 | fn xiaomi_mimo_api_key_uses_token_plan(api_key: &str) -> bool { |
| 3409 | api_key.trim_start().starts_with("tp-") |
| 3410 | } |
| 3411 | |
| 3412 | impl CodewhaleClient { |
| 3413 | /// Returns the API base URL used by this client. |
| 3414 | pub fn base_url(&self) -> &str { |
| 3415 | &self.base_url |
| 3416 | } |
| 3417 | |
| 3418 | /// Prepare — but do not send — the exact outbound request for `request`. |
| 3419 | /// |
| 3420 | /// This is *the* outbound seam (#1004). Production dispatch |
| 3421 | /// (`create_message`, `create_message_stream`) and `/preview-request` both |
| 3422 | /// call it, so a preview cannot describe a request different from the one |
| 3423 | /// a turn would send. |
| 3424 | /// |
| 3425 | /// It runs, in production order: |
| 3426 | /// |
| 3427 | /// 1. tool-history repair and model-bound secret redaction |
| 3428 | /// ([`Self::prepare_model_bound_request`]); |
| 3429 | /// 2. protocol binding and route model re-resolution |
| 3430 | /// ([`Self::bind_request_to_protocol`]); |
| 3431 | /// 3. the dialect's own body builder — Chat Completions, Anthropic |
| 3432 | /// Messages, or OpenAI Responses — including every provider-specific |
| 3433 | /// sanitizer and reasoning shaper; |
| 3434 | /// 4. exact endpoint resolution for that dialect and route shape. |
| 3435 | /// |
| 3436 | /// It performs no I/O and mutates no client state. |
| 3437 | pub fn prepare_outbound_request( |
| 3438 | &self, |
| 3439 | request: MessageRequest, |
| 3440 | stream: bool, |
| 3441 | ) -> Result<PreparedOutboundRequest> { |
| 3442 | let mut prepared = self.prepare_outbound_request_body(request.clone(), stream)?; |
| 3443 | let original_bytes = prepared.serialized_body_bytes()?; |
| 3444 | if original_bytes <= prepared::REQUEST_BODY_BYTE_TRIGGER { |
| 3445 | return Ok(prepared); |
| 3446 | } |
| 3447 | let total = codewhale_models::image_window::count_request_images(&request.messages); |
| 3448 | if total == 0 { |
| 3449 | return Ok(prepared); |
| 3450 | } |
| 3451 | let mut candidate = request.clone(); |
| 3452 | codewhale_models::image_window::cap_request_images_with_notes( |
| 3453 | &mut candidate.messages, |
| 3454 | 0, |
| 3455 | prepared::REQUEST_BODY_IMAGE_NOTE, |
| 3456 | prepared::REQUEST_BODY_IMAGE_NOTE, |
| 3457 | ); |
| 3458 | prepared = self.prepare_outbound_request_body(candidate, stream)?; |
| 3459 | let mut body_bytes = prepared.serialized_body_bytes()?; |
| 3460 | let mut retained = 0; |
| 3461 | let mut rejected = total; |
| 3462 | if body_bytes <= prepared::REQUEST_BODY_BYTE_TARGET { |
| 3463 | while retained + 1 < rejected { |
| 3464 | let keep = retained + (rejected - retained) / 2; |
| 3465 | let mut candidate = request.clone(); |
| 3466 | codewhale_models::image_window::cap_request_images_with_notes( |
| 3467 | &mut candidate.messages, |
| 3468 | keep, |
| 3469 | prepared::REQUEST_BODY_IMAGE_NOTE, |
| 3470 | prepared::REQUEST_BODY_IMAGE_NOTE, |
| 3471 | ); |
| 3472 | let candidate = self.prepare_outbound_request_body(candidate, stream)?; |
| 3473 | let candidate_bytes = candidate.serialized_body_bytes()?; |
| 3474 | if candidate_bytes <= prepared::REQUEST_BODY_BYTE_TARGET { |
| 3475 | retained = keep; |
| 3476 | body_bytes = candidate_bytes; |
| 3477 | prepared = candidate; |
| 3478 | } else { |
| 3479 | rejected = keep; |
| 3480 | } |
| 3481 | } |
| 3482 | } |
| 3483 | let chunk_retained = |
| 3484 | total - codewhale_models::image_window::images_to_elide(total, retained); |
| 3485 | if chunk_retained < retained { |
| 3486 | let mut candidate = request.clone(); |
| 3487 | codewhale_models::image_window::cap_request_images_with_notes( |
| 3488 | &mut candidate.messages, |
| 3489 | chunk_retained, |
| 3490 | prepared::REQUEST_BODY_IMAGE_NOTE, |
| 3491 | prepared::REQUEST_BODY_IMAGE_NOTE, |
| 3492 | ); |
| 3493 | prepared = self.prepare_outbound_request_body(candidate, stream)?; |
| 3494 | body_bytes = prepared.serialized_body_bytes()?; |
| 3495 | retained = chunk_retained; |
| 3496 | } |
| 3497 | if body_bytes >= original_bytes { |
| 3498 | return self.prepare_outbound_request_body(request, stream); |
| 3499 | } |
| 3500 | prepared.image_projection = Some(crate::llm_client::ImageProjectionReceipt { |
| 3501 | cause: "local_request_byte_budget".into(), |
| 3502 | original_image_blocks: total, |
| 3503 | omitted_oldest_blocks: total - retained, |
| 3504 | retained_newest_blocks: retained, |
| 3505 | body_bytes_before: original_bytes, |
| 3506 | body_bytes_after: body_bytes, |
| 3507 | omission_note: prepared::REQUEST_BODY_IMAGE_NOTE.into(), |
| 3508 | }); |
| 3509 | prepared.image_omission_notice = Some(format!( |
| 3510 | "Image request budget: omitted {} older image-bearing blocks; retained {retained} newest blocks. Serialized request reduced from {original_bytes} to {body_bytes} bytes. Original images remain in the session.", |
| 3511 | total - retained, |
| 3512 | )); |
| 3513 | Ok(prepared) |
| 3514 | } |
| 3515 | |
| 3516 | fn prepare_outbound_request_body( |
| 3517 | &self, |
| 3518 | request: MessageRequest, |
| 3519 | stream: bool, |
| 3520 | ) -> Result<PreparedOutboundRequest> { |
| 3521 | // Step 0: refuse role/dialect pairs this wire cannot represent, before |
| 3522 | // any dialect builds a body. Doing it here rather than inside each |
| 3523 | // adapter is what stops an unrepresentable role from being discovered |
| 3524 | // as an opaque provider 400 (Anthropic) or from vanishing silently |
| 3525 | // (the OpenAI-shaped dialects) depending on which adapter ran. |
| 3526 | let outbound_dialect = WireDialect::from_wire_format(self.wire_format); |
| 3527 | role_placement::reject_unsupported_roles(&request.messages, outbound_dialect)?; |
| 3528 | role_placement::validate_latest_reminder_messages(&request.messages)?; |
| 3529 | let clamp_output_cap = |mut request: MessageRequest, route_limits: Option<RouteLimits>| { |
| 3530 | let route_cap = self.effective_max_output_tokens_with_limits( |
| 3531 | &request.model, |
| 3532 | route_limits, |
| 3533 | request.reasoning_effort.as_deref(), |
| 3534 | ); |
| 3535 | if request.max_tokens > route_cap { |
| 3536 | tracing::debug!( |
| 3537 | requested_max_tokens = request.max_tokens, |
| 3538 | route_max_tokens = route_cap, |
| 3539 | model = %request.model, |
| 3540 | "clamped outbound max_tokens to the resolved route envelope" |
| 3541 | ); |
| 3542 | request.max_tokens = route_cap; |
| 3543 | } |
| 3544 | request |
| 3545 | }; |
| 3546 | let (request, request_route_limits) = |
| 3547 | self.bind_request_to_protocol(self.prepare_model_bound_request(request))?; |
| 3548 | let mut request = clamp_output_cap(request, request_route_limits); |
| 3549 | request.max_tokens = self.bounded_output_tokens( |
| 3550 | &self.wire_model_for_route(&request.model), |
| 3551 | request_route_limits, |
| 3552 | request.max_tokens, |
| 3553 | crate::compaction::estimate_request_input_tokens( |
| 3554 | &request.messages, |
| 3555 | request.system.as_ref(), |
| 3556 | request.tools.as_deref(), |
| 3557 | ), |
| 3558 | )?; |
| 3559 | let facts = if request.model == self.default_model { |
| 3560 | self.route_facts.clone() |
| 3561 | } else { |
| 3562 | self.catalog_facts_for_model(&request.model) |
| 3563 | } |
| 3564 | .filter(|facts| facts.wire_model_id == request.model); |
| 3565 | let mut published_wire_effort = None; |
| 3566 | if let Some(facts) = facts.as_deref() { |
| 3567 | if facts.temperature == Some(false) { |
| 3568 | request.temperature = None; |
| 3569 | request.top_p = None; |
| 3570 | } |
| 3571 | if facts.tool_call == Some(false) |
| 3572 | && request |
| 3573 | .tools |
| 3574 | .as_ref() |
| 3575 | .is_some_and(|tools| !tools.is_empty()) |
| 3576 | { |
| 3577 | anyhow::bail!("The selected provider offering does not support tool calls"); |
| 3578 | } |
| 3579 | if codewhale_config::models_dev::image_input_support(facts.modalities.as_ref()) |
| 3580 | == codewhale_config::route::CapabilityState::Unsupported |
| 3581 | && request |
| 3582 | .messages |
| 3583 | .iter() |
| 3584 | .flat_map(|message| &message.content) |
| 3585 | .any(|block| matches!(block, ContentBlock::ImageUrl { .. })) |
| 3586 | { |
| 3587 | anyhow::bail!("The selected provider offering does not support image input"); |
| 3588 | } |
| 3589 | if facts.reasoning == Some(false) { |
| 3590 | request.reasoning_effort = None; |
| 3591 | request.thinking = None; |
| 3592 | } else { |
| 3593 | for option in &facts.reasoning_options { |
| 3594 | if option.get("type").and_then(Value::as_str) != Some("effort") { |
| 3595 | continue; |
| 3596 | } |
| 3597 | if request |
| 3598 | .reasoning_effort |
| 3599 | .as_deref() |
| 3600 | .is_some_and(|effort| matches!(effort, "auto" | "default")) |
| 3601 | { |
| 3602 | request.reasoning_effort = option |
| 3603 | .get("default") |
| 3604 | .and_then(Value::as_str) |
| 3605 | .map(str::to_string); |
| 3606 | } |
| 3607 | let wire_effort = if matches!(self.wire_format, WireFormat::ChatCompletions) { |
| 3608 | request.reasoning_effort.as_deref().and_then(|effort| { |
| 3609 | let provider = self.chat_shape_provider(&request.model); |
| 3610 | let model = codewhale_config::route::resolve_model( |
| 3611 | provider, |
| 3612 | &request.model, |
| 3613 | Some(&self.base_url), |
| 3614 | ) |
| 3615 | .map_or_else( |
| 3616 | |_| request.model.trim().to_string(), |
| 3617 | |resolved| resolved.wire_id, |
| 3618 | ); |
| 3619 | let mut body = json!({ "model": model }); |
| 3620 | chat::apply_route_reasoning_controls_with_options( |
| 3621 | &mut body, |
| 3622 | provider, |
| 3623 | &self.base_url, |
| 3624 | &model, |
| 3625 | Some(effort), |
| 3626 | (!facts.reasoning_options.is_empty()) |
| 3627 | .then_some(facts.reasoning_options.as_slice()), |
| 3628 | ); |
| 3629 | body.get("reasoning_effort") |
| 3630 | .or_else(|| body.pointer("/reasoning/effort")) |
| 3631 | .and_then(Value::as_str) |
| 3632 | .map(str::to_string) |
| 3633 | }) |
| 3634 | } else { |
| 3635 | request.reasoning_effort.clone() |
| 3636 | }; |
| 3637 | let values = option.get("values").and_then(Value::as_array); |
| 3638 | let published = |effort: &str| { |
| 3639 | values.is_some_and(|values| { |
| 3640 | values.iter().any(|value| value.as_str() == Some(effort)) |
| 3641 | }) |
| 3642 | }; |
| 3643 | if matches!(self.wire_format, WireFormat::ChatCompletions) |
| 3644 | && let Some(wire) = wire_effort.as_deref() |
| 3645 | && let Some(requested) = request.reasoning_effort.as_deref() |
| 3646 | && !published(wire) |
| 3647 | && published(requested) |
| 3648 | { |
| 3649 | published_wire_effort = Some(requested.to_string()); |
| 3650 | continue; |
| 3651 | } |
| 3652 | if let Some(effort) = wire_effort.as_deref() |
| 3653 | && let Some(values) = values |
| 3654 | && !published(effort) |
| 3655 | && !(matches!(effort, "off" | "disabled" | "false") |
| 3656 | && (values.iter().any(|value| value.as_str() == Some("none")) |
| 3657 | || facts.reasoning_options.iter().any(|option| { |
| 3658 | option.get("type").and_then(Value::as_str) == Some("toggle") |
| 3659 | }))) |
| 3660 | { |
| 3661 | let mut offered = Vec::new(); |
| 3662 | for label in values |
| 3663 | .iter() |
| 3664 | .filter_map(Value::as_str) |
| 3665 | .filter_map( |
| 3666 | crate::reasoning_preference::ReasoningEffort::from_catalog_token, |
| 3667 | ) |
| 3668 | .map(crate::reasoning_preference::ReasoningEffort::as_setting) |
| 3669 | { |
| 3670 | if !offered.contains(&label) { |
| 3671 | offered.push(label); |
| 3672 | } |
| 3673 | } |
| 3674 | anyhow::bail!( |
| 3675 | "The selected provider offering does not support the resolved reasoning effort `{}`; it publishes: {}. Choose a published value or turn reasoning off", |
| 3676 | request.reasoning_effort.as_deref().unwrap_or(effort), |
| 3677 | if offered.is_empty() { |
| 3678 | "no recognized effort values".to_string() |
| 3679 | } else { |
| 3680 | offered.join(", ") |
| 3681 | } |
| 3682 | ); |
| 3683 | } |
| 3684 | } |
| 3685 | } |
| 3686 | } |
| 3687 | let declared_wire_model = self.declared_wire_model(&request.model).map(str::to_string); |
| 3688 | let strict_tools_disabled = self.is_local_ds4_model(&request.model); |
| 3689 | let requested_effort = request.reasoning_effort.clone(); |
| 3690 | // Same value computed for the seam above. |
| 3691 | let dialect = outbound_dialect; |
| 3692 | // `stream` is the caller's entry point, not a wire fact: each dialect |
| 3693 | // decides for itself what the body's `stream` field says. |
| 3694 | let entrypoint = CallerStreamMode::from_stream_flag(stream); |
| 3695 | |
| 3696 | let route_reasoning_options = facts |
| 3697 | .as_deref() |
| 3698 | .filter(|facts| !facts.reasoning_options.is_empty()) |
| 3699 | .map(|facts| facts.reasoning_options.as_slice()); |
| 3700 | |
| 3701 | match self.wire_format { |
| 3702 | WireFormat::ChatCompletions => { |
| 3703 | let chat_shape_provider = self.chat_shape_provider(&request.model); |
| 3704 | let mut wire = chat::build_chat_wire_body_with_window_and_options( |
| 3705 | &request, |
| 3706 | chat_shape_provider, |
| 3707 | &self.base_url, |
| 3708 | stream, |
| 3709 | request_route_limits, |
| 3710 | self.context_window_for_model(&request.model), |
| 3711 | strict_tools_disabled, |
| 3712 | route_reasoning_options, |
| 3713 | )?; |
| 3714 | if let Some(effort) = published_wire_effort.as_deref() { |
| 3715 | if wire.body.get("reasoning_effort").is_some() { |
| 3716 | wire.body["reasoning_effort"] = json!(effort); |
| 3717 | } else if let Some(slot) = wire.body.pointer_mut("/reasoning/effort") { |
| 3718 | *slot = json!(effort); |
| 3719 | } |
| 3720 | } |
| 3721 | if let Some(model) = &declared_wire_model { |
| 3722 | wire.model.clone_from(model); |
| 3723 | wire.body["model"] = json!(model); |
| 3724 | } |
| 3725 | self.apply_provider_routing(&mut wire.body); |
| 3726 | let url = chat_completions_url( |
| 3727 | self.chat_transport_base_url(), |
| 3728 | &self.base_url, |
| 3729 | self.api_provider, |
| 3730 | self.path_suffix.as_deref(), |
| 3731 | &wire.body, |
| 3732 | ); |
| 3733 | let shape = prepared::chat_route_shape( |
| 3734 | self.api_provider, |
| 3735 | &self.base_url, |
| 3736 | &wire.model, |
| 3737 | &url, |
| 3738 | ); |
| 3739 | Ok(PreparedOutboundRequest::new( |
| 3740 | dialect, |
| 3741 | self.endpoint_identity(url, shape), |
| 3742 | wire.model, |
| 3743 | wire.body, |
| 3744 | requested_effort, |
| 3745 | wire.replay_input_tokens, |
| 3746 | entrypoint, |
| 3747 | ) |
| 3748 | .with_omitted_tool_names(wire.omitted_tool_names)) |
| 3749 | } |
| 3750 | WireFormat::AnthropicMessages => { |
| 3751 | let (mut body, omitted_tool_names) = |
| 3752 | self.build_anthropic_wire_body(&request, stream)?; |
| 3753 | if let Some(model) = &declared_wire_model { |
| 3754 | body["model"] = json!(model); |
| 3755 | } |
| 3756 | let url = anthropic::anthropic_messages_url(&self.base_url); |
| 3757 | let shape = if self.api_provider == ProviderKind::OpencodeZen { |
| 3758 | RouteShape::OpencodeZen |
| 3759 | } else if self.api_provider == ProviderKind::Custom { |
| 3760 | RouteShape::CustomCompatible |
| 3761 | } else { |
| 3762 | RouteShape::Standard |
| 3763 | }; |
| 3764 | let wire_model = body |
| 3765 | .get("model") |
| 3766 | .and_then(Value::as_str) |
| 3767 | .unwrap_or(request.model.as_str()) |
| 3768 | .to_string(); |
| 3769 | Ok(PreparedOutboundRequest::new( |
| 3770 | dialect, |
| 3771 | self.endpoint_identity(url, shape), |
| 3772 | wire_model, |
| 3773 | body, |
| 3774 | requested_effort, |
| 3775 | None, |
| 3776 | entrypoint, |
| 3777 | ) |
| 3778 | .with_omitted_tool_names(omitted_tool_names)) |
| 3779 | } |
| 3780 | WireFormat::Responses => { |
| 3781 | let Some(profile_id) = self.responses_profile_id else { |
| 3782 | bail!( |
| 3783 | "responses client for {} has no dialect profile", |
| 3784 | self.api_provider.as_str() |
| 3785 | ); |
| 3786 | }; |
| 3787 | let Some(profile) = |
| 3788 | codewhale_config::responses_dialect::profile(profile_id.as_str()) |
| 3789 | else { |
| 3790 | bail!( |
| 3791 | "responses profile {} is not in the dialect table", |
| 3792 | profile_id.as_str() |
| 3793 | ); |
| 3794 | }; |
| 3795 | let (mut body, omitted_tool_names) = responses::build_responses_wire_body( |
| 3796 | &request, |
| 3797 | profile, |
| 3798 | responses::ResponsesReplayContext { |
| 3799 | provider_id: self.api_provider.as_str(), |
| 3800 | wire_model_id: request.model.as_str(), |
| 3801 | reasoning_api_id: self.chatgpt_reasoning_api.as_deref(), |
| 3802 | }, |
| 3803 | )?; |
| 3804 | if let Some(model) = &declared_wire_model { |
| 3805 | body["model"] = json!(model); |
| 3806 | } |
| 3807 | let is_codex = self.api_provider == ProviderKind::OpenaiCodex; |
| 3808 | let url = responses_api_url(&self.base_url, profile.endpoint.path); |
| 3809 | let shape = if is_codex { |
| 3810 | RouteShape::CodexResponses |
| 3811 | } else if self.api_provider == ProviderKind::OpencodeZen { |
| 3812 | RouteShape::OpencodeZen |
| 3813 | } else if self.api_provider == ProviderKind::Custom { |
| 3814 | RouteShape::CustomCompatible |
| 3815 | } else { |
| 3816 | RouteShape::Standard |
| 3817 | }; |
| 3818 | let wire_model = body |
| 3819 | .get("model") |
| 3820 | .and_then(Value::as_str) |
| 3821 | .unwrap_or(request.model.as_str()) |
| 3822 | .to_string(); |
| 3823 | Ok(PreparedOutboundRequest::new( |
| 3824 | dialect, |
| 3825 | self.endpoint_identity(url, shape), |
| 3826 | wire_model, |
| 3827 | body, |
| 3828 | requested_effort, |
| 3829 | None, |
| 3830 | entrypoint, |
| 3831 | ) |
| 3832 | .with_omitted_tool_names(omitted_tool_names)) |
| 3833 | } |
| 3834 | WireFormat::GenerateContent => { |
| 3835 | let wire_model = declared_wire_model |
| 3836 | .clone() |
| 3837 | .unwrap_or_else(|| request.model.clone()); |
| 3838 | let body = gemini::build_generate_content_body(&request); |
| 3839 | let url = gemini::gemini_generate_content_url(&self.base_url, &wire_model); |
| 3840 | let shape = if self.api_provider == ProviderKind::OpencodeZen { |
| 3841 | RouteShape::OpencodeZen |
| 3842 | } else if self.api_provider == ProviderKind::Custom { |
| 3843 | RouteShape::CustomCompatible |
| 3844 | } else { |
| 3845 | RouteShape::Standard |
| 3846 | }; |
| 3847 | Ok(PreparedOutboundRequest::new( |
| 3848 | dialect, |
| 3849 | self.endpoint_identity(url, shape), |
| 3850 | wire_model, |
| 3851 | body, |
| 3852 | requested_effort, |
| 3853 | None, |
| 3854 | entrypoint, |
| 3855 | )) |
| 3856 | } |
| 3857 | } |
| 3858 | .map(|prepared| prepared.with_responses_profile_id(self.responses_profile_id)) |
| 3859 | } |
| 3860 | |
| 3861 | pub fn apply_provider_routing(&self, body: &mut Value) { |
| 3862 | apply_openrouter_vendor(body, self.openrouter_vendor.as_deref()); |
| 3863 | } |
| 3864 | |
| 3865 | pub fn openrouter_vendor(&self) -> Option<&str> { |
| 3866 | self.openrouter_vendor.as_deref() |
| 3867 | } |
| 3868 | |
| 3869 | /// Typed identity of the endpoint this client would POST to. |
| 3870 | /// |
| 3871 | /// `route_id` is left empty here on purpose: the client knows the provider |
| 3872 | /// and the URL, but only the caller's resolved turn plan knows whether the |
| 3873 | /// user reached this route through a named custom-provider entry. The |
| 3874 | /// engine attaches it with [`PreparedOutboundRequest::with_route_id`]. |
| 3875 | fn endpoint_identity(&self, url: String, shape: RouteShape) -> EndpointIdentity { |
| 3876 | EndpointIdentity { |
| 3877 | provider_id: self.api_provider.as_str().to_string(), |
| 3878 | provider_display: self.api_provider.provider().display_name().to_string(), |
| 3879 | route_id: None, |
| 3880 | url, |
| 3881 | shape, |
| 3882 | } |
| 3883 | } |
| 3884 | |
| 3885 | /// Returns the active API provider for this client. |
| 3886 | pub fn api_provider(&self) -> ProviderKind { |
| 3887 | self.api_provider |
| 3888 | } |
| 3889 | |
| 3890 | pub fn admitted_provider_identity(&self) -> &ProviderIdentity { |
| 3891 | &self.admitted_identity |
| 3892 | } |
| 3893 | |
| 3894 | /// Route limits frozen with this client at resolution time. |
| 3895 | #[must_use] |
| 3896 | pub fn route_limits(&self) -> Option<RouteLimits> { |
| 3897 | self.route_limits |
| 3898 | } |
| 3899 | |
| 3900 | pub fn with_context_window( |
| 3901 | mut self, |
| 3902 | context_window: crate::route_runtime::ContextWindowResolution, |
| 3903 | ) -> Self { |
| 3904 | self.context_window = Some(context_window); |
| 3905 | self |
| 3906 | } |
| 3907 | |
| 3908 | fn context_window_for_model(&self, model: &str) -> Option<u32> { |
| 3909 | self.context_window_resolution_for_model(model) |
| 3910 | .map(|window| window.tokens) |
| 3911 | } |
| 3912 | |
| 3913 | pub fn context_window_resolution_for_model( |
| 3914 | &self, |
| 3915 | model: &str, |
| 3916 | ) -> Option<crate::route_runtime::ContextWindowResolution> { |
| 3917 | (model.trim() == self.default_model) |
| 3918 | .then_some(self.context_window) |
| 3919 | .flatten() |
| 3920 | } |
| 3921 | |
| 3922 | /// Output cap for a request dispatched by this exact client route. |
| 3923 | #[must_use] |
| 3924 | pub fn effective_max_output_tokens(&self, requested_model: &str) -> u32 { |
| 3925 | self.effective_max_output_tokens_with_limits( |
| 3926 | requested_model, |
| 3927 | self.route_limits_for_model(requested_model), |
| 3928 | None, |
| 3929 | ) |
| 3930 | } |
| 3931 | |
| 3932 | fn route_limits_for_model(&self, requested_model: &str) -> Option<RouteLimits> { |
| 3933 | if requested_model.trim() == self.default_model { |
| 3934 | self.route_limits |
| 3935 | } else { |
| 3936 | self.resolve_model_route(requested_model) |
| 3937 | .ok() |
| 3938 | .and_then(|candidate| crate::route_budget::known_route_limits(candidate.limits())) |
| 3939 | } |
| 3940 | } |
| 3941 | |
| 3942 | fn bounded_output_tokens( |
| 3943 | &self, |
| 3944 | model: &str, |
| 3945 | route_limits: Option<RouteLimits>, |
| 3946 | max_tokens: u32, |
| 3947 | input_tokens: usize, |
| 3948 | ) -> Result<u32> { |
| 3949 | crate::route_budget::request_output_cap_for_input_with_window( |
| 3950 | self.api_provider, |
| 3951 | model, |
| 3952 | route_limits, |
| 3953 | self.context_window_for_model(model), |
| 3954 | max_tokens, |
| 3955 | u64::try_from(input_tokens).unwrap_or(u64::MAX), |
| 3956 | ) |
| 3957 | .ok_or_else(|| { |
| 3958 | crate::llm_client::LlmError::ContextLengthError(format!( |
| 3959 | "about {input_tokens} input tokens leave no output room in this route's context window" |
| 3960 | )) |
| 3961 | .into() |
| 3962 | }) |
| 3963 | } |
| 3964 | |
| 3965 | #[must_use] |
| 3966 | fn effective_max_output_tokens_with_limits( |
| 3967 | &self, |
| 3968 | requested_model: &str, |
| 3969 | route_limits: Option<RouteLimits>, |
| 3970 | reasoning_effort: Option<&str>, |
| 3971 | ) -> u32 { |
| 3972 | let wire_model = self.wire_model_for_route(requested_model); |
| 3973 | crate::route_budget::effective_max_output_tokens_for_turn_with_window( |
| 3974 | self.api_provider, |
| 3975 | &wire_model, |
| 3976 | route_limits, |
| 3977 | self.context_window_for_model(requested_model), |
| 3978 | None, |
| 3979 | reasoning_effort, |
| 3980 | ) |
| 3981 | } |
| 3982 | |
| 3983 | pub async fn pin_exec_auth_scope(&mut self) -> Result<()> { |
| 3984 | if let Some(claude) = &self.claude_org { |
| 3985 | self.resume_account_scope = claude |
| 3986 | .pin_resume_identity() |
| 3987 | .await |
| 3988 | .map_err(anyhow::Error::new)? |
| 3989 | .map(|identity| serde_json::to_string(&identity)) |
| 3990 | .transpose()?; |
| 3991 | } else if self.plugin_provider.is_some() { |
| 3992 | let grant = self |
| 3993 | .with_plugin_authority(codewhale_runtime::oauth::pin_plugin_oauth_grant) |
| 3994 | .await?; |
| 3995 | self.exec_plugin_grant = Some(grant); |
| 3996 | self.resume_account_scope = Some(grant.to_string()); |
| 3997 | } |
| 3998 | Ok(()) |
| 3999 | } |
| 4000 | |
| 4001 | pub fn exec_route_binding( |
| 4002 | &self, |
| 4003 | key: &[u8; 32], |
| 4004 | config: &Config, |
| 4005 | ) -> Result<crate::route_receipt::ExecRouteBinding> { |
| 4006 | use crate::route_receipt::ExecRouteBinding; |
| 4007 | if self.go_route.is_some() { |
| 4008 | let mut binding = self.go_discovery_binding(key, config)?; |
| 4009 | binding.go_dispatch = Some(ExecRouteBinding::tag( |
| 4010 | key, |
| 4011 | b"go-dispatch-v1", |
| 4012 | &[ |
| 4013 | &self.base_url, |
| 4014 | &self.default_model, |
| 4015 | &format!("{:?}:{:?}", self.wire_format, self.responses_profile_id), |
| 4016 | ], |
| 4017 | )); |
| 4018 | return Ok(binding); |
| 4019 | } |
| 4020 | let endpoint = Some(ExecRouteBinding::endpoint_tag(key, &self.base_url)); |
| 4021 | let authority = if (self.plugin_provider.is_some() || self.claude_org.is_some()) |
| 4022 | && self.resume_account_scope.is_none() |
| 4023 | { |
| 4024 | None |
| 4025 | } else { |
| 4026 | let (source, credential) = self |
| 4027 | .resume_account_scope |
| 4028 | .as_deref() |
| 4029 | .map_or(("key", self.api_key.as_str()), |account| { |
| 4030 | ("account", account) |
| 4031 | }); |
| 4032 | let headers = config |
| 4033 | .http_headers() |
| 4034 | .into_iter() |
| 4035 | .collect::<std::collections::BTreeMap<_, _>>(); |
| 4036 | let headers = serde_json::to_string(&headers)?; |
| 4037 | let wire = format!("{:?}:{:?}", self.wire_format, self.responses_profile_id); |
| 4038 | Some(ExecRouteBinding::tag( |
| 4039 | key, |
| 4040 | b"authority", |
| 4041 | &[ |
| 4042 | self.admitted_identity.persisted_kind(), |
| 4043 | self.admitted_identity.key.as_str(), |
| 4044 | source, |
| 4045 | credential, |
| 4046 | self.path_suffix.as_deref().unwrap_or_default(), |
| 4047 | &wire, |
| 4048 | &headers, |
| 4049 | ], |
| 4050 | )) |
| 4051 | }; |
| 4052 | Ok(ExecRouteBinding { |
| 4053 | endpoint, |
| 4054 | authority, |
| 4055 | go_dispatch: None, |
| 4056 | }) |
| 4057 | } |
| 4058 | |
| 4059 | pub fn go_discovery_binding( |
| 4060 | &self, |
| 4061 | key: &[u8; 32], |
| 4062 | config: &Config, |
| 4063 | ) -> Result<crate::route_receipt::ExecRouteBinding> { |
| 4064 | use crate::route_receipt::ExecRouteBinding; |
| 4065 | anyhow::ensure!( |
| 4066 | self.api_provider == ProviderKind::OpencodeGo, |
| 4067 | "Expected the saved Go connection" |
| 4068 | ); |
| 4069 | let headers = config |
| 4070 | .http_headers() |
| 4071 | .into_iter() |
| 4072 | .collect::<std::collections::BTreeMap<_, _>>(); |
| 4073 | let authority = ExecRouteBinding::tag( |
| 4074 | key, |
| 4075 | b"go-discovery-v1", |
| 4076 | &[ |
| 4077 | self.admitted_identity.persisted_kind(), |
| 4078 | self.admitted_identity.key.as_str(), |
| 4079 | &self.api_key, |
| 4080 | self.path_suffix.as_deref().unwrap_or_default(), |
| 4081 | &serde_json::to_string(&headers)?, |
| 4082 | ], |
| 4083 | ); |
| 4084 | Ok(ExecRouteBinding { |
| 4085 | endpoint: Some(ExecRouteBinding::endpoint_tag(key, self.catalog_base_url())), |
| 4086 | authority: Some(authority), |
| 4087 | go_dispatch: None, |
| 4088 | }) |
| 4089 | } |
| 4090 | |
| 4091 | /// Secret-free receipt for the exact base endpoint and credential |
| 4092 | /// generation this client was constructed with. |
| 4093 | /// |
| 4094 | /// This is the only way the API key leaves `client.rs`, and it leaves as a |
| 4095 | /// one-way digest. Minting the receipt here — rather than re-reading config |
| 4096 | /// at some later lifecycle point — is what makes it immutable proof of the |
| 4097 | /// route that was actually installed for the turn. |
| 4098 | #[must_use] |
| 4099 | pub fn turn_route_receipt(&self) -> crate::route_receipt::TurnRouteReceipt { |
| 4100 | crate::route_receipt::TurnRouteReceipt::from_admitted( |
| 4101 | &self.admitted_identity, |
| 4102 | &self.default_model, |
| 4103 | &self.base_url, |
| 4104 | &self.api_key, |
| 4105 | ) |
| 4106 | .with_openrouter_vendor(self.openrouter_vendor.as_deref()) |
| 4107 | } |
| 4108 | |
| 4109 | /// The operator-declared `[[custom_models]]` rate for `model` on this |
| 4110 | /// client's exact endpoint, frozen at `dispatched_at`. Every dispatch |
| 4111 | /// boundary (background envelopes and main interactive turns alike) asks |
| 4112 | /// this before the provider lake, so a declared rate is honored the same |
| 4113 | /// way on each (#6690). |
| 4114 | #[must_use] |
| 4115 | pub fn configured_pricing_quote_at( |
| 4116 | &self, |
| 4117 | provider: ProviderKind, |
| 4118 | provider_identity: &str, |
| 4119 | model: &str, |
| 4120 | dispatched_at: u64, |
| 4121 | ) -> Option<crate::provider_catalog_live::ProviderLivePricingQuote> { |
| 4122 | crate::provider_catalog_live::configured_dispatch_pricing_quote_at( |
| 4123 | &self.configured_models, |
| 4124 | provider, |
| 4125 | provider_identity, |
| 4126 | model, |
| 4127 | &self.base_url, |
| 4128 | dispatched_at, |
| 4129 | ) |
| 4130 | } |
| 4131 | |
| 4132 | /// Capture the immutable, redacted route envelope at the caller's |
| 4133 | /// application-dispatch/admission time. This is not proof of network |
| 4134 | /// delivery or provider invoice-time pricing. The wire model is normalized |
| 4135 | /// exactly as the transport will normalize it; a provider-returned alias |
| 4136 | /// must never replace this billing identity later. |
| 4137 | #[must_use] |
| 4138 | pub fn effective_route_envelope( |
| 4139 | &self, |
| 4140 | requested_model: &str, |
| 4141 | dispatched_at: chrono::DateTime<chrono::Utc>, |
| 4142 | ) -> crate::cost_status::EffectiveRouteEnvelope { |
| 4143 | let model = self.wire_model_for_route(requested_model); |
| 4144 | let endpoint_fingerprint = crate::cost_status::endpoint_fingerprint(&self.base_url); |
| 4145 | let provider_live_pricing = u64::try_from(dispatched_at.timestamp()) |
| 4146 | .ok() |
| 4147 | .and_then(|at| { |
| 4148 | crate::provider_catalog_live::declared_or_catalog_quote( |
| 4149 | self.configured_pricing_quote_at( |
| 4150 | self.api_provider, |
| 4151 | self.admitted_identity.key.as_str(), |
| 4152 | &model, |
| 4153 | at, |
| 4154 | ), |
| 4155 | || { |
| 4156 | crate::provider_catalog_live::fresh_dispatch_pricing_quote_at( |
| 4157 | self.api_provider, |
| 4158 | self.admitted_identity.key.as_str(), |
| 4159 | &model, |
| 4160 | &self.base_url, |
| 4161 | at, |
| 4162 | ) |
| 4163 | }, |
| 4164 | ) |
| 4165 | }); |
| 4166 | crate::cost_status::EffectiveRouteEnvelope { |
| 4167 | openrouter_vendor: self.openrouter_vendor.clone(), |
| 4168 | provider: self.api_provider, |
| 4169 | provider_identity: self.admitted_identity.key.to_string(), |
| 4170 | model, |
| 4171 | billing_surface: self.billing_surface.clone(), |
| 4172 | endpoint_fingerprint, |
| 4173 | provider_live_pricing, |
| 4174 | billing_mode: self.billing_mode, |
| 4175 | dispatched_at, |
| 4176 | } |
| 4177 | } |
| 4178 | |
| 4179 | /// Resolved in-flight provider request cap, if one is active. |
| 4180 | #[must_use] |
| 4181 | pub fn provider_request_concurrency_limit(&self) -> Option<usize> { |
| 4182 | self.request_concurrency |
| 4183 | .as_ref() |
| 4184 | .map(ProviderConcurrencyLimiter::limit) |
| 4185 | } |
| 4186 | |
| 4187 | /// Number of currently active requests held by this client's shared |
| 4188 | /// provider request limiter. |
| 4189 | #[must_use] |
| 4190 | pub fn active_provider_requests(&self) -> usize { |
| 4191 | self.request_concurrency |
| 4192 | .as_ref() |
| 4193 | .map_or(0, ProviderConcurrencyLimiter::active) |
| 4194 | } |
| 4195 | |
| 4196 | async fn acquire_provider_request_permit(&self) -> Option<ProviderRequestPermit> { |
| 4197 | match self.request_concurrency.as_ref() { |
| 4198 | Some(limiter) => limiter.acquire().await, |
| 4199 | None => None, |
| 4200 | } |
| 4201 | } |
| 4202 | |
| 4203 | pub async fn acquire_remote_control_inference_permit( |
| 4204 | &self, |
| 4205 | ) -> Option<RemoteControlInferencePermit> { |
| 4206 | if !self.remote_control_inference_participant { |
| 4207 | return None; |
| 4208 | } |
| 4209 | Some(acquire_remote_control_inference_participant().await) |
| 4210 | } |
| 4211 | |
| 4212 | fn hold_provider_request_permit_for_stream( |
| 4213 | stream: crate::llm_client::StreamEventBox, |
| 4214 | permit: Option<ProviderRequestPermit>, |
| 4215 | ) -> crate::llm_client::StreamEventBox { |
| 4216 | Box::pin(async_stream::stream! { |
| 4217 | let _permit = permit; |
| 4218 | let mut stream = stream; |
| 4219 | while let Some(event) = stream.next().await { |
| 4220 | yield event; |
| 4221 | } |
| 4222 | }) |
| 4223 | } |
| 4224 | |
| 4225 | fn hold_remote_control_inference_permit_for_stream( |
| 4226 | stream: crate::llm_client::StreamEventBox, |
| 4227 | permit: Option<RemoteControlInferencePermit>, |
| 4228 | ) -> crate::llm_client::StreamEventBox { |
| 4229 | Box::pin(async_stream::stream! { |
| 4230 | let _permit = permit; |
| 4231 | let mut stream = stream; |
| 4232 | while let Some(event) = stream.next().await { |
| 4233 | yield event; |
| 4234 | } |
| 4235 | }) |
| 4236 | } |
| 4237 | |
| 4238 | /// Translate text to the requested target language using a focused |
| 4239 | /// non-streaming chat completion call on the supplied model. |
| 4240 | /// |
| 4241 | /// This is a lightweight translation service — no tool calls, no |
| 4242 | /// streaming, no conversation history. The dedicated translation agent |
| 4243 | /// receives the source text and returns only the translated result. |
| 4244 | pub async fn translate_with_usage( |
| 4245 | &self, |
| 4246 | text: &str, |
| 4247 | model: &str, |
| 4248 | target_language: &str, |
| 4249 | source: &crate::cost_status::NativeUsageSource, |
| 4250 | ) -> Result<TranslationProviderResponse> { |
| 4251 | let route = self.effective_route_envelope(model, chrono::Utc::now()); |
| 4252 | let observation = source.observation(); |
| 4253 | let wire = observation.wire_observations.clone(); |
| 4254 | let response = crate::llm_client::observe_request_retries( |
| 4255 | Some(observation), |
| 4256 | self.translate_prepared_with_usage(text, model, target_language, route.clone()), |
| 4257 | ) |
| 4258 | .await; |
| 4259 | let wire = wire.drain(); |
| 4260 | let usage = response |
| 4261 | .as_ref() |
| 4262 | .ok() |
| 4263 | .and_then(|response| response.usage.clone()) |
| 4264 | .unwrap_or_default(); |
| 4265 | let coverage = if wire.last_transmission.is_some() { |
| 4266 | wire.usage_coverage(usage != Usage::default(), response.is_ok()) |
| 4267 | } else { |
| 4268 | match &response { |
| 4269 | Ok(_) if usage != Usage::default() => { |
| 4270 | crate::llm_client::ProviderUsageCoverage::Reported |
| 4271 | } |
| 4272 | Ok(_) => crate::llm_client::ProviderUsageCoverage::Missing, |
| 4273 | Err(error) => match error |
| 4274 | .downcast_ref::<crate::llm_client::LlmError>() |
| 4275 | .map(crate::llm_client::LlmError::transmission) |
| 4276 | { |
| 4277 | Some(crate::llm_client::RequestTransmission::NotDispatched) => { |
| 4278 | crate::llm_client::ProviderUsageCoverage::NotDispatched |
| 4279 | } |
| 4280 | Some(crate::llm_client::RequestTransmission::Rejected) => { |
| 4281 | crate::llm_client::ProviderUsageCoverage::Rejected |
| 4282 | } |
| 4283 | _ => crate::llm_client::ProviderUsageCoverage::Missing, |
| 4284 | }, |
| 4285 | } |
| 4286 | }; |
| 4287 | let record = source.prepare_record( |
| 4288 | &route, |
| 4289 | &usage, |
| 4290 | coverage, |
| 4291 | if response.is_ok() { |
| 4292 | crate::cost_status::RuntimeUsageMissingReason::SuccessWithoutUsage |
| 4293 | } else { |
| 4294 | crate::cost_status::RuntimeUsageMissingReason::RequestOutcomeUnknown |
| 4295 | }, |
| 4296 | &wire, |
| 4297 | ); |
| 4298 | if let Some(origin) = source.origin() { |
| 4299 | crate::cost_status::record_runtime_usage_async(origin.scope(), Some(origin), &record) |
| 4300 | .await; |
| 4301 | } |
| 4302 | response.map(|mut response| { |
| 4303 | response.accounting = Some(record); |
| 4304 | response |
| 4305 | }) |
| 4306 | } |
| 4307 | |
| 4308 | async fn translate_prepared_with_usage( |
| 4309 | &self, |
| 4310 | text: &str, |
| 4311 | model: &str, |
| 4312 | target_language: &str, |
| 4313 | route: crate::cost_status::EffectiveRouteEnvelope, |
| 4314 | ) -> Result<TranslationProviderResponse> { |
| 4315 | // Freeze pricing before either the remote-control gate or the provider |
| 4316 | // permit. A later live-catalog refresh must not reprice this request. |
| 4317 | let _inference = self.acquire_remote_control_inference_permit().await; |
| 4318 | let _permit = self.acquire_provider_request_permit().await; |
| 4319 | let model = self.wire_model_for_route(model); |
| 4320 | let max_tokens = self.effective_max_output_tokens(&model); |
| 4321 | let probe = translation_message_request(text, model.clone(), target_language, max_tokens); |
| 4322 | let max_tokens = self.bounded_output_tokens( |
| 4323 | &model, |
| 4324 | self.route_limits_for_model(&model), |
| 4325 | max_tokens, |
| 4326 | crate::compaction::estimate_request_input_tokens( |
| 4327 | &probe.messages, |
| 4328 | probe.system.as_ref(), |
| 4329 | None, |
| 4330 | ), |
| 4331 | )?; |
| 4332 | if self.wire_format != WireFormat::ChatCompletions { |
| 4333 | // Non-Chat dialects reuse the prepared-request seam so translation |
| 4334 | // cannot drift from production shaping. Translation is still an |
| 4335 | // *auxiliary* call, not a primary agent turn: the Chat dialect |
| 4336 | // below builds its own small fixed body, and `/preview-request` |
| 4337 | // deliberately does not claim to describe either |
| 4338 | // (see `docs/PREVIEW_REQUEST.md`). |
| 4339 | let prepared = self.prepare_outbound_request( |
| 4340 | translation_message_request(text, model, target_language, max_tokens), |
| 4341 | false, |
| 4342 | )?; |
| 4343 | let response = match prepared.dialect { |
| 4344 | WireDialect::OpenAiResponses => self.handle_responses_message(&prepared).await?, |
| 4345 | WireDialect::AnthropicMessages => self.handle_anthropic_message(&prepared).await?, |
| 4346 | WireDialect::GenerateContent => self.handle_gemini_message(&prepared).await?, |
| 4347 | WireDialect::ChatCompletions => unreachable!(), |
| 4348 | }; |
| 4349 | let usage = (response.usage != Usage::default()).then_some(response.usage.clone()); |
| 4350 | let translated = |
| 4351 | if codewhale_models::is_incomplete_stop_reason(response.stop_reason.as_deref()) { |
| 4352 | Err(anyhow::anyhow!( |
| 4353 | "translate: provider response incomplete ({})", |
| 4354 | codewhale_models::stop_reason_detail(response.stop_reason.as_deref()) |
| 4355 | )) |
| 4356 | } else { |
| 4357 | translation_text_from_response(&response) |
| 4358 | }; |
| 4359 | return Ok(TranslationProviderResponse { |
| 4360 | accounting: None, |
| 4361 | |
| 4362 | translated, |
| 4363 | route, |
| 4364 | usage, |
| 4365 | }); |
| 4366 | } |
| 4367 | |
| 4368 | let url = api_url_with_suffix( |
| 4369 | self.chat_transport_base_url(), |
| 4370 | "chat/completions", |
| 4371 | self.path_suffix.as_deref(), |
| 4372 | ); |
| 4373 | let mut body = serde_json::json!({ |
| 4374 | "model": model, |
| 4375 | "messages": [ |
| 4376 | { |
| 4377 | "role": "system", |
| 4378 | "content": translation_system_prompt(target_language) |
| 4379 | }, |
| 4380 | { |
| 4381 | "role": "user", |
| 4382 | "content": text |
| 4383 | } |
| 4384 | ], |
| 4385 | "max_tokens": max_tokens, |
| 4386 | "stream": false |
| 4387 | }); |
| 4388 | chat::apply_route_reasoning_controls( |
| 4389 | &mut body, |
| 4390 | self.chat_shape_provider(&model), |
| 4391 | &self.base_url, |
| 4392 | &model, |
| 4393 | Some("off"), |
| 4394 | ); |
| 4395 | |
| 4396 | self.apply_provider_routing(&mut body); |
| 4397 | let response = self.send_json_with_retry(&url, &body).await?; |
| 4398 | let status = response.status(); |
| 4399 | if !status.is_success() { |
| 4400 | let raw_error_text = bounded_error_text(response, ERROR_BODY_MAX_BYTES).await; |
| 4401 | let error_text = sanitize_http_error_body( |
| 4402 | Some(self.api_provider.provider().display_name()), |
| 4403 | status.as_u16(), |
| 4404 | &raw_error_text, |
| 4405 | ); |
| 4406 | anyhow::bail!("translate: HTTP {status}: {error_text}"); |
| 4407 | } |
| 4408 | |
| 4409 | let value: serde_json::Value = response.json().await?; |
| 4410 | let usage_reported = value |
| 4411 | .get("usage") |
| 4412 | .and_then(Value::as_object) |
| 4413 | .is_some_and(|usage| { |
| 4414 | [ |
| 4415 | "input_tokens", |
| 4416 | "prompt_tokens", |
| 4417 | "output_tokens", |
| 4418 | "completion_tokens", |
| 4419 | "total_tokens", |
| 4420 | ] |
| 4421 | .iter() |
| 4422 | .any(|field| usage.contains_key(*field)) |
| 4423 | }); |
| 4424 | let usage = parse_usage(value.get("usage")); |
| 4425 | let stop_reason = value["choices"][0]["finish_reason"].as_str(); |
| 4426 | let stop_reason = if codewhale_models::stop_contradicts_output_ceiling( |
| 4427 | stop_reason, |
| 4428 | usage_reported.then_some(usage.output_tokens), |
| 4429 | max_tokens, |
| 4430 | ) { |
| 4431 | Some(codewhale_models::OUTPUT_CEILING_STOP_REASON) |
| 4432 | } else { |
| 4433 | stop_reason |
| 4434 | }; |
| 4435 | let usage = (usage_reported && usage != Usage::default()).then_some(usage); |
| 4436 | let translated = if codewhale_models::is_incomplete_stop_reason(stop_reason) { |
| 4437 | Err(anyhow::anyhow!( |
| 4438 | "translate: provider response incomplete ({})", |
| 4439 | codewhale_models::stop_reason_detail(stop_reason) |
| 4440 | )) |
| 4441 | } else { |
| 4442 | value["choices"][0]["message"]["content"] |
| 4443 | .as_str() |
| 4444 | .ok_or_else(|| anyhow::anyhow!("translate: unexpected API response shape")) |
| 4445 | .and_then(|translated| { |
| 4446 | let translated = translated.trim().to_string(); |
| 4447 | if translated.is_empty() { |
| 4448 | bail!("translate: provider response did not contain text content"); |
| 4449 | } |
| 4450 | Ok(translated) |
| 4451 | }) |
| 4452 | }; |
| 4453 | |
| 4454 | Ok(TranslationProviderResponse { |
| 4455 | accounting: None, |
| 4456 | |
| 4457 | translated, |
| 4458 | route, |
| 4459 | usage, |
| 4460 | }) |
| 4461 | } |
| 4462 | |
| 4463 | /// Test adapter for asserting the translated text; production retains receipts. |
| 4464 | #[cfg(test)] |
| 4465 | async fn translate(&self, text: &str, model: &str, target_language: &str) -> Result<String> { |
| 4466 | self.translate_with_usage( |
| 4467 | text, |
| 4468 | model, |
| 4469 | target_language, |
| 4470 | &crate::cost_status::NativeUsageSource::capture( |
| 4471 | format!("translation-test:{}", uuid::Uuid::new_v4()), |
| 4472 | crate::cost_status::UsageSpendOwner::Auxiliary, |
| 4473 | ), |
| 4474 | ) |
| 4475 | .await? |
| 4476 | .translated |
| 4477 | } |
| 4478 | |
| 4479 | /// List every available model under the endpoint's verified pagination contract. |
| 4480 | pub async fn list_models(&self) -> Result<Vec<AvailableModel>> { |
| 4481 | let (body, deadline) = self |
| 4482 | .models_document(ModelsRequestMode::Interactive) |
| 4483 | .await |
| 4484 | .map_err(ModelsFetchError::into_interactive)?; |
| 4485 | let models = if self.api_provider == ProviderKind::OpencodeGo |
| 4486 | && let Some(offerings) = opencode_catalog::parse( |
| 4487 | &body, |
| 4488 | &self.catalog_provider_id(), |
| 4489 | self.catalog_base_url(), |
| 4490 | &base_url_fingerprint(self.catalog_base_url()), |
| 4491 | now_unix(), |
| 4492 | &self.catalog_error_secret_values, |
| 4493 | ) |
| 4494 | .map_err(|error| ModelsFetchError::Catalog(error).into_interactive())? |
| 4495 | { |
| 4496 | let mut models: Vec<_> = offerings |
| 4497 | .into_iter() |
| 4498 | .filter(|row| { |
| 4499 | self.api_provider |
| 4500 | .provider() |
| 4501 | .wire_policy() |
| 4502 | .resolve(&row.endpoint_key) |
| 4503 | .is_some() |
| 4504 | }) |
| 4505 | .map(|row| AvailableModel { |
| 4506 | id: row.wire_model_id, |
| 4507 | owned_by: None, |
| 4508 | created: None, |
| 4509 | display_name: row.name, |
| 4510 | context_window: row |
| 4511 | .limit |
| 4512 | .and_then(|limit| limit.context) |
| 4513 | .and_then(|n| u32::try_from(n).ok()), |
| 4514 | effective_context_window_percent: None, |
| 4515 | reasoning: row.reasoning, |
| 4516 | efforts: Vec::new(), |
| 4517 | }) |
| 4518 | .collect(); |
| 4519 | models.sort_by(|left, right| left.id.cmp(&right.id)); |
| 4520 | models |
| 4521 | } else { |
| 4522 | parse_models_response_for_provider(&body, self.api_provider) |
| 4523 | .map(|models| apply_provider_model_cutline(self.api_provider, models)) |
| 4524 | .map_err(|_| { |
| 4525 | ModelsFetchError::Catalog(CatalogRefreshError::InvalidResponse) |
| 4526 | .into_interactive() |
| 4527 | })? |
| 4528 | }; |
| 4529 | if tokio::time::Instant::now() >= deadline { |
| 4530 | return Err(ModelsFetchError::Catalog(CatalogRefreshError::Network).into_interactive()); |
| 4531 | } |
| 4532 | if self.api_provider == ProviderKind::OpenaiCodex |
| 4533 | && models.iter().any(|model| { |
| 4534 | self.model_bound_secret_values.iter().any(|secret| { |
| 4535 | !secret.is_empty() |
| 4536 | && (model.id.contains(secret.as_str()) |
| 4537 | || model |
| 4538 | .display_name |
| 4539 | .as_deref() |
| 4540 | .is_some_and(|name| name.contains(secret.as_str()))) |
| 4541 | }) |
| 4542 | }) |
| 4543 | { |
| 4544 | return Err( |
| 4545 | ModelsFetchError::Catalog(CatalogRefreshError::InvalidResponse).into_interactive(), |
| 4546 | ); |
| 4547 | } |
| 4548 | Ok(models) |
| 4549 | } |
| 4550 | |
| 4551 | fn catalog_base_url(&self) -> &str { |
| 4552 | self.catalog_connection_base |
| 4553 | .as_deref() |
| 4554 | .unwrap_or(&self.base_url) |
| 4555 | } |
| 4556 | |
| 4557 | async fn models_document( |
| 4558 | &self, |
| 4559 | mode: ModelsRequestMode, |
| 4560 | ) -> Result<(String, tokio::time::Instant), ModelsFetchError> { |
| 4561 | if model_listing_unavailable(self.api_provider, &self.base_url) { |
| 4562 | return Err(ModelsFetchError::Interactive(anyhow::anyhow!( |
| 4563 | "This provider has no documented model-list endpoint; select a configured model instead" |
| 4564 | ))); |
| 4565 | } |
| 4566 | let mut endpoint = reqwest::Url::parse(&model_listing_url( |
| 4567 | self.api_provider, |
| 4568 | self.catalog_base_url(), |
| 4569 | )) |
| 4570 | .map_err(|_| CatalogRefreshError::InvalidResponse)?; |
| 4571 | // OrcaRouter scopes `GET /v1/models` to one capability. Ask for the chat |
| 4572 | // roster so the model control is the real chat list rather than every |
| 4573 | // kind the account can reach; other providers take the unfiltered |
| 4574 | // listing. Non-text rows are dropped again by the chat endpoint filter. |
| 4575 | if self.api_provider == ProviderKind::Orcarouter { |
| 4576 | endpoint.query_pairs_mut().append_pair("capability", "chat"); |
| 4577 | } |
| 4578 | // https://platform.claude.com/docs/en/api/models/list specifies after_id. |
| 4579 | // Go is unpaginated. A Messages generation dialect or a custom identity |
| 4580 | // resembling a built-in provider does not establish this list contract. |
| 4581 | let cursor_query = (self.api_provider == ProviderKind::Anthropic).then_some("after_id"); |
| 4582 | self.models_document_at(endpoint, cursor_query, mode).await |
| 4583 | } |
| 4584 | |
| 4585 | async fn models_document_at( |
| 4586 | &self, |
| 4587 | endpoint: reqwest::Url, |
| 4588 | cursor_query: Option<&str>, |
| 4589 | mode: ModelsRequestMode, |
| 4590 | ) -> Result<(String, tokio::time::Instant), ModelsFetchError> { |
| 4591 | collect_models_document( |
| 4592 | endpoint, |
| 4593 | cursor_query, |
| 4594 | MODELS_FETCH_LIMITS, |
| 4595 | |url| async move { |
| 4596 | let build = || { |
| 4597 | self.models_http_client |
| 4598 | .get(url.clone()) |
| 4599 | .timeout(NON_STREAMING_HTTP_TIMEOUT) |
| 4600 | }; |
| 4601 | let response = match mode { |
| 4602 | // #6173: the provider's own words, minus this client's |
| 4603 | // secrets and this request's cursor. The endpoint is not |
| 4604 | // established here — it is whatever the user typed during |
| 4605 | // setup — so the body is guarded rather than trusted. |
| 4606 | ModelsRequestMode::Interactive => { |
| 4607 | let disclosure = ErrorBodyDisclosure::Guarded { |
| 4608 | request_secrets: request_query_secret_values(&url), |
| 4609 | }; |
| 4610 | // The pinned 30s per-attempt total survives: the retry |
| 4611 | // loop's shared envelope is not allowed to overwrite a |
| 4612 | // caller's own budget. |
| 4613 | self.send_with_retry_total_error_body( |
| 4614 | NON_STREAMING_HTTP_TIMEOUT, |
| 4615 | build, |
| 4616 | &disclosure, |
| 4617 | crate::llm_client::RetryOperation::ReadOnly, |
| 4618 | ) |
| 4619 | .await |
| 4620 | .map_err(ModelsFetchError::Interactive)? |
| 4621 | } |
| 4622 | ModelsRequestMode::Refresh => self |
| 4623 | .authorize_plugin_request(build()) |
| 4624 | .await |
| 4625 | .map_err(|_| CatalogRefreshError::Unauthorized)? |
| 4626 | .send() |
| 4627 | .await |
| 4628 | .map_err(|_| CatalogRefreshError::Network)?, |
| 4629 | }; |
| 4630 | if !response.status().is_success() { |
| 4631 | return Err(ModelsFetchError::Catalog( |
| 4632 | match response.status().as_u16() { |
| 4633 | 401 => CatalogRefreshError::Unauthorized, |
| 4634 | 403 => CatalogRefreshError::Forbidden, |
| 4635 | 404 => CatalogRefreshError::NotFound, |
| 4636 | 429 => CatalogRefreshError::RateLimited, |
| 4637 | _ => CatalogRefreshError::Network, |
| 4638 | }, |
| 4639 | )); |
| 4640 | } |
| 4641 | Ok(response) |
| 4642 | }, |
| 4643 | ) |
| 4644 | .await |
| 4645 | } |
| 4646 | |
| 4647 | /// The catalog provider id for this client (the `ProviderKind` slug, falling |
| 4648 | /// back to the `ProviderKind` slug for legacy variants without a kind). This |
| 4649 | /// is the id used as the cache scope and `CatalogOffering.provider`. |
| 4650 | fn catalog_provider_id(&self) -> String { |
| 4651 | self.admitted_identity.key.to_string() |
| 4652 | } |
| 4653 | |
| 4654 | /// Whether this route speaks Baseten's `/models` dialect. |
| 4655 | /// |
| 4656 | /// Schema recognition is by endpoint, never by table name: whatever the |
| 4657 | /// user called the `[providers.<name>]` table, the wire shape is a fact |
| 4658 | /// about the host (#6289). Catalog ownership still uses the exact |
| 4659 | /// configured identity, so a renamed Baseten table keeps its own |
| 4660 | /// partition. |
| 4661 | #[cfg(test)] |
| 4662 | fn catalog_endpoint_is_baseten(&self) -> bool { |
| 4663 | catalog_endpoint_is_baseten(self.api_provider, &self.base_url) |
| 4664 | } |
| 4665 | |
| 4666 | /// Fetch the provider's live model listing as a secret-free |
| 4667 | /// [`ProviderCatalogDelta`] (#3385). |
| 4668 | /// |
| 4669 | /// Uses the listing auth client, with native catalog routes for Ollama, |
| 4670 | /// and fetches pages without `send_with_retry` so a refresh |
| 4671 | /// failure stays typed and non-fatal — bundled / saved / static rows are |
| 4672 | /// untouched. The delta is scoped to the base-URL fingerprint and stamped |
| 4673 | /// with the fetch time; the API key authorizes the request but is **never** |
| 4674 | /// persisted into the delta or cache. Unknown live rows carry no canonical |
| 4675 | /// model, capabilities, or pricing, per the #3385 contract. |
| 4676 | pub async fn fetch_catalog_delta(&self) -> Result<ProviderCatalogDelta, CatalogRefreshError> { |
| 4677 | if self.api_provider == ProviderKind::Ollama { |
| 4678 | let origin = ollama_catalog::ollama_native_origin(&self.base_url); |
| 4679 | let tags_url = reqwest::Url::parse(&format!("{origin}/api/tags")) |
| 4680 | .map_err(|_| CatalogRefreshError::InvalidResponse)?; |
| 4681 | let (body, deadline) = self |
| 4682 | .models_document_at(tags_url, None, ModelsRequestMode::Refresh) |
| 4683 | .await |
| 4684 | .map_err(ModelsFetchError::into_catalog)?; |
| 4685 | let (tags, mut profiles) = ollama_catalog::parse_ollama_tags_with_profiles(&body) |
| 4686 | .map_err(|_| CatalogRefreshError::InvalidResponse)?; |
| 4687 | if tags.iter().any(|tag| { |
| 4688 | self.model_bound_secret_values |
| 4689 | .iter() |
| 4690 | .any(|secret| !secret.is_empty() && tag.contains(secret)) |
| 4691 | }) { |
| 4692 | return Err(CatalogRefreshError::InvalidResponse); |
| 4693 | } |
| 4694 | let fetched = tokio::time::timeout_at( |
| 4695 | deadline, |
| 4696 | ollama_catalog::fetch_tag_profiles(&tags, &profiles, |tag| { |
| 4697 | let origin = &origin; |
| 4698 | async move { |
| 4699 | let result = async { |
| 4700 | let request = self |
| 4701 | .models_http_client |
| 4702 | .post(format!("{origin}/api/show")) |
| 4703 | .json(&serde_json::json!({ "model": tag })) |
| 4704 | .timeout(Duration::from_secs(2)); |
| 4705 | let response = |
| 4706 | self.authorize_plugin_request(request).await?.send().await?; |
| 4707 | anyhow::ensure!( |
| 4708 | response.status().is_success(), |
| 4709 | "Ollama profile request failed" |
| 4710 | ); |
| 4711 | let body = bounded_provider_catalog_text( |
| 4712 | response, |
| 4713 | PROVIDER_CATALOG_MAX_RESPONSE_BYTES, |
| 4714 | ) |
| 4715 | .await |
| 4716 | .map_err(|reason| { |
| 4717 | anyhow::anyhow!("Ollama profile rejected: {reason:?}") |
| 4718 | })?; |
| 4719 | ollama_catalog::parse_ollama_show_response(&body) |
| 4720 | } |
| 4721 | .await; |
| 4722 | result.map_err(|error: anyhow::Error| { |
| 4723 | anyhow::anyhow!(self.redact_model_bound_text(&error.to_string())) |
| 4724 | }) |
| 4725 | } |
| 4726 | }), |
| 4727 | ) |
| 4728 | .await |
| 4729 | .map_err(|_| CatalogRefreshError::Network)?; |
| 4730 | ollama_catalog::merge_ollama_profiles(&mut profiles, fetched); |
| 4731 | let running_url = reqwest::Url::parse(&format!("{origin}/api/ps")) |
| 4732 | .map_err(|_| CatalogRefreshError::InvalidResponse)?; |
| 4733 | let running_deadline = |
| 4734 | deadline.min(tokio::time::Instant::now() + Duration::from_secs(2)); |
| 4735 | let running = tokio::time::timeout_at( |
| 4736 | running_deadline, |
| 4737 | self.models_document_at(running_url, None, ModelsRequestMode::Refresh), |
| 4738 | ) |
| 4739 | .await |
| 4740 | .ok() |
| 4741 | .and_then(Result::ok) |
| 4742 | .map(|(body, _)| body); |
| 4743 | let delta = ollama_catalog::ollama_catalog_delta( |
| 4744 | &self.catalog_provider_id(), |
| 4745 | &self.base_url, |
| 4746 | &tags, |
| 4747 | &profiles, |
| 4748 | running.as_deref(), |
| 4749 | ); |
| 4750 | if tokio::time::Instant::now() >= deadline |
| 4751 | || delta.offerings.iter().any(|row| { |
| 4752 | self.model_bound_secret_values |
| 4753 | .iter() |
| 4754 | .any(|secret| !secret.is_empty() && row.wire_model_id.contains(secret)) |
| 4755 | }) |
| 4756 | { |
| 4757 | return Err(CatalogRefreshError::InvalidResponse); |
| 4758 | } |
| 4759 | return Ok(delta); |
| 4760 | } |
| 4761 | let (body, deadline) = self |
| 4762 | .models_document(ModelsRequestMode::Refresh) |
| 4763 | .await |
| 4764 | .map_err(ModelsFetchError::into_catalog)?; |
| 4765 | |
| 4766 | let delta = catalog_delta_from_models_body( |
| 4767 | self.api_provider, |
| 4768 | self.catalog_provider_id(), |
| 4769 | self.catalog_base_url(), |
| 4770 | &body, |
| 4771 | if self.api_provider == ProviderKind::OpencodeGo { |
| 4772 | &self.catalog_error_secret_values |
| 4773 | } else { |
| 4774 | &self.model_bound_secret_values |
| 4775 | }, |
| 4776 | )?; |
| 4777 | if tokio::time::Instant::now() >= deadline { |
| 4778 | return Err(CatalogRefreshError::Network); |
| 4779 | } |
| 4780 | Ok(delta) |
| 4781 | } |
| 4782 | |
| 4783 | /// Refresh `cache` for this client's provider + base URL, recording either a |
| 4784 | /// success or a typed failure (#3385). Returns the resulting status so the UI |
| 4785 | /// can surface a visible "fresh / failed(reason)" chip without inspecting the |
| 4786 | /// cache internals. A failed refresh preserves any previously cached rows. |
| 4787 | #[cfg(any(test, feature = "test-support"))] |
| 4788 | pub async fn refresh_catalog_cache( |
| 4789 | &self, |
| 4790 | cache: &mut ProviderCatalogCache, |
| 4791 | ttl_secs: u64, |
| 4792 | ) -> CatalogStatus { |
| 4793 | match self.fetch_catalog_delta().await { |
| 4794 | Ok(delta) => { |
| 4795 | let provider = delta.provider.clone(); |
| 4796 | let fingerprint = delta.base_url_fingerprint.clone(); |
| 4797 | cache.record_success(delta, ttl_secs); |
| 4798 | publish_provider_lake_scope(cache, &provider, &fingerprint); |
| 4799 | CatalogStatus::Fresh |
| 4800 | } |
| 4801 | Err(reason) => { |
| 4802 | let provider = self.catalog_provider_id(); |
| 4803 | let fingerprint = base_url_fingerprint(&self.base_url); |
| 4804 | cache.record_failure(&provider, &fingerprint, reason); |
| 4805 | publish_provider_lake_scope(cache, &provider, &fingerprint); |
| 4806 | CatalogStatus::Failed { reason } |
| 4807 | } |
| 4808 | } |
| 4809 | } |
| 4810 | |
| 4811 | /// Best-effort background refresh of the active provider's own `/v1/models` |
| 4812 | /// catalog, replacing that provider's exact lake partition (#3385). |
| 4813 | /// |
| 4814 | /// Unlike `models_dev_live::spawn_background_refresh` (which fetches the |
| 4815 | /// cross-provider Models.dev catalog), this calls the provider's own |
| 4816 | /// `/v1/models` endpoint and merges the results into the existing live |
| 4817 | /// snapshot via `provider_catalog_live`, preserving other providers while |
| 4818 | /// allowing this provider's successful roster to retire removed ids. |
| 4819 | /// |
| 4820 | /// Activated for model-list authorities that are not satisfied by the |
| 4821 | /// cross-provider Models.dev snapshot: OpenRouter, OrcaRouter, named live gateways, |
| 4822 | /// and Baseten's account-scoped endpoint (no static snapshot can serve a |
| 4823 | /// per-credential roster). Custom OpenAI-compatible hosts are included |
| 4824 | /// too: a private relay is not in the Models.dev snapshot, so without a |
| 4825 | /// probe its `/model` picker stays empty even though the chat route |
| 4826 | /// already talks to the same endpoint (#6289 widened). |
| 4827 | /// The refresh is non-fatal: on failure, persisted prior rows and static |
| 4828 | /// seeds remain available with a typed failed receipt. |
| 4829 | pub fn spawn_active_provider_catalog_refresh(config: &Config) { |
| 4830 | // Unit tests use explicit fixture refreshes; never probe a developer's provider. |
| 4831 | #[cfg(any( |
| 4832 | test, |
| 4833 | feature = "test-support", |
| 4834 | all(feature = "test-thread-scoped-state", debug_assertions) |
| 4835 | ))] |
| 4836 | let _ = config; |
| 4837 | #[cfg(not(any( |
| 4838 | test, |
| 4839 | feature = "test-support", |
| 4840 | all(feature = "test-thread-scoped-state", debug_assertions) |
| 4841 | )))] |
| 4842 | { |
| 4843 | let Ok(identity) = config.active_provider_identity() else { |
| 4844 | return; |
| 4845 | }; |
| 4846 | let provider = identity.provider; |
| 4847 | // Custom hosts include Baseten (its `/models` dialect is detected |
| 4848 | // at fetch time) and every other custom host. A private route is |
| 4849 | // the only place its roster exists, and a failed probe stays |
| 4850 | // non-fatal. |
| 4851 | if !crate::provider_catalog_live::provider_owns_live_catalog( |
| 4852 | provider, |
| 4853 | &config.active_route_base_url(), |
| 4854 | ) { |
| 4855 | return; |
| 4856 | } |
| 4857 | |
| 4858 | let config = config.clone(); |
| 4859 | tokio::spawn(async move { |
| 4860 | let _ = crate::provider_lake::update_provider_catalog(&config, &identity).await; |
| 4861 | }); |
| 4862 | } |
| 4863 | } |
| 4864 | |
| 4865 | /// Best-effort refresh of every configured route that owns its own |
| 4866 | /// `/v1/models` roster, so opening `/model` finds each relay already probed |
| 4867 | /// instead of a route still waiting for a provider switch. |
| 4868 | /// |
| 4869 | /// [`Self::spawn_active_provider_catalog_refresh`] keeps its own faster path |
| 4870 | /// for the active route (it also publishes that route's persisted scope |
| 4871 | /// before the probe). This is the wider sweep behind it, for the relays a |
| 4872 | /// session is *not* currently on — the picker lists every configured route, |
| 4873 | /// so every one of them has to be able to answer, not just the active one. |
| 4874 | /// |
| 4875 | /// Each route is probed through the same `update_provider_catalog` the |
| 4876 | /// explicit `models --update` command uses, so the TTL, the typed receipt, |
| 4877 | /// the credential-change guard and the superseded-refresh ticket are shared |
| 4878 | /// rather than reimplemented. Failures stay non-fatal: a route that cannot |
| 4879 | /// answer keeps its persisted and configured rows. |
| 4880 | pub fn spawn_configured_provider_catalog_refresh(config: &Config) { |
| 4881 | #[cfg(any( |
| 4882 | test, |
| 4883 | feature = "test-support", |
| 4884 | all(feature = "test-thread-scoped-state", debug_assertions) |
| 4885 | ))] |
| 4886 | let _ = config; |
| 4887 | #[cfg(not(any( |
| 4888 | test, |
| 4889 | feature = "test-support", |
| 4890 | all(feature = "test-thread-scoped-state", debug_assertions) |
| 4891 | )))] |
| 4892 | { |
| 4893 | let active = config.active_provider_identity().ok(); |
| 4894 | for identity in crate::provider_lake::configured_providers(config) { |
| 4895 | if active.as_ref() == Some(&identity) { |
| 4896 | continue; |
| 4897 | } |
| 4898 | let base_url = config.base_url_for_route(&identity); |
| 4899 | if !crate::provider_catalog_live::provider_owns_live_catalog( |
| 4900 | identity.provider, |
| 4901 | &base_url, |
| 4902 | ) { |
| 4903 | continue; |
| 4904 | } |
| 4905 | let route_config = config.clone(); |
| 4906 | tokio::spawn(async move { |
| 4907 | let _ = crate::provider_lake::update_provider_catalog(&route_config, &identity) |
| 4908 | .await; |
| 4909 | }); |
| 4910 | } |
| 4911 | } |
| 4912 | } |
| 4913 | |
| 4914 | pub async fn synthesize_speech( |
| 4915 | &self, |
| 4916 | request: SpeechSynthesisRequest, |
| 4917 | ) -> Result<SpeechSynthesisResponse> { |
| 4918 | let _inference = self.acquire_remote_control_inference_permit().await; |
| 4919 | let _permit = self.acquire_provider_request_permit().await; |
| 4920 | if self.uses_minimax_speech() { |
| 4921 | return self.synthesize_minimax_speech(request).await; |
| 4922 | } |
| 4923 | if matches!( |
| 4924 | self.api_provider, |
| 4925 | codewhale_config::ProviderKind::Deepseek |
| 4926 | | codewhale_config::ProviderKind::DeepseekAnthropic |
| 4927 | ) { |
| 4928 | return crate::deepseek_media::synthesize_deepseek_with_client( |
| 4929 | &self.http_client, |
| 4930 | &self.base_url, |
| 4931 | &self.api_key, |
| 4932 | request, |
| 4933 | ) |
| 4934 | .await; |
| 4935 | } |
| 4936 | if self.api_provider != codewhale_config::ProviderKind::XiaomiMimo { |
| 4937 | anyhow::bail!( |
| 4938 | "speech synthesis requires provider 'xiaomi-mimo', 'deepseek' or 'minimax' on its OpenAI-compatible /v1 route (current: {})", |
| 4939 | self.api_provider.as_str() |
| 4940 | ); |
| 4941 | } |
| 4942 | |
| 4943 | let model = request.model.trim().to_string(); |
| 4944 | if model.is_empty() { |
| 4945 | anyhow::bail!("Speech model cannot be empty"); |
| 4946 | } |
| 4947 | let text = request.text.trim().to_string(); |
| 4948 | if text.is_empty() { |
| 4949 | anyhow::bail!("Speech text cannot be empty"); |
| 4950 | } |
| 4951 | |
| 4952 | let audio_format = normalize_audio_format(&request.audio_format); |
| 4953 | let model = self.wire_model_for_route(&model); |
| 4954 | let model_lower = model.to_ascii_lowercase(); |
| 4955 | let instruction = request |
| 4956 | .instruction |
| 4957 | .as_deref() |
| 4958 | .map(str::trim) |
| 4959 | .filter(|value| !value.is_empty()); |
| 4960 | let voice = request |
| 4961 | .voice |
| 4962 | .as_deref() |
| 4963 | .map(str::trim) |
| 4964 | .filter(|value| !value.is_empty()) |
| 4965 | .map(str::to_string); |
| 4966 | |
| 4967 | if model_lower.contains("voicedesign") && instruction.is_none() { |
| 4968 | anyhow::bail!( |
| 4969 | "Model '{model}' requires a voice design prompt. Pass --voice-prompt or --instruction." |
| 4970 | ); |
| 4971 | } |
| 4972 | if model_lower.contains("voiceclone") && voice.is_none() { |
| 4973 | anyhow::bail!( |
| 4974 | "Model '{model}' requires cloned voice data. Pass --clone-voice <mp3|wav> or --voice <data-uri>." |
| 4975 | ); |
| 4976 | } |
| 4977 | |
| 4978 | let mut audio = json!({ |
| 4979 | "format": audio_format.clone(), |
| 4980 | }); |
| 4981 | if let Some(voice) = voice.as_deref() { |
| 4982 | audio["voice"] = json!(voice); |
| 4983 | } |
| 4984 | |
| 4985 | let body = build_speech_synthesis_body(&model, &text, instruction, audio); |
| 4986 | |
| 4987 | let url = api_url(&self.base_url, "chat/completions"); |
| 4988 | let response = self.send_json_with_retry(&url, &body).await?; |
| 4989 | let status = response.status(); |
| 4990 | if !status.is_success() { |
| 4991 | let raw_error_text = bounded_error_text(response, ERROR_BODY_MAX_BYTES).await; |
| 4992 | let error_text = sanitize_http_error_body( |
| 4993 | Some(self.api_provider.provider().display_name()), |
| 4994 | status.as_u16(), |
| 4995 | &raw_error_text, |
| 4996 | ); |
| 4997 | anyhow::bail!("Speech synthesis failed: HTTP {status}: {error_text}"); |
| 4998 | } |
| 4999 | |
| 5000 | let response_text = response |
| 5001 | .text() |
| 5002 | .await |
| 5003 | .context("Failed to read speech synthesis response body")?; |
| 5004 | let payload: Value = serde_json::from_str(&response_text) |
| 5005 | .context("Failed to parse speech synthesis response JSON")?; |
| 5006 | let (audio_bytes, transcript) = parse_speech_audio_response(&payload)?; |
| 5007 | |
| 5008 | Ok(SpeechSynthesisResponse { |
| 5009 | model, |
| 5010 | audio_format, |
| 5011 | audio_bytes, |
| 5012 | transcript, |
| 5013 | voice, |
| 5014 | }) |
| 5015 | } |
| 5016 | |
| 5017 | async fn wait_for_rate_limit(&self) { |
| 5018 | let maybe_delay = { |
| 5019 | let mut limiter = self.rate_limiter.lock().await; |
| 5020 | limiter.delay_until_available(1.0) |
| 5021 | }; |
| 5022 | if let Some(delay) = maybe_delay { |
| 5023 | tokio::time::sleep(delay).await; |
| 5024 | } |
| 5025 | } |
| 5026 | |
| 5027 | async fn mark_request_success(&self) { |
| 5028 | let mut health = self.connection_health.lock().await; |
| 5029 | if apply_request_success(&mut health, Instant::now()) { |
| 5030 | logging::info("Connection recovered"); |
| 5031 | } |
| 5032 | } |
| 5033 | |
| 5034 | async fn mark_request_failure(&self, reason: &str) { |
| 5035 | let mut health = self.connection_health.lock().await; |
| 5036 | apply_request_failure(&mut health, Instant::now()); |
| 5037 | logging::warn(format!( |
| 5038 | "Connection degraded (failures={}): {}", |
| 5039 | health.consecutive_failures, reason |
| 5040 | )); |
| 5041 | } |
| 5042 | |
| 5043 | async fn spawn_recovery_probe(&self) { |
| 5044 | if self.claim_recovery_probe().await { |
| 5045 | let client = self.clone(); |
| 5046 | tokio::spawn(async move { client.run_recovery_probe().await }); |
| 5047 | } |
| 5048 | } |
| 5049 | |
| 5050 | async fn claim_recovery_probe(&self) -> bool { |
| 5051 | if model_listing_unavailable(self.api_provider, &self.base_url) { |
| 5052 | return false; |
| 5053 | } |
| 5054 | let should_probe = { |
| 5055 | let mut health = self.connection_health.lock().await; |
| 5056 | mark_recovery_probe_if_due(&mut health, Instant::now()) |
| 5057 | }; |
| 5058 | if !should_probe { |
| 5059 | return false; |
| 5060 | } |
| 5061 | if !provider_api_key_verification_is_observed_for_route(self.api_provider, &self.base_url) { |
| 5062 | self.mark_request_success().await; |
| 5063 | logging::info("Skipping /models recovery probe for provider without a models endpoint"); |
| 5064 | return false; |
| 5065 | } |
| 5066 | true |
| 5067 | } |
| 5068 | |
| 5069 | async fn run_recovery_probe(&self) { |
| 5070 | let health_url = model_listing_url(self.api_provider, self.catalog_base_url()); |
| 5071 | let request = self |
| 5072 | .models_http_client |
| 5073 | .get(health_url) |
| 5074 | .timeout(NON_STREAMING_HTTP_TIMEOUT); |
| 5075 | let request = match self.authorize_plugin_request(request).await { |
| 5076 | Ok(request) => request, |
| 5077 | Err(_) => { |
| 5078 | self.mark_request_failure("probe authorization failed") |
| 5079 | .await; |
| 5080 | return; |
| 5081 | } |
| 5082 | }; |
| 5083 | let probe = request.send().await; |
| 5084 | match probe { |
| 5085 | Ok(resp) if resp.status().is_success() => { |
| 5086 | // Consume the response body so the connection can be returned to the pool. |
| 5087 | let _ = bounded_error_text(resp, ERROR_BODY_MAX_BYTES).await; |
| 5088 | self.mark_request_success().await; |
| 5089 | logging::info("Recovery probe succeeded"); |
| 5090 | } |
| 5091 | Ok(resp) => { |
| 5092 | self.mark_request_failure(&format!("probe status={}", resp.status())) |
| 5093 | .await; |
| 5094 | } |
| 5095 | Err(err) => { |
| 5096 | self.mark_request_failure(&format!("probe error={}", err.without_url())) |
| 5097 | .await; |
| 5098 | } |
| 5099 | } |
| 5100 | } |
| 5101 | |
| 5102 | /// Apply `disclosure` to one provider error body. |
| 5103 | /// |
| 5104 | /// Redaction runs on the raw bytes, *before* `sanitize_http_error_body` |
| 5105 | /// truncates them, so a secret can never be split across the truncation |
| 5106 | /// boundary and survive as a fragment. The result is then checked against |
| 5107 | /// every value this client knows is secret; if one is still there the |
| 5108 | /// whole body is dropped, which is exactly the behaviour this path had |
| 5109 | /// before #6173. The fallback is the old contract, not a weaker one. |
| 5110 | /// |
| 5111 | /// Known limitation: this removes what the *client* knows is secret. A |
| 5112 | /// credential the user configured outside Codewhale — in a proxy, say — |
| 5113 | /// is not in that set and would pass through, the same limit |
| 5114 | /// `redact_model_bound_text` has. |
| 5115 | fn disclosed_http_error_body( |
| 5116 | &self, |
| 5117 | disclosure: &ErrorBodyDisclosure, |
| 5118 | status: u16, |
| 5119 | raw: &str, |
| 5120 | ) -> String { |
| 5121 | // Rotated opaque bearer values are not part of this client's frozen |
| 5122 | // redaction list. Do not disclose a dynamic OAuth endpoint's body. |
| 5123 | if self.plugin_provider.is_some() { |
| 5124 | return "plugin provider request failed".into(); |
| 5125 | } |
| 5126 | let claude_org_redacted; |
| 5127 | let raw = match &self.claude_org { |
| 5128 | Some(claude_org) => { |
| 5129 | claude_org_redacted = claude_org.redact(raw); |
| 5130 | claude_org_redacted.as_str() |
| 5131 | } |
| 5132 | None => raw, |
| 5133 | }; |
| 5134 | let provider = Some(self.api_provider.provider().display_name()); |
| 5135 | let ErrorBodyDisclosure::Guarded { request_secrets } = disclosure else { |
| 5136 | return sanitize_http_error_body(provider, status, raw); |
| 5137 | }; |
| 5138 | let mut redacted = raw.to_string(); |
| 5139 | for secret in self |
| 5140 | .catalog_error_secret_values |
| 5141 | .iter() |
| 5142 | .chain(request_secrets.iter()) |
| 5143 | { |
| 5144 | redacted = redacted.replace(secret.as_str(), codewhale_config::persistence::REDACTED); |
| 5145 | } |
| 5146 | let message = sanitize_http_error_body(provider, status, &redacted); |
| 5147 | let leaked = self |
| 5148 | .catalog_error_secret_values |
| 5149 | .iter() |
| 5150 | .chain(request_secrets.iter()) |
| 5151 | .any(|secret| message.contains(secret.as_str())); |
| 5152 | if leaked { String::new() } else { message } |
| 5153 | } |
| 5154 | |
| 5155 | pub(super) async fn send_with_retry<F>(&self, build: F) -> Result<reqwest::Response> |
| 5156 | where |
| 5157 | F: FnMut() -> reqwest::RequestBuilder, |
| 5158 | { |
| 5159 | self.send_with_retry_error_body(build, &ErrorBodyDisclosure::Full) |
| 5160 | .await |
| 5161 | } |
| 5162 | |
| 5163 | /// Model-list errors can echo opaque cursors or credentials. Keep status |
| 5164 | /// and Retry-After classification either way; `disclosure` decides how |
| 5165 | /// much of the body reaches retry logs, state updates and the user. |
| 5166 | async fn send_with_retry_error_body<F>( |
| 5167 | &self, |
| 5168 | build: F, |
| 5169 | disclosure: &ErrorBodyDisclosure, |
| 5170 | ) -> Result<reqwest::Response> |
| 5171 | where |
| 5172 | F: FnMut() -> reqwest::RequestBuilder, |
| 5173 | { |
| 5174 | self.send_with_retry_total_error_body( |
| 5175 | non_streaming_request_envelope(), |
| 5176 | build, |
| 5177 | disclosure, |
| 5178 | crate::llm_client::RetryOperation::Inference, |
| 5179 | ) |
| 5180 | .await |
| 5181 | } |
| 5182 | |
| 5183 | /// [`Self::send_with_retry_error_body`] with a caller-pinned per-attempt |
| 5184 | /// total (connect through body end). `list_models` pins its own 30s: the |
| 5185 | /// plain variant would otherwise stretch that pinned budget out to the |
| 5186 | /// shared envelope, because `.timeout()` on the builder is a pure |
| 5187 | /// overwrite. |
| 5188 | async fn send_with_retry_total_error_body<F>( |
| 5189 | &self, |
| 5190 | total: Duration, |
| 5191 | mut build: F, |
| 5192 | disclosure: &ErrorBodyDisclosure, |
| 5193 | operation: crate::llm_client::RetryOperation, |
| 5194 | ) -> Result<reqwest::Response> |
| 5195 | where |
| 5196 | F: FnMut() -> reqwest::RequestBuilder, |
| 5197 | { |
| 5198 | self.send_retry_loop( |
| 5199 | || { |
| 5200 | let request = build(); |
| 5201 | let request = if self.isolated_request_state { |
| 5202 | request |
| 5203 | } else { |
| 5204 | request.timeout(total) |
| 5205 | }; |
| 5206 | async move { self.dispatch_attempt(request, operation).await } |
| 5207 | }, |
| 5208 | Some(total), |
| 5209 | disclosure, |
| 5210 | operation, |
| 5211 | ) |
| 5212 | .await |
| 5213 | } |
| 5214 | |
| 5215 | /// The streaming-open twin of [`Self::send_with_retry`]: provider backoff |
| 5216 | /// stays outside each physical response-header wait. No reqwest total |
| 5217 | /// timeout may ride on the returned body and truncate a live stream. |
| 5218 | pub(super) async fn send_stream_open_with_retry<F>(&self, build: F) -> Result<reqwest::Response> |
| 5219 | where |
| 5220 | F: Fn(stream_entry::StreamHttpPolicy) -> reqwest::RequestBuilder, |
| 5221 | { |
| 5222 | let open_req = self.stream_open_request(); |
| 5223 | self.send_retry_loop( |
| 5224 | || async { |
| 5225 | stream_entry::open_sse_response(&open_req, |policy| { |
| 5226 | let request = build(policy); |
| 5227 | async move { |
| 5228 | self.dispatch_attempt(request, crate::llm_client::RetryOperation::Inference) |
| 5229 | .await |
| 5230 | .map_err(anyhow::Error::new) |
| 5231 | } |
| 5232 | }) |
| 5233 | .await |
| 5234 | .map_err(|error| { |
| 5235 | error |
| 5236 | .downcast::<LlmError>() |
| 5237 | .unwrap_or_else(|error| LlmError::Other(error.to_string())) |
| 5238 | }) |
| 5239 | }, |
| 5240 | None, |
| 5241 | &ErrorBodyDisclosure::Full, |
| 5242 | crate::llm_client::RetryOperation::Inference, |
| 5243 | ) |
| 5244 | .await |
| 5245 | } |
| 5246 | |
| 5247 | #[allow(clippy::result_large_err)] |
| 5248 | async fn dispatch_attempt( |
| 5249 | &self, |
| 5250 | request: reqwest::RequestBuilder, |
| 5251 | operation: crate::llm_client::RetryOperation, |
| 5252 | ) -> std::result::Result<reqwest::Response, LlmError> { |
| 5253 | if self.api_provider == ProviderKind::OpencodeGo |
| 5254 | && self.go_route.is_none() |
| 5255 | && matches!(operation, crate::llm_client::RetryOperation::Inference) |
| 5256 | && (opencode_catalog::official_listing(self.catalog_base_url()) |
| 5257 | || crate::provider_catalog_live::go_has_typed_catalog( |
| 5258 | self.admitted_identity.key.as_str(), |
| 5259 | self.catalog_base_url(), |
| 5260 | )) |
| 5261 | { |
| 5262 | return Err(LlmError::Other( |
| 5263 | "Go inference requires a current account-specific route. Refresh models and reselect before sending.".into(), |
| 5264 | )); |
| 5265 | } |
| 5266 | if matches!(operation, crate::llm_client::RetryOperation::Inference) |
| 5267 | && let Some((connection, endpoint_key)) = &self.go_route |
| 5268 | && !crate::provider_catalog_live::go_route_is_current( |
| 5269 | connection, |
| 5270 | &self.default_model, |
| 5271 | endpoint_key, |
| 5272 | &self.base_url, |
| 5273 | ) |
| 5274 | { |
| 5275 | return Err(LlmError::Other( |
| 5276 | "Go model inventory changed. Refresh and reselect the route.".into(), |
| 5277 | )); |
| 5278 | } |
| 5279 | let request = if let Some(fallback) = &self.automatic_opencode_session |
| 5280 | && matches!(operation, crate::llm_client::RetryOperation::Inference) |
| 5281 | { |
| 5282 | let session = OPENCODE_CONVERSATION |
| 5283 | .try_with(Clone::clone) |
| 5284 | .unwrap_or_else(|_| fallback.clone()); |
| 5285 | request.header("x-opencode-session", session) |
| 5286 | } else { |
| 5287 | request |
| 5288 | }; |
| 5289 | let replay = self.claude_org.as_ref().and_then(|_| request.try_clone()); |
| 5290 | let (response, sent_token) = self.dispatch_authorized(request, operation).await?; |
| 5291 | if response.status() == reqwest::StatusCode::UNAUTHORIZED |
| 5292 | && let (Some(claude_org), Some(replay), Some(sent_token)) = |
| 5293 | (self.claude_org.as_ref(), replay, sent_token) |
| 5294 | && claude_org.refetch_after_rejection(&sent_token).await? |
| 5295 | { |
| 5296 | drop(response); |
| 5297 | return self |
| 5298 | .dispatch_authorized(replay, operation) |
| 5299 | .await |
| 5300 | .map(|(response, _)| response); |
| 5301 | } |
| 5302 | Ok(response) |
| 5303 | } |
| 5304 | |
| 5305 | #[allow(clippy::result_large_err)] |
| 5306 | async fn dispatch_authorized( |
| 5307 | &self, |
| 5308 | request: reqwest::RequestBuilder, |
| 5309 | operation: crate::llm_client::RetryOperation, |
| 5310 | ) -> std::result::Result<(reqwest::Response, Option<String>), LlmError> { |
| 5311 | let (request, sent_token) = match &self.claude_org { |
| 5312 | Some(_) if self.session_provider_keys_only => { |
| 5313 | return Err(LlmError::Other( |
| 5314 | "Claude organization billing is unavailable under session-only provider key policy" |
| 5315 | .into(), |
| 5316 | )); |
| 5317 | } |
| 5318 | Some(claude_org) => { |
| 5319 | let (request, token) = claude_org |
| 5320 | .authorize(request, self.claude_org_test_transport_base()) |
| 5321 | .await?; |
| 5322 | (request, Some(token)) |
| 5323 | } |
| 5324 | None => ( |
| 5325 | self.authorize_plugin_request(request) |
| 5326 | .await |
| 5327 | .map_err(|error| { |
| 5328 | error |
| 5329 | .downcast::<LlmError>() |
| 5330 | .unwrap_or_else(|error| LlmError::Other(format!("{error:#}"))) |
| 5331 | })?, |
| 5332 | None, |
| 5333 | ), |
| 5334 | }; |
| 5335 | let (client, request) = request.build_split(); |
| 5336 | let request = request.map_err(|error| LlmError::Other(error.without_url().to_string()))?; |
| 5337 | if operation == crate::llm_client::RetryOperation::ReadOnly |
| 5338 | && request.method() != reqwest::Method::GET |
| 5339 | && request.method() != reqwest::Method::HEAD |
| 5340 | { |
| 5341 | return Err(LlmError::Other( |
| 5342 | "Read-only retry requires GET or HEAD".to_string(), |
| 5343 | )); |
| 5344 | } |
| 5345 | let pending = crate::llm_client::begin_outbound_transmission(request.method()); |
| 5346 | // Measure the attempt: from_reqwest cannot know the spent |
| 5347 | // budget (reqwest does not expose it). |
| 5348 | let started = std::time::Instant::now(); |
| 5349 | let result = client |
| 5350 | .execute(request) |
| 5351 | .await |
| 5352 | .map_err(|error| LlmError::from_reqwest_measured(&error.without_url(), started)); |
| 5353 | crate::llm_client::settle_outbound_transmission(pending, &result); |
| 5354 | result.map(|response| (response, sent_token)) |
| 5355 | } |
| 5356 | |
| 5357 | async fn send_retry_loop<F, Fut>( |
| 5358 | &self, |
| 5359 | mut attempt: F, |
| 5360 | attempt_total: Option<Duration>, |
| 5361 | disclosure: &ErrorBodyDisclosure, |
| 5362 | operation: crate::llm_client::RetryOperation, |
| 5363 | ) -> Result<reqwest::Response> |
| 5364 | where |
| 5365 | F: FnMut() -> Fut, |
| 5366 | Fut: std::future::Future<Output = std::result::Result<reqwest::Response, LlmError>>, |
| 5367 | { |
| 5368 | if self.isolated_request_state { |
| 5369 | return self |
| 5370 | .send_with_isolated_retry(attempt, disclosure, operation) |
| 5371 | .await; |
| 5372 | } |
| 5373 | let mut retry_cfg: LlmRetryConfig = self.retry.clone().into(); |
| 5374 | retry_cfg.operation = operation; |
| 5375 | let pause_scope = self.rate_limit_scope(); |
| 5376 | let callback_scope = pause_scope.clone(); |
| 5377 | // Non-streaming calls retain their whole-retry envelope. Streaming |
| 5378 | // attempts own their header wait and never carry a total body timeout. |
| 5379 | let rate_policy = &retry_cfg.rate_limit; |
| 5380 | let retry_future = crate::llm_client::rate_limit::with_recovery_clock(with_retry( |
| 5381 | &retry_cfg, |
| 5382 | || { |
| 5383 | let response = attempt(); |
| 5384 | let pause_scope = pause_scope.as_str(); |
| 5385 | async move { |
| 5386 | // Sleep in bounded slices rather than the full remaining |
| 5387 | // window: the pause is shared by every request to this |
| 5388 | // route, so a concurrent `clear_rate_limit()` (or a |
| 5389 | // shortened deadline) must release requests that are |
| 5390 | // already waiting instead of stranding them for the whole |
| 5391 | // original window. |
| 5392 | let admission_started = tokio::time::Instant::now(); |
| 5393 | loop { |
| 5394 | while let Some(delay) = |
| 5395 | codewhale_runtime::retry_status::rate_limit_remaining(pause_scope) |
| 5396 | { |
| 5397 | let remaining = |
| 5398 | crate::llm_client::rate_limit::remaining_recovery_budget( |
| 5399 | rate_policy, |
| 5400 | ) |
| 5401 | .min( |
| 5402 | Duration::from_secs(rate_policy.recovery_budget_secs) |
| 5403 | .saturating_sub(admission_started.elapsed()), |
| 5404 | ); |
| 5405 | if delay >= remaining { |
| 5406 | return Err(LlmError::QuotaWindow { |
| 5407 | message: |
| 5408 | "Shared provider minimum exceeds the HTTP recovery budget" |
| 5409 | .into(), |
| 5410 | retry_after: Some(delay), |
| 5411 | transmission: |
| 5412 | crate::llm_client::RequestTransmission::NotDispatched, |
| 5413 | }); |
| 5414 | } |
| 5415 | crate::llm_client::rate_limit::wait( |
| 5416 | delay.min(RATE_LIMIT_PAUSE_RECHECK_INTERVAL), |
| 5417 | ) |
| 5418 | .await; |
| 5419 | } |
| 5420 | self.wait_for_rate_limit().await; |
| 5421 | if codewhale_runtime::retry_status::rate_limit_remaining(pause_scope) |
| 5422 | .is_some() |
| 5423 | { |
| 5424 | continue; |
| 5425 | } |
| 5426 | if crate::llm_client::rate_limit::remaining_recovery_budget(rate_policy) |
| 5427 | .is_zero() |
| 5428 | { |
| 5429 | return Err(LlmError::QuotaWindow { |
| 5430 | message: "HTTP recovery budget exhausted in admission".into(), |
| 5431 | retry_after: None, |
| 5432 | transmission: crate::llm_client::RequestTransmission::NotDispatched, |
| 5433 | }); |
| 5434 | } |
| 5435 | break; |
| 5436 | } |
| 5437 | let response = response.await?; |
| 5438 | let response = |
| 5439 | crate::llm_client::rate_limit::inspect_json_envelope_with_disclosure( |
| 5440 | self.api_provider.as_str(), |
| 5441 | response, |
| 5442 | Some(( |
| 5443 | stream_entry::first_byte_timeout(self.stream_idle_timeout), |
| 5444 | self.stream_idle_timeout, |
| 5445 | )), |
| 5446 | |status, raw| self.disclosed_http_error_body(disclosure, status, raw), |
| 5447 | ) |
| 5448 | .await |
| 5449 | .inspect_err(crate::llm_client::settle_outbound_http_error)?; |
| 5450 | let status = response.status(); |
| 5451 | if status.is_success() { |
| 5452 | return Ok(response); |
| 5453 | } |
| 5454 | let header_retry_after = extract_retry_after(response.headers()); |
| 5455 | let retry_refused = crate::llm_client::server_refuses_retry( |
| 5456 | status.as_u16(), |
| 5457 | response.headers(), |
| 5458 | ); |
| 5459 | let raw = bounded_error_text(response, ERROR_BODY_MAX_BYTES).await; |
| 5460 | let body_retry_after = retry_delay_from_error_body(&raw) |
| 5461 | .max(crate::llm_client::rate_limit::body_delay(&raw)); |
| 5462 | let body = self.disclosed_http_error_body(disclosure, status.as_u16(), &raw); |
| 5463 | let provider_error = crate::llm_client::rate_limit::provider_error( |
| 5464 | self.api_provider.as_str(), |
| 5465 | status.as_u16(), |
| 5466 | &raw, |
| 5467 | &body, |
| 5468 | header_retry_after, |
| 5469 | ); |
| 5470 | let route_error = self.http_error_with_route_context( |
| 5471 | status.as_u16(), |
| 5472 | &body, |
| 5473 | header_retry_after, |
| 5474 | body_retry_after, |
| 5475 | ); |
| 5476 | let billing_stop = self |
| 5477 | .claude_org |
| 5478 | .as_ref() |
| 5479 | .and_then(|_| claude_org::http_error(status.as_u16(), &raw)); |
| 5480 | let error = match (billing_stop, provider_error, route_error) { |
| 5481 | (Some(stop), _, _) => stop, |
| 5482 | ( |
| 5483 | None, |
| 5484 | Some(LlmError::QuotaExhausted(_)), |
| 5485 | route @ LlmError::QuotaExhausted(_), |
| 5486 | ) => route, |
| 5487 | (None, Some(native), _) => native, |
| 5488 | (None, None, route) => route, |
| 5489 | }; |
| 5490 | let error = if retry_refused { |
| 5491 | error.into_non_retryable() |
| 5492 | } else { |
| 5493 | error |
| 5494 | }; |
| 5495 | crate::llm_client::settle_outbound_http_error(&error); |
| 5496 | Err(error) |
| 5497 | } |
| 5498 | }, |
| 5499 | Some(Box::new(move |err, attempt, delay| { |
| 5500 | let (reason_label, human_reason) = retry_reason_label_and_human(err); |
| 5501 | logging::warn(format!( |
| 5502 | "HTTP retry reason={} attempt={} delay={:.2}s", |
| 5503 | reason_label, |
| 5504 | attempt + 1, |
| 5505 | delay.as_secs_f64(), |
| 5506 | )); |
| 5507 | if matches!( |
| 5508 | err, |
| 5509 | LlmError::RateLimited { .. } | LlmError::QuotaWindow { .. } |
| 5510 | ) { |
| 5511 | codewhale_runtime::retry_status::note_rate_limit(&callback_scope, delay); |
| 5512 | } |
| 5513 | codewhale_runtime::retry_status::start(attempt + 1, delay, human_reason); |
| 5514 | })), |
| 5515 | )); |
| 5516 | let request_result = if let Some(total) = attempt_total { |
| 5517 | // The loop envelope must dominate the per-attempt total it |
| 5518 | // wraps: a caller-pinned budget (list_models' 30s) may exceed |
| 5519 | // the shared envelope, and the envelope must never strangle |
| 5520 | // its own attempts. |
| 5521 | let loop_envelope = total.max(non_streaming_request_envelope()); |
| 5522 | match crate::llm_client::rate_limit::active_timeout_total(loop_envelope, retry_future) |
| 5523 | .await |
| 5524 | { |
| 5525 | Ok(result) => result, |
| 5526 | Err(_elapsed) => { |
| 5527 | let last = LlmError::Timeout(loop_envelope); |
| 5528 | logging::warn(format!( |
| 5529 | "non-streaming request envelope exceeded ({loop_envelope:?}); retry loop aborted" |
| 5530 | )); |
| 5531 | codewhale_runtime::retry_status::failed(last.to_string()); |
| 5532 | self.mark_request_failure("non-streaming request envelope exceeded") |
| 5533 | .await; |
| 5534 | self.spawn_recovery_probe().await; |
| 5535 | return Err(anyhow::Error::new(last)); |
| 5536 | } |
| 5537 | } |
| 5538 | } else { |
| 5539 | retry_future.await |
| 5540 | }; |
| 5541 | |
| 5542 | match request_result { |
| 5543 | Ok(response) => { |
| 5544 | codewhale_runtime::retry_status::succeeded(); |
| 5545 | self.mark_request_success().await; |
| 5546 | Ok(response) |
| 5547 | } |
| 5548 | Err(err) => { |
| 5549 | if let LlmError::RateLimited { retry_after, .. } |
| 5550 | | LlmError::QuotaWindow { retry_after, .. } = &err.last_error |
| 5551 | { |
| 5552 | codewhale_runtime::retry_status::note_rate_limit( |
| 5553 | &pause_scope, |
| 5554 | retry_after |
| 5555 | .unwrap_or_else(|| retry_cfg.delay_for_attempt(retry_cfg.max_retries)), |
| 5556 | ); |
| 5557 | } |
| 5558 | let last = err.last_error.to_string(); |
| 5559 | if err.attempts > 1 { |
| 5560 | codewhale_runtime::retry_status::failed(last.clone()); |
| 5561 | } else { |
| 5562 | codewhale_runtime::retry_status::clear(); |
| 5563 | } |
| 5564 | self.mark_request_failure(&last).await; |
| 5565 | if !matches!( |
| 5566 | err.last_error, |
| 5567 | LlmError::RateLimited { .. } | LlmError::QuotaWindow { .. } |
| 5568 | ) { |
| 5569 | self.spawn_recovery_probe().await; |
| 5570 | } |
| 5571 | // Keep the structured `LlmError` downcastable so failure |
| 5572 | // surfaces can classify auth/rate-limit/invalid-request |
| 5573 | // instead of reporting an opaque string (#3884). |
| 5574 | Err(anyhow::Error::new(err.last_error)) |
| 5575 | } |
| 5576 | } |
| 5577 | } |
| 5578 | |
| 5579 | /// Key for this route's shared `Retry-After` pause: the configured route |
| 5580 | /// identity plus the host it reaches. A 429 from one provider pauses only |
| 5581 | /// requests that would hit the same limit, never another provider, a |
| 5582 | /// local runtime, or a sub-agent on a different route. |
| 5583 | pub fn rate_limit_scope(&self) -> String { |
| 5584 | let route = self.admitted_identity.key.as_str(); |
| 5585 | let host = crate::llm_client::base_url_authority(&self.base_url) |
| 5586 | .unwrap_or_else(|| redact_url_for_display(&self.base_url)); |
| 5587 | format!("{route}@{host}") |
| 5588 | } |
| 5589 | |
| 5590 | /// The same bounded transport retry policy without process-global retry |
| 5591 | /// banners, provider-wide pause cells, or shared connection-health writes. |
| 5592 | /// Used only by the Auto classifier during read-only request inspection. |
| 5593 | async fn send_with_isolated_retry<F, Fut>( |
| 5594 | &self, |
| 5595 | mut attempt: F, |
| 5596 | disclosure: &ErrorBodyDisclosure, |
| 5597 | operation: crate::llm_client::RetryOperation, |
| 5598 | ) -> Result<reqwest::Response> |
| 5599 | where |
| 5600 | F: FnMut() -> Fut, |
| 5601 | Fut: std::future::Future<Output = std::result::Result<reqwest::Response, LlmError>>, |
| 5602 | { |
| 5603 | let mut retry_cfg: LlmRetryConfig = self.retry.clone().into(); |
| 5604 | retry_cfg.operation = operation; |
| 5605 | let request_result = with_retry( |
| 5606 | &retry_cfg, |
| 5607 | || { |
| 5608 | let response = attempt(); |
| 5609 | async move { |
| 5610 | self.wait_for_rate_limit().await; |
| 5611 | let response = response.await?; |
| 5612 | let response = |
| 5613 | crate::llm_client::rate_limit::inspect_json_envelope_with_disclosure( |
| 5614 | self.api_provider.as_str(), |
| 5615 | response, |
| 5616 | Some(( |
| 5617 | stream_entry::first_byte_timeout(self.stream_idle_timeout), |
| 5618 | self.stream_idle_timeout, |
| 5619 | )), |
| 5620 | |status, raw| self.disclosed_http_error_body(disclosure, status, raw), |
| 5621 | ) |
| 5622 | .await |
| 5623 | .inspect_err(crate::llm_client::settle_outbound_http_error)?; |
| 5624 | let status = response.status(); |
| 5625 | if status.is_success() { |
| 5626 | return Ok(response); |
| 5627 | } |
| 5628 | let header_retry_after = extract_retry_after(response.headers()); |
| 5629 | let retry_refused = crate::llm_client::server_refuses_retry( |
| 5630 | status.as_u16(), |
| 5631 | response.headers(), |
| 5632 | ); |
| 5633 | let raw = bounded_error_text(response, ERROR_BODY_MAX_BYTES).await; |
| 5634 | let body_retry_after = retry_delay_from_error_body(&raw) |
| 5635 | .max(crate::llm_client::rate_limit::body_delay(&raw)); |
| 5636 | let body = self.disclosed_http_error_body(disclosure, status.as_u16(), &raw); |
| 5637 | let provider_error = crate::llm_client::rate_limit::provider_error( |
| 5638 | self.api_provider.as_str(), |
| 5639 | status.as_u16(), |
| 5640 | &raw, |
| 5641 | &body, |
| 5642 | header_retry_after, |
| 5643 | ); |
| 5644 | let route_error = self.http_error_with_route_context( |
| 5645 | status.as_u16(), |
| 5646 | &body, |
| 5647 | header_retry_after, |
| 5648 | body_retry_after, |
| 5649 | ); |
| 5650 | let billing_stop = self |
| 5651 | .claude_org |
| 5652 | .as_ref() |
| 5653 | .and_then(|_| claude_org::http_error(status.as_u16(), &raw)); |
| 5654 | let error = match (billing_stop, provider_error, route_error) { |
| 5655 | (Some(stop), _, _) => stop, |
| 5656 | ( |
| 5657 | None, |
| 5658 | Some(LlmError::QuotaExhausted(_)), |
| 5659 | route @ LlmError::QuotaExhausted(_), |
| 5660 | ) => route, |
| 5661 | (None, Some(native), _) => native, |
| 5662 | (None, None, route) => route, |
| 5663 | }; |
| 5664 | let error = if retry_refused { |
| 5665 | error.into_non_retryable() |
| 5666 | } else { |
| 5667 | error |
| 5668 | }; |
| 5669 | crate::llm_client::settle_outbound_http_error(&error); |
| 5670 | Err(error) |
| 5671 | } |
| 5672 | }, |
| 5673 | Some(Box::new(|err, attempt, delay| { |
| 5674 | let (reason_label, _) = retry_reason_label_and_human(err); |
| 5675 | logging::warn(format!( |
| 5676 | "Isolated HTTP retry reason={} attempt={} delay={:.2}s", |
| 5677 | reason_label, |
| 5678 | attempt + 1, |
| 5679 | delay.as_secs_f64(), |
| 5680 | )); |
| 5681 | })), |
| 5682 | ) |
| 5683 | .await; |
| 5684 | |
| 5685 | request_result.map_err(|err| anyhow::Error::new(err.last_error)) |
| 5686 | } |
| 5687 | |
| 5688 | pub(super) async fn send_json_with_retry( |
| 5689 | &self, |
| 5690 | url: &str, |
| 5691 | body: &serde_json::Value, |
| 5692 | ) -> Result<reqwest::Response> { |
| 5693 | let request_body = |
| 5694 | serde_json::to_vec(body).context("Failed to serialize JSON request body")?; |
| 5695 | self.send_with_retry(|| { |
| 5696 | self.http_client |
| 5697 | .post(url) |
| 5698 | .header(CONTENT_TYPE, "application/json") |
| 5699 | .body(request_body.clone()) |
| 5700 | }) |
| 5701 | .await |
| 5702 | } |
| 5703 | } |
| 5704 | |
| 5705 | /// Record that a request was routed to `provider` and came back with `status`. |
| 5706 | /// |
| 5707 | /// Called at every provider response site, **before** the error is built: an |
| 5708 | /// `LlmError` carries the raw provider body verbatim, so the status class has |
| 5709 | /// to be taken from the response itself. |
| 5710 | /// |
| 5711 | /// The provider is recorded as a `ProviderKind` by value. Every accessor that |
| 5712 | /// looks like the natural seam here — the persistence identity, the stream |
| 5713 | /// meta's `provider_id`, the planned route's effective label — returns the |
| 5714 | /// customer's own `[providers.<name>]` table key when the route is custom. |
| 5715 | /// `ProviderKind::Custom` yields the literal `"custom"` and nothing else, and |
| 5716 | /// no model id is sent for any provider. |
| 5717 | pub fn record_provider_response(provider: codewhale_config::ProviderKind, status: u16) { |
| 5718 | let counters = codewhale_telemetry::session_counters(); |
| 5719 | counters.record_provider(provider); |
| 5720 | if let Some(counter) = codewhale_telemetry::counters::http_status_counter(status) { |
| 5721 | counters.bump_error(counter); |
| 5722 | } |
| 5723 | } |
| 5724 | |
| 5725 | /// Translate the structured `LlmError` into both a categorical label |
| 5726 | /// (for structured logs / metrics) and a short human reason string |
| 5727 | /// (for the retry banner). Returning both from one match avoids the |
| 5728 | /// double-classification we had before. |
| 5729 | fn retry_reason_label_and_human(err: &LlmError) -> (&'static str, String) { |
| 5730 | // The variant, never the payload. Every `LlmError` variant carries the raw |
| 5731 | // provider HTTP body verbatim, and a 400 from a content filter routinely |
| 5732 | // echoes the prompt. |
| 5733 | if matches!( |
| 5734 | err, |
| 5735 | LlmError::NetworkError(_) | LlmError::HeaderTimeout { .. } | LlmError::Timeout(_) |
| 5736 | ) { |
| 5737 | codewhale_telemetry::session_counters() |
| 5738 | .bump_error(codewhale_telemetry::ErrorCounter::NetworkError); |
| 5739 | } |
| 5740 | match err { |
| 5741 | LlmError::RateLimited { retry_after, .. } | LlmError::QuotaWindow { retry_after, .. } => { |
| 5742 | let human = if let Some(after) = retry_after { |
| 5743 | format!("rate limited (Retry-After {}s)", after.as_secs()) |
| 5744 | } else { |
| 5745 | "rate limited".to_string() |
| 5746 | }; |
| 5747 | ("rate_limited", human) |
| 5748 | } |
| 5749 | LlmError::ServerError { status, .. } => ("server_error", format!("upstream {status}")), |
| 5750 | LlmError::NetworkError(_) | LlmError::HeaderTimeout { .. } => ( |
| 5751 | "network_error", |
| 5752 | "network error; request outcome unknown".to_string(), |
| 5753 | ), |
| 5754 | LlmError::ConnectError { .. } => ( |
| 5755 | "connect_error", |
| 5756 | "connection failed before dispatch".to_string(), |
| 5757 | ), |
| 5758 | LlmError::Timeout(_) => ("timeout", "timeout".to_string()), |
| 5759 | _ => ("other", "other".to_string()), |
| 5760 | } |
| 5761 | } |
| 5762 | |
| 5763 | impl CodewhaleClient { |
| 5764 | /// Execute a non-streaming request without consulting or updating the |
| 5765 | /// process-global response cache. |
| 5766 | /// |
| 5767 | /// Request previews use this only for Auto's auxiliary router classifier: |
| 5768 | /// the classifier may call its configured provider, but an inspection must |
| 5769 | /// not perturb later production routing through shared cache state. |
| 5770 | pub async fn create_message_without_response_cache( |
| 5771 | &self, |
| 5772 | request: MessageRequest, |
| 5773 | observation: crate::llm_client::RequestRetryObservation, |
| 5774 | ) -> Result<MessageResponse> { |
| 5775 | let mut isolated = self.clone(); |
| 5776 | isolated.isolated_request_state = true; |
| 5777 | // The ordinary clone shares its provider token bucket so concurrent |
| 5778 | // production calls observe one rate budget. Request inspection is an |
| 5779 | // auxiliary classifier call, however: it must neither consume nor |
| 5780 | // inherit that mutable foreground state. |
| 5781 | isolated.rate_limiter = Arc::new(AsyncMutex::new(TokenBucket::from_env())); |
| 5782 | crate::llm_client::observe_request_retries( |
| 5783 | Some(observation), |
| 5784 | isolated.create_message_with_cache_policy(request, false), |
| 5785 | ) |
| 5786 | .await |
| 5787 | } |
| 5788 | |
| 5789 | async fn create_message_with_cache_policy( |
| 5790 | &self, |
| 5791 | request: MessageRequest, |
| 5792 | allow_response_cache: bool, |
| 5793 | ) -> Result<MessageResponse> { |
| 5794 | let _inference = self.acquire_remote_control_inference_permit().await; |
| 5795 | let _permit = self.acquire_provider_request_permit().await; |
| 5796 | let cacheable = allow_response_cache |
| 5797 | && codewhale_runtime::llm_response_cache::request_is_cacheable(&request); |
| 5798 | let mut prepared = self.prepare_outbound_request(request.clone(), false)?; |
| 5799 | let mut warning = prepared.tool_projection_warning(); |
| 5800 | if let Some(warning) = &warning { |
| 5801 | tracing::warn!( |
| 5802 | provider = %warning.provider, |
| 5803 | omitted_tool_count = warning.omitted_tool_count, |
| 5804 | omitted_tools = ?warning.omitted_tool_names, |
| 5805 | "omitted incompatible tools for this request" |
| 5806 | ); |
| 5807 | } |
| 5808 | let mut response = match self.dispatch_prepared_message(&prepared, cacheable).await { |
| 5809 | Err(error) => { |
| 5810 | let Some(retry) = |
| 5811 | self.prepare_image_elision_retry(request, false, &prepared, &error)? |
| 5812 | else { |
| 5813 | return Err(error); |
| 5814 | }; |
| 5815 | crate::llm_client::observe_transport_attempt(); |
| 5816 | prepared = retry; |
| 5817 | warning = prepared.tool_projection_warning(); |
| 5818 | self.dispatch_prepared_message(&prepared, cacheable).await? |
| 5819 | } |
| 5820 | Ok(response) => response, |
| 5821 | }; |
| 5822 | response.tool_projection_warning = warning; |
| 5823 | Ok(response) |
| 5824 | } |
| 5825 | |
| 5826 | fn prepare_image_elision_retry( |
| 5827 | &self, |
| 5828 | mut request: MessageRequest, |
| 5829 | stream: bool, |
| 5830 | previous: &PreparedOutboundRequest, |
| 5831 | error: &anyhow::Error, |
| 5832 | ) -> Result<Option<PreparedOutboundRequest>> { |
| 5833 | if !matches!( |
| 5834 | error.downcast_ref::<LlmError>(), |
| 5835 | Some(LlmError::InvalidRequest { status: 413, .. }) |
| 5836 | ) { |
| 5837 | return Ok(None); |
| 5838 | } |
| 5839 | if previous |
| 5840 | .image_projection |
| 5841 | .as_ref() |
| 5842 | .is_some_and(|projection| projection.retained_newest_blocks == 0) |
| 5843 | { |
| 5844 | return Ok(None); |
| 5845 | } |
| 5846 | let window = codewhale_models::image_window::cap_request_images_with_notes( |
| 5847 | &mut request.messages, |
| 5848 | 0, |
| 5849 | prepared::REQUEST_BODY_413_IMAGE_NOTE, |
| 5850 | prepared::REQUEST_BODY_413_IMAGE_NOTE, |
| 5851 | ); |
| 5852 | if window.elided == 0 { |
| 5853 | return Ok(None); |
| 5854 | } |
| 5855 | let mut retry = self.prepare_outbound_request(request, stream)?; |
| 5856 | let before = previous.serialized_body_bytes()?; |
| 5857 | let after = retry.serialized_body_bytes()?; |
| 5858 | if after >= before { |
| 5859 | return Ok(None); |
| 5860 | } |
| 5861 | retry.image_projection = Some(crate::llm_client::ImageProjectionReceipt { |
| 5862 | cause: "initial_http_413".into(), |
| 5863 | original_image_blocks: window.total, |
| 5864 | omitted_oldest_blocks: window.elided, |
| 5865 | retained_newest_blocks: 0, |
| 5866 | body_bytes_before: before, |
| 5867 | body_bytes_after: after, |
| 5868 | omission_note: prepared::REQUEST_BODY_413_IMAGE_NOTE.into(), |
| 5869 | }); |
| 5870 | retry.image_omission_notice = Some(format!( |
| 5871 | "HTTP 413 recovery: retrying once without image attachments; serialized request reduced from {before} to {after} bytes. Original images remain in the session.", |
| 5872 | )); |
| 5873 | Ok(Some(retry)) |
| 5874 | } |
| 5875 | |
| 5876 | async fn observe_prepared_request(&self, prepared: &PreparedOutboundRequest) { |
| 5877 | observe_outbound_wire(|| OutboundWireObservation { |
| 5878 | provider_id: prepared.endpoint.provider_id.clone(), |
| 5879 | route_id: self.admitted_identity.persisted_id().map(str::to_owned), |
| 5880 | endpoint_fingerprint: prepared.endpoint_fingerprint(), |
| 5881 | wire_model: prepared.wire_model.clone(), |
| 5882 | wire_dialect: prepared.dialect.as_str().to_owned(), |
| 5883 | responses_profile_id: prepared |
| 5884 | .responses_profile_id |
| 5885 | .map(|id| id.as_str().to_owned()), |
| 5886 | tools: prepared.tool_wire_measurement().bounded_for_receipt(), |
| 5887 | image_projection: prepared.image_projection.clone(), |
| 5888 | }); |
| 5889 | if let Some(notice) = &prepared.image_omission_notice { |
| 5890 | crate::llm_client::observe_transport_status(notice.clone()).await; |
| 5891 | } |
| 5892 | } |
| 5893 | |
| 5894 | async fn dispatch_prepared_message( |
| 5895 | &self, |
| 5896 | prepared: &PreparedOutboundRequest, |
| 5897 | cacheable: bool, |
| 5898 | ) -> Result<MessageResponse> { |
| 5899 | self.observe_prepared_request(prepared).await; |
| 5900 | match prepared.dialect { |
| 5901 | WireDialect::OpenAiResponses => self.handle_responses_message(prepared).await, |
| 5902 | WireDialect::AnthropicMessages => self.handle_anthropic_message(prepared).await, |
| 5903 | WireDialect::GenerateContent => self.handle_gemini_message(prepared).await, |
| 5904 | WireDialect::ChatCompletions => self.create_message_chat(prepared, cacheable).await, |
| 5905 | } |
| 5906 | } |
| 5907 | |
| 5908 | async fn dispatch_prepared_stream( |
| 5909 | &self, |
| 5910 | prepared: &PreparedOutboundRequest, |
| 5911 | ) -> Result<crate::llm_client::StreamEventBox> { |
| 5912 | self.observe_prepared_request(prepared).await; |
| 5913 | match prepared.dialect { |
| 5914 | WireDialect::OpenAiResponses => self.handle_responses_stream(prepared).await, |
| 5915 | WireDialect::AnthropicMessages => self.handle_anthropic_stream(prepared).await, |
| 5916 | WireDialect::GenerateContent => self.handle_gemini_stream(prepared).await, |
| 5917 | WireDialect::ChatCompletions => self.handle_chat_completion_stream(prepared).await, |
| 5918 | } |
| 5919 | } |
| 5920 | } |
| 5921 | |
| 5922 | impl LlmClient for CodewhaleClient { |
| 5923 | fn provider_name(&self) -> &'static str { |
| 5924 | self.api_provider.as_str() |
| 5925 | } |
| 5926 | |
| 5927 | fn model(&self) -> &str { |
| 5928 | &self.default_model |
| 5929 | } |
| 5930 | |
| 5931 | fn measure_outbound_tools( |
| 5932 | &self, |
| 5933 | request: MessageRequest, |
| 5934 | ) -> Result<Option<ToolWireMeasurement>> { |
| 5935 | self.prepare_outbound_request(request, true) |
| 5936 | .map(|prepared| Some(prepared.tool_wire_measurement())) |
| 5937 | } |
| 5938 | |
| 5939 | fn billing_base_url(&self) -> Option<&str> { |
| 5940 | Some(&self.base_url) |
| 5941 | } |
| 5942 | |
| 5943 | fn route_limits(&self) -> Option<RouteLimits> { |
| 5944 | CodewhaleClient::route_limits(self) |
| 5945 | } |
| 5946 | |
| 5947 | fn effective_context_window(&self, model: &str) -> Option<u32> { |
| 5948 | self.context_window_for_model(model) |
| 5949 | } |
| 5950 | |
| 5951 | fn effective_max_output_tokens(&self, requested_model: &str) -> u32 { |
| 5952 | CodewhaleClient::effective_max_output_tokens(self, requested_model) |
| 5953 | } |
| 5954 | |
| 5955 | fn effective_route_envelope( |
| 5956 | &self, |
| 5957 | requested_model: &str, |
| 5958 | dispatched_at: chrono::DateTime<chrono::Utc>, |
| 5959 | ) -> crate::cost_status::EffectiveRouteEnvelope { |
| 5960 | CodewhaleClient::effective_route_envelope(self, requested_model, dispatched_at) |
| 5961 | } |
| 5962 | |
| 5963 | fn supports_catalog_reviewer_model(&self, candidate: &str) -> bool { |
| 5964 | codewhale_config::provider_base_url_is_official(self.api_provider, &self.base_url) |
| 5965 | && self |
| 5966 | .resolve_model_route(candidate) |
| 5967 | .is_ok_and(|resolved| resolved.protocol() == self.wire_format) |
| 5968 | } |
| 5969 | |
| 5970 | async fn health_check(&self) -> Result<bool> { |
| 5971 | if model_listing_unavailable(self.api_provider, &self.base_url) { |
| 5972 | anyhow::bail!("Provider health is unobserved: no documented model-list endpoint"); |
| 5973 | } |
| 5974 | if !provider_api_key_verification_is_observed_for_route(self.api_provider, &self.base_url) { |
| 5975 | self.mark_request_success().await; |
| 5976 | return Ok(true); |
| 5977 | } |
| 5978 | let health_url = model_listing_url(self.api_provider, self.catalog_base_url()); |
| 5979 | self.wait_for_rate_limit().await; |
| 5980 | let response = self |
| 5981 | .authorize_plugin_request( |
| 5982 | self.models_http_client |
| 5983 | .get(health_url) |
| 5984 | .timeout(NON_STREAMING_HTTP_TIMEOUT), |
| 5985 | ) |
| 5986 | .await? |
| 5987 | .send() |
| 5988 | .await; |
| 5989 | match response { |
| 5990 | Ok(resp) if resp.status().is_success() => { |
| 5991 | // Consume the response body so the connection can be returned to the pool. |
| 5992 | let _ = bounded_error_text(resp, ERROR_BODY_MAX_BYTES).await; |
| 5993 | self.mark_request_success().await; |
| 5994 | Ok(true) |
| 5995 | } |
| 5996 | Ok(resp) => { |
| 5997 | self.mark_request_failure(&format!("health status={}", resp.status())) |
| 5998 | .await; |
| 5999 | Ok(false) |
| 6000 | } |
| 6001 | Err(err) => { |
| 6002 | self.mark_request_failure(&format!("health error={}", err.without_url())) |
| 6003 | .await; |
| 6004 | Ok(false) |
| 6005 | } |
| 6006 | } |
| 6007 | } |
| 6008 | |
| 6009 | async fn create_message(&self, request: MessageRequest) -> Result<MessageResponse> { |
| 6010 | self.create_message_with_cache_policy(request, true).await |
| 6011 | } |
| 6012 | |
| 6013 | async fn create_message_uncached(&self, request: MessageRequest) -> Result<MessageResponse> { |
| 6014 | // Keep shared provider permits and rate limits. Only the response |
| 6015 | // cache is bypassed; a guardian is still real, metered inference. |
| 6016 | self.create_message_with_cache_policy(request, false).await |
| 6017 | } |
| 6018 | |
| 6019 | async fn create_message_stream( |
| 6020 | &self, |
| 6021 | request: MessageRequest, |
| 6022 | ) -> Result<crate::llm_client::StreamEventBox> { |
| 6023 | let inference = self.acquire_remote_control_inference_permit().await; |
| 6024 | let permit = self.acquire_provider_request_permit().await; |
| 6025 | let mut prepared = self.prepare_outbound_request(request.clone(), true)?; |
| 6026 | let stream = match self.dispatch_prepared_stream(&prepared).await { |
| 6027 | Err(error) => { |
| 6028 | let Some(retry) = |
| 6029 | self.prepare_image_elision_retry(request, true, &prepared, &error)? |
| 6030 | else { |
| 6031 | return Err(error); |
| 6032 | }; |
| 6033 | crate::llm_client::observe_transport_attempt(); |
| 6034 | prepared = retry; |
| 6035 | self.dispatch_prepared_stream(&prepared).await? |
| 6036 | } |
| 6037 | Ok(stream) => stream, |
| 6038 | }; |
| 6039 | let stream = if let Some(warning) = prepared.tool_projection_warning() { |
| 6040 | let event = codewhale_models::StreamEvent::ToolProjectionWarning { |
| 6041 | provider: warning.provider, |
| 6042 | omitted_tool_names: warning.omitted_tool_names, |
| 6043 | omitted_tool_count: warning.omitted_tool_count, |
| 6044 | }; |
| 6045 | futures_util::stream::once(async move { Ok(event) }) |
| 6046 | .chain(stream) |
| 6047 | .boxed() |
| 6048 | } else { |
| 6049 | stream |
| 6050 | }; |
| 6051 | let stream = Self::hold_provider_request_permit_for_stream(stream, permit); |
| 6052 | Ok(Self::hold_remote_control_inference_permit_for_stream( |
| 6053 | stream, inference, |
| 6054 | )) |
| 6055 | } |
| 6056 | } |
| 6057 | |
| 6058 | #[derive(Debug, Deserialize)] |
| 6059 | struct ModelsListResponse { |
| 6060 | data: Vec<ModelListItem>, |
| 6061 | } |
| 6062 | |
| 6063 | /// The list envelope is validated as a whole; each row is decoded on its own |
| 6064 | /// so one malformed row cannot fail the entire roster (#6690). Rows stay raw |
| 6065 | /// text rather than `serde_json::Value`: a `Value` map keeps the last of a |
| 6066 | /// duplicated key, which would silently accept an ambiguous row (two `id`s, |
| 6067 | /// two `pricing.prompt`s) instead of skipping it as malformed. |
| 6068 | #[derive(Debug, Deserialize)] |
| 6069 | struct OpenRouterModelsResponse { |
| 6070 | data: Vec<Box<serde_json::value::RawValue>>, |
| 6071 | } |
| 6072 | |
| 6073 | #[derive(Debug, Deserialize)] |
| 6074 | struct ModelListItem { |
| 6075 | id: String, |
| 6076 | #[serde(default)] |
| 6077 | owned_by: Option<String>, |
| 6078 | #[serde(default)] |
| 6079 | created: Option<u64>, |
| 6080 | } |
| 6081 | |
| 6082 | /// Token limits a provider's own `/models` listing states for one row. |
| 6083 | /// |
| 6084 | /// Relays publish the same two numbers under several shapes: the |
| 6085 | /// OpenAI-style `limit` block, flat `context_length` / `max_model_len` |
| 6086 | /// fields, or a vendor `metadata` block. Each field is read only as the |
| 6087 | /// token count it names; a row that states nothing stays empty so the |
| 6088 | /// resolver can still tell "the provider said 1M" from "nobody said". |
| 6089 | #[derive(Debug, Default, Deserialize)] |
| 6090 | struct ListedRowLimits { |
| 6091 | #[serde(default)] |
| 6092 | context_length: Option<CatalogNumber>, |
| 6093 | #[serde(default)] |
| 6094 | context_window: Option<CatalogNumber>, |
| 6095 | #[serde(default)] |
| 6096 | max_model_len: Option<CatalogNumber>, |
| 6097 | #[serde(default)] |
| 6098 | max_context_length: Option<CatalogNumber>, |
| 6099 | #[serde(default)] |
| 6100 | context_size: Option<CatalogNumber>, |
| 6101 | #[serde(default)] |
| 6102 | max_input_tokens: Option<CatalogNumber>, |
| 6103 | #[serde(default, alias = "inputTokenLimit")] |
| 6104 | input_token_limit: Option<CatalogNumber>, |
| 6105 | #[serde(default)] |
| 6106 | max_output_tokens: Option<CatalogNumber>, |
| 6107 | #[serde(default)] |
| 6108 | max_completion_tokens: Option<CatalogNumber>, |
| 6109 | #[serde(default, alias = "outputTokenLimit")] |
| 6110 | output_token_limit: Option<CatalogNumber>, |
| 6111 | #[serde(default)] |
| 6112 | max_tokens: Option<CatalogNumber>, |
| 6113 | #[serde(default)] |
| 6114 | limit: Option<ListedLimitBlock>, |
| 6115 | #[serde(default)] |
| 6116 | limits: Option<ListedLimitBlock>, |
| 6117 | #[serde(default)] |
| 6118 | top_provider: Option<ListedTopProviderBlock>, |
| 6119 | #[serde(default)] |
| 6120 | metadata: Option<ListedMetadataBlock>, |
| 6121 | } |
| 6122 | |
| 6123 | #[derive(Debug, Default, Deserialize)] |
| 6124 | struct ListedLimitBlock { |
| 6125 | #[serde(default)] |
| 6126 | context: Option<CatalogNumber>, |
| 6127 | #[serde(default)] |
| 6128 | output: Option<CatalogNumber>, |
| 6129 | } |
| 6130 | |
| 6131 | #[derive(Debug, Default, Deserialize)] |
| 6132 | struct ListedTopProviderBlock { |
| 6133 | #[serde(default)] |
| 6134 | context_length: Option<CatalogNumber>, |
| 6135 | #[serde(default)] |
| 6136 | max_completion_tokens: Option<CatalogNumber>, |
| 6137 | #[serde(default)] |
| 6138 | max_output_tokens: Option<CatalogNumber>, |
| 6139 | } |
| 6140 | |
| 6141 | /// Relay-specific limits. Some gateways publish a private `metadata` block |
| 6142 | /// beside the OpenAI list shape; `context_limit` is the model capability and |
| 6143 | /// `context_budget` the share this deployment will actually accept, so the |
| 6144 | /// capability is preferred when both are stated. |
| 6145 | #[derive(Debug, Default, Deserialize)] |
| 6146 | struct ListedMetadataBlock { |
| 6147 | #[serde(default)] |
| 6148 | context_limit: Option<CatalogNumber>, |
| 6149 | #[serde(default)] |
| 6150 | context_budget: Option<CatalogNumber>, |
| 6151 | #[serde(default)] |
| 6152 | output_budget: Option<CatalogNumber>, |
| 6153 | } |
| 6154 | |
| 6155 | #[derive(Debug, Deserialize)] |
| 6156 | struct ListedRow { |
| 6157 | id: String, |
| 6158 | #[serde(flatten)] |
| 6159 | limits: ListedRowLimits, |
| 6160 | } |
| 6161 | |
| 6162 | #[derive(Debug, Deserialize)] |
| 6163 | struct ListedDeepseekRow { |
| 6164 | id: String, |
| 6165 | #[serde(default)] |
| 6166 | effort: Option<ListedDeepseekEffort>, |
| 6167 | } |
| 6168 | |
| 6169 | #[derive(Debug, Deserialize)] |
| 6170 | struct ListedDeepseekEffort { |
| 6171 | supported_levels: Vec<String>, |
| 6172 | #[serde(default)] |
| 6173 | default_level: Option<String>, |
| 6174 | } |
| 6175 | |
| 6176 | fn listed_deepseek_efforts_by_model_id( |
| 6177 | body: &str, |
| 6178 | ) -> Result<std::collections::BTreeMap<String, Vec<Value>>, CatalogRefreshError> { |
| 6179 | let page: ModelsPage<'_> = |
| 6180 | serde_json::from_str(body).map_err(|_| CatalogRefreshError::InvalidResponse)?; |
| 6181 | let rows: Vec<Box<serde_json::value::RawValue>> = serde_json::from_str(page.rows()?.get()) |
| 6182 | .map_err(|_| CatalogRefreshError::InvalidResponse)?; |
| 6183 | if rows.len() > PROVIDER_CATALOG_MAX_ROWS { |
| 6184 | return Err(CatalogRefreshError::InvalidResponse); |
| 6185 | } |
| 6186 | let mut result = std::collections::BTreeMap::new(); |
| 6187 | for row in rows { |
| 6188 | let row: ListedDeepseekRow = |
| 6189 | serde_json::from_str(row.get()).map_err(|_| CatalogRefreshError::InvalidResponse)?; |
| 6190 | if !codewhale_runtime::catalog_cache::valid_catalog_model_id(&row.id) |
| 6191 | || result.contains_key(&row.id) |
| 6192 | { |
| 6193 | return Err(CatalogRefreshError::InvalidResponse); |
| 6194 | } |
| 6195 | let mut options = Vec::new(); |
| 6196 | if let Some(effort) = row.effort { |
| 6197 | let mut seen = std::collections::BTreeSet::new(); |
| 6198 | if effort.supported_levels.len() > 16 |
| 6199 | || effort.supported_levels.iter().any(|level| { |
| 6200 | level.is_empty() |
| 6201 | || level.len() > 32 |
| 6202 | || !level.bytes().all(|byte| { |
| 6203 | byte.is_ascii_lowercase() |
| 6204 | || byte.is_ascii_digit() |
| 6205 | || matches!(byte, b'_' | b'-') |
| 6206 | }) |
| 6207 | || !seen.insert(level) |
| 6208 | }) |
| 6209 | || effort |
| 6210 | .default_level |
| 6211 | .as_ref() |
| 6212 | .is_some_and(|default| !effort.supported_levels.contains(default)) |
| 6213 | { |
| 6214 | return Err(CatalogRefreshError::InvalidResponse); |
| 6215 | } |
| 6216 | let supported: Vec<_> = effort |
| 6217 | .supported_levels |
| 6218 | .iter() |
| 6219 | .filter(|level| matches!(level.as_str(), "low" | "high" | "max")) |
| 6220 | .cloned() |
| 6221 | .collect(); |
| 6222 | let mut option = json!({ "type": "effort", "values": supported }); |
| 6223 | if let Some(default) = effort |
| 6224 | .default_level |
| 6225 | .filter(|level| matches!(level.as_str(), "low" | "high" | "max")) |
| 6226 | { |
| 6227 | option["default"] = json!(default); |
| 6228 | } |
| 6229 | options.push(json!({ "type": "toggle" })); |
| 6230 | options.push(option); |
| 6231 | } |
| 6232 | result.insert(row.id, options); |
| 6233 | } |
| 6234 | Ok(result) |
| 6235 | } |
| 6236 | |
| 6237 | impl ListedRowLimits { |
| 6238 | fn to_models_dev_limit(&self) -> Option<codewhale_config::models_dev::ModelsDevLimit> { |
| 6239 | let block = self.limit.as_ref(); |
| 6240 | let limits = self.limits.as_ref(); |
| 6241 | let top_provider = self.top_provider.as_ref(); |
| 6242 | let metadata = self.metadata.as_ref(); |
| 6243 | // Each candidate is parsed on its own and the first readable one wins: |
| 6244 | // selecting by presence first would let one unreadable field hide every |
| 6245 | // field below it, reintroducing the 128K fallback this pass exists to |
| 6246 | // replace. |
| 6247 | let context = [ |
| 6248 | top_provider.and_then(|block| block.context_length.as_ref()), |
| 6249 | block.and_then(|block| block.context.as_ref()), |
| 6250 | limits.and_then(|block| block.context.as_ref()), |
| 6251 | metadata.and_then(|block| block.context_limit.as_ref()), |
| 6252 | self.context_length.as_ref(), |
| 6253 | self.context_window.as_ref(), |
| 6254 | self.max_model_len.as_ref(), |
| 6255 | self.max_context_length.as_ref(), |
| 6256 | self.context_size.as_ref(), |
| 6257 | self.input_token_limit.as_ref(), |
| 6258 | self.max_input_tokens.as_ref(), |
| 6259 | metadata.and_then(|block| block.context_budget.as_ref()), |
| 6260 | ] |
| 6261 | .into_iter() |
| 6262 | .find_map(stated_token_count); |
| 6263 | let output = [ |
| 6264 | top_provider.and_then(|block| block.max_completion_tokens.as_ref()), |
| 6265 | top_provider.and_then(|block| block.max_output_tokens.as_ref()), |
| 6266 | block.and_then(|block| block.output.as_ref()), |
| 6267 | limits.and_then(|block| block.output.as_ref()), |
| 6268 | metadata.and_then(|block| block.output_budget.as_ref()), |
| 6269 | self.max_output_tokens.as_ref(), |
| 6270 | self.max_completion_tokens.as_ref(), |
| 6271 | self.output_token_limit.as_ref(), |
| 6272 | self.max_tokens.as_ref(), |
| 6273 | ] |
| 6274 | .into_iter() |
| 6275 | .find_map(stated_token_count); |
| 6276 | (context.is_some() || output.is_some()).then_some( |
| 6277 | codewhale_config::models_dev::ModelsDevLimit { |
| 6278 | context, |
| 6279 | input: None, |
| 6280 | output, |
| 6281 | }, |
| 6282 | ) |
| 6283 | } |
| 6284 | } |
| 6285 | |
| 6286 | #[derive(Debug, Default)] |
| 6287 | struct ListedRowCapabilities { |
| 6288 | model_type: Option<String>, |
| 6289 | status: Option<String>, |
| 6290 | modalities: Option<codewhale_config::models_dev::ModelsDevModalities>, |
| 6291 | reasoning: Option<bool>, |
| 6292 | tool_call: Option<bool>, |
| 6293 | structured_output: Option<bool>, |
| 6294 | reasoning_options: Vec<Value>, |
| 6295 | reasoning_options_present: bool, |
| 6296 | } |
| 6297 | |
| 6298 | #[derive(Debug, Default, Deserialize)] |
| 6299 | struct ListedCapabilitiesRow { |
| 6300 | id: String, |
| 6301 | #[serde(flatten)] |
| 6302 | fields: ListedCapabilitiesFields, |
| 6303 | } |
| 6304 | |
| 6305 | #[derive(Debug, Default, Deserialize)] |
| 6306 | struct ListedCapabilitiesFields { |
| 6307 | #[serde(rename = "type")] |
| 6308 | model_type: Option<Value>, |
| 6309 | status: Option<Value>, |
| 6310 | modalities: Option<Value>, |
| 6311 | #[serde(default)] |
| 6312 | supported_parameters: Option<Vec<String>>, |
| 6313 | #[serde(default)] |
| 6314 | supported_features: Option<Vec<String>>, |
| 6315 | #[serde(default)] |
| 6316 | features: Option<Vec<String>>, |
| 6317 | #[serde(default)] |
| 6318 | reasoning: Option<bool>, |
| 6319 | #[serde(default)] |
| 6320 | supports_reasoning: Option<bool>, |
| 6321 | #[serde(default)] |
| 6322 | thinking: Option<Value>, |
| 6323 | #[serde(default)] |
| 6324 | capabilities: Option<ListedCapabilitiesBlock>, |
| 6325 | #[serde(default)] |
| 6326 | tool_call: Option<bool>, |
| 6327 | #[serde(default)] |
| 6328 | supports_tools: Option<bool>, |
| 6329 | #[serde(default)] |
| 6330 | structured_output: Option<bool>, |
| 6331 | #[serde(default)] |
| 6332 | supports_structured_output: Option<bool>, |
| 6333 | #[serde(default)] |
| 6334 | reasoning_options: Option<Vec<Value>>, |
| 6335 | #[serde(default)] |
| 6336 | supported_reasoning_levels: Option<Value>, |
| 6337 | #[serde(default)] |
| 6338 | default_reasoning_level: Option<String>, |
| 6339 | } |
| 6340 | |
| 6341 | #[derive(Debug, Default, Deserialize)] |
| 6342 | struct ListedCapabilitiesBlock { |
| 6343 | #[serde(default)] |
| 6344 | thinking: Option<Value>, |
| 6345 | #[serde(default)] |
| 6346 | effort: Option<Value>, |
| 6347 | #[serde(default)] |
| 6348 | reasoning: Option<Value>, |
| 6349 | #[serde(default)] |
| 6350 | function_calling: Option<Value>, |
| 6351 | #[serde(default)] |
| 6352 | tools: Option<Value>, |
| 6353 | } |
| 6354 | |
| 6355 | fn value_supported_flag(value: &Value) -> Option<bool> { |
| 6356 | value |
| 6357 | .as_bool() |
| 6358 | .or_else(|| value.get("supported").and_then(Value::as_bool)) |
| 6359 | } |
| 6360 | |
| 6361 | fn valid_effort_token(raw: &str) -> Option<String> { |
| 6362 | let token = raw.trim().to_ascii_lowercase(); |
| 6363 | (!token.is_empty() |
| 6364 | && token.len() <= 32 |
| 6365 | && token.bytes().all(|byte| { |
| 6366 | byte.is_ascii_lowercase() || byte.is_ascii_digit() || matches!(byte, b'_' | b'-') |
| 6367 | })) |
| 6368 | .then_some(token) |
| 6369 | } |
| 6370 | |
| 6371 | fn reasoning_options_from_levels( |
| 6372 | levels: &Value, |
| 6373 | default_level: Option<&str>, |
| 6374 | ) -> Option<Vec<Value>> { |
| 6375 | let items = levels.as_array()?; |
| 6376 | let mut values = Vec::new(); |
| 6377 | for item in items { |
| 6378 | let raw = item |
| 6379 | .as_str() |
| 6380 | .or_else(|| item.get("effort").and_then(Value::as_str)) |
| 6381 | .or_else(|| item.get("level").and_then(Value::as_str)) |
| 6382 | .or_else(|| item.get("value").and_then(Value::as_str)); |
| 6383 | if let Some(token) = raw.and_then(valid_effort_token) |
| 6384 | && !values.iter().any(|existing| existing == &token) |
| 6385 | { |
| 6386 | values.push(token); |
| 6387 | } |
| 6388 | } |
| 6389 | if values.is_empty() { |
| 6390 | return None; |
| 6391 | } |
| 6392 | let mut option = json!({ "type": "effort", "values": values }); |
| 6393 | if let Some(default) = default_level.and_then(valid_effort_token).filter(|token| { |
| 6394 | option["values"] |
| 6395 | .as_array() |
| 6396 | .is_some_and(|arr| arr.iter().any(|v| v.as_str() == Some(token.as_str()))) |
| 6397 | }) { |
| 6398 | option["default"] = json!(default); |
| 6399 | } |
| 6400 | Some(vec![option]) |
| 6401 | } |
| 6402 | |
| 6403 | fn reasoning_options_from_capabilities_effort(effort: &Value) -> Option<Vec<Value>> { |
| 6404 | if let Some(values) = effort.get("values") { |
| 6405 | return reasoning_options_from_levels( |
| 6406 | values, |
| 6407 | effort.get("default").and_then(Value::as_str), |
| 6408 | ); |
| 6409 | } |
| 6410 | if let Some(levels) = effort.get("supported_levels") { |
| 6411 | return reasoning_options_from_levels( |
| 6412 | levels, |
| 6413 | effort.get("default_level").and_then(Value::as_str), |
| 6414 | ); |
| 6415 | } |
| 6416 | None |
| 6417 | } |
| 6418 | |
| 6419 | fn extract_row_capabilities(row: &ListedCapabilitiesFields) -> ListedRowCapabilities { |
| 6420 | let mut features = Vec::new(); |
| 6421 | for item in row.supported_features.iter().chain(&row.features).flatten() { |
| 6422 | let normalized = item.trim(); |
| 6423 | if !normalized.is_empty() && !features.iter().any(|existing| existing == normalized) { |
| 6424 | features.push(normalized.to_string()); |
| 6425 | } |
| 6426 | } |
| 6427 | let has_feature = (!features.is_empty()).then_some(features); |
| 6428 | let feature_support = |needles: &[&str]| { |
| 6429 | has_feature.as_ref().map(|items| { |
| 6430 | items |
| 6431 | .iter() |
| 6432 | .any(|feature| feature_matches_any(feature, needles)) |
| 6433 | }) |
| 6434 | }; |
| 6435 | let param_support = |pred: &dyn Fn(&str) -> bool| { |
| 6436 | row.supported_parameters |
| 6437 | .as_ref() |
| 6438 | .map(|params| params.iter().any(|param| pred(param))) |
| 6439 | }; |
| 6440 | |
| 6441 | let (reasoning_options, reasoning_options_present) = |
| 6442 | if let Some(options) = row.reasoning_options.as_ref() { |
| 6443 | (options.clone(), true) |
| 6444 | } else if let Some(options) = row.supported_reasoning_levels.as_ref().and_then(|levels| { |
| 6445 | reasoning_options_from_levels(levels, row.default_reasoning_level.as_deref()) |
| 6446 | }) { |
| 6447 | (options, true) |
| 6448 | } else if let Some(options) = row |
| 6449 | .capabilities |
| 6450 | .as_ref() |
| 6451 | .and_then(|caps| caps.effort.as_ref()) |
| 6452 | .and_then(reasoning_options_from_capabilities_effort) |
| 6453 | { |
| 6454 | (options, true) |
| 6455 | } else { |
| 6456 | (Vec::new(), false) |
| 6457 | }; |
| 6458 | |
| 6459 | let reasoning = row |
| 6460 | .reasoning |
| 6461 | .or(row.supports_reasoning) |
| 6462 | .or_else(|| row.thinking.as_ref().and_then(value_supported_flag)) |
| 6463 | .or_else(|| { |
| 6464 | row.capabilities.as_ref().and_then(|caps| { |
| 6465 | caps.reasoning |
| 6466 | .as_ref() |
| 6467 | .and_then(value_supported_flag) |
| 6468 | .or_else(|| caps.thinking.as_ref().and_then(value_supported_flag)) |
| 6469 | }) |
| 6470 | }) |
| 6471 | .or_else(|| { |
| 6472 | param_support(&|p| { |
| 6473 | p == "reasoning" || p == "include_reasoning" || p.contains("reasoning") |
| 6474 | }) |
| 6475 | }) |
| 6476 | .or_else(|| feature_support(&["reasoning", "include_reasoning"])) |
| 6477 | .or_else(|| (!reasoning_options.is_empty()).then_some(true)); |
| 6478 | |
| 6479 | let tools = row.capabilities.as_ref(); |
| 6480 | let explicit_tool_flags = [ |
| 6481 | row.tool_call, |
| 6482 | row.supports_tools, |
| 6483 | tools |
| 6484 | .and_then(|caps| caps.function_calling.as_ref()) |
| 6485 | .and_then(value_supported_flag), |
| 6486 | tools |
| 6487 | .and_then(|caps| caps.tools.as_ref()) |
| 6488 | .and_then(value_supported_flag), |
| 6489 | ]; |
| 6490 | let explicit_tool_support = if explicit_tool_flags.contains(&Some(false)) { |
| 6491 | Some(false) |
| 6492 | } else { |
| 6493 | explicit_tool_flags.into_iter().flatten().next() |
| 6494 | }; |
| 6495 | let tool_call = explicit_tool_support |
| 6496 | .or_else(|| { |
| 6497 | param_support(&|p| { |
| 6498 | p == "tools" || p == "tool_choice" || p == "functions" || p.contains("tool") |
| 6499 | }) |
| 6500 | }) |
| 6501 | .or_else(|| feature_support(&["tools", "tool_calling", "function_calling"])); |
| 6502 | |
| 6503 | let structured_output = row |
| 6504 | .structured_output |
| 6505 | .or(row.supports_structured_output) |
| 6506 | .or_else(|| param_support(&|p| matches!(p, "response_format" | "structured_outputs"))) |
| 6507 | .or_else(|| { |
| 6508 | feature_support(&["structured_output", "structured_outputs", "response_format"]) |
| 6509 | }); |
| 6510 | |
| 6511 | let bounded_text = |value: Option<&Value>| { |
| 6512 | value |
| 6513 | .and_then(Value::as_str) |
| 6514 | .map(str::trim) |
| 6515 | .filter(|value| { |
| 6516 | !value.is_empty() && value.len() <= 64 && !value.chars().any(char::is_whitespace) |
| 6517 | }) |
| 6518 | .filter(|value| !value.chars().any(char::is_control)) |
| 6519 | .map(str::to_owned) |
| 6520 | }; |
| 6521 | let modality_list = |direction: &str| { |
| 6522 | row.modalities |
| 6523 | .as_ref() |
| 6524 | .and_then(|value| value.get(direction)) |
| 6525 | .and_then(Value::as_array) |
| 6526 | .into_iter() |
| 6527 | .flatten() |
| 6528 | .filter_map(|value| bounded_text(Some(value))) |
| 6529 | .take(32) |
| 6530 | .collect::<Vec<_>>() |
| 6531 | }; |
| 6532 | let input = modality_list("input"); |
| 6533 | let output = modality_list("output"); |
| 6534 | ListedRowCapabilities { |
| 6535 | model_type: bounded_text(row.model_type.as_ref()) |
| 6536 | .filter(|kind| !kind.eq_ignore_ascii_case("model")), |
| 6537 | status: bounded_text(row.status.as_ref()), |
| 6538 | modalities: (!input.is_empty() || !output.is_empty()) |
| 6539 | .then_some(codewhale_config::models_dev::ModelsDevModalities { input, output }), |
| 6540 | reasoning, |
| 6541 | tool_call, |
| 6542 | structured_output, |
| 6543 | reasoning_options, |
| 6544 | reasoning_options_present, |
| 6545 | } |
| 6546 | } |
| 6547 | |
| 6548 | fn listed_capabilities_by_model_id( |
| 6549 | body: &str, |
| 6550 | ) -> std::collections::BTreeMap<String, ListedRowCapabilities> { |
| 6551 | let Ok(page) = serde_json::from_str::<ModelsPage<'_>>(body) else { |
| 6552 | return std::collections::BTreeMap::new(); |
| 6553 | }; |
| 6554 | let Ok(rows) = page.rows() else { |
| 6555 | return std::collections::BTreeMap::new(); |
| 6556 | }; |
| 6557 | let Ok(rows) = serde_json::from_str::<Vec<Box<serde_json::value::RawValue>>>(rows.get()) else { |
| 6558 | return std::collections::BTreeMap::new(); |
| 6559 | }; |
| 6560 | let mut capabilities = std::collections::BTreeMap::new(); |
| 6561 | for row in rows { |
| 6562 | let Ok(row) = serde_json::from_str::<ListedCapabilitiesRow>(row.get()) else { |
| 6563 | continue; |
| 6564 | }; |
| 6565 | let caps = extract_row_capabilities(&row.fields); |
| 6566 | if caps.model_type.is_some() |
| 6567 | || caps.status.is_some() |
| 6568 | || caps.modalities.is_some() |
| 6569 | || caps.reasoning.is_some() |
| 6570 | || caps.tool_call.is_some() |
| 6571 | || caps.structured_output.is_some() |
| 6572 | || caps.reasoning_options_present |
| 6573 | { |
| 6574 | capabilities.insert(row.id, caps); |
| 6575 | } |
| 6576 | } |
| 6577 | capabilities |
| 6578 | } |
| 6579 | |
| 6580 | /// A positive whole token count, or `None` when the field is unreadable. |
| 6581 | fn stated_token_count(value: Option<&CatalogNumber>) -> Option<u64> { |
| 6582 | catalog_number_u64(value) |
| 6583 | .ok() |
| 6584 | .flatten() |
| 6585 | .filter(|tokens| *tokens > 0) |
| 6586 | } |
| 6587 | |
| 6588 | /// Per-model limits a provider's `/models` body states, keyed by wire id. |
| 6589 | /// |
| 6590 | /// Best-effort by design: the roster itself has already been parsed and |
| 6591 | /// validated by the provider's typed parser, so one unreadable metadata row |
| 6592 | /// must not fail the refresh. A body with no `data` array yields no limits. |
| 6593 | fn listed_limits_by_model_id( |
| 6594 | body: &str, |
| 6595 | ) -> std::collections::BTreeMap<String, codewhale_config::models_dev::ModelsDevLimit> { |
| 6596 | let Ok(page) = serde_json::from_str::<ModelsPage<'_>>(body) else { |
| 6597 | return std::collections::BTreeMap::new(); |
| 6598 | }; |
| 6599 | let Ok(rows) = page.rows() else { |
| 6600 | return std::collections::BTreeMap::new(); |
| 6601 | }; |
| 6602 | let Ok(rows) = serde_json::from_str::<Vec<Box<serde_json::value::RawValue>>>(rows.get()) else { |
| 6603 | return std::collections::BTreeMap::new(); |
| 6604 | }; |
| 6605 | let mut limits = std::collections::BTreeMap::new(); |
| 6606 | for row in rows { |
| 6607 | let Ok(row) = serde_json::from_str::<ListedRow>(row.get()) else { |
| 6608 | continue; |
| 6609 | }; |
| 6610 | if let Some(limit) = row.limits.to_models_dev_limit() { |
| 6611 | limits.insert(row.id, limit); |
| 6612 | } |
| 6613 | } |
| 6614 | limits |
| 6615 | } |
| 6616 | |
| 6617 | /// OpenRouter `/models` response item with full capability metadata (#3385). |
| 6618 | #[derive(Debug, Deserialize)] |
| 6619 | struct OpenRouterModelItem { |
| 6620 | id: String, |
| 6621 | #[serde(default)] |
| 6622 | context_length: Option<u32>, |
| 6623 | #[serde(default)] |
| 6624 | pricing: Option<OpenRouterPricing>, |
| 6625 | #[serde(default)] |
| 6626 | top_provider: Option<OpenRouterTopProvider>, |
| 6627 | #[serde(default)] |
| 6628 | supported_parameters: Option<Vec<String>>, |
| 6629 | #[serde(default)] |
| 6630 | architecture: Option<OpenRouterArchitecture>, |
| 6631 | #[serde(default)] |
| 6632 | reasoning_options: Option<Vec<Value>>, |
| 6633 | #[serde(default)] |
| 6634 | supported_reasoning_levels: Option<Value>, |
| 6635 | #[serde(default)] |
| 6636 | default_reasoning_level: Option<String>, |
| 6637 | /// Endpoint dialects this gateway advertises for the row. OrcaRouter |
| 6638 | /// publishes this for every model it lists; it is what lets chat rows be |
| 6639 | /// separated from image/video/rerank rows without guessing from the name. |
| 6640 | #[serde(default)] |
| 6641 | supported_endpoint_types: Option<Vec<String>>, |
| 6642 | } |
| 6643 | |
| 6644 | #[derive(Debug, Deserialize)] |
| 6645 | struct OpenRouterPricing { |
| 6646 | #[serde(default)] |
| 6647 | prompt: Option<String>, |
| 6648 | #[serde(default)] |
| 6649 | completion: Option<String>, |
| 6650 | #[serde(default)] |
| 6651 | input_cache_read: Option<String>, |
| 6652 | /// Per-token cache-write (cache-creation) price. OpenRouter publishes this |
| 6653 | /// for the upstreams that charge a write premium (Anthropic, Qwen, …); |
| 6654 | /// dropping it undercounted every cache-creation turn on those routes. |
| 6655 | #[serde(default)] |
| 6656 | input_cache_write: Option<String>, |
| 6657 | #[serde(default)] |
| 6658 | tiers: Option<Value>, |
| 6659 | } |
| 6660 | |
| 6661 | #[derive(Debug, Deserialize)] |
| 6662 | struct OrcaRouterPriceTier { |
| 6663 | #[serde(default)] |
| 6664 | max_input_tokens: Option<u64>, |
| 6665 | #[serde(default)] |
| 6666 | prompt: Option<String>, |
| 6667 | #[serde(default)] |
| 6668 | completion: Option<String>, |
| 6669 | #[serde(default)] |
| 6670 | input_cache_read: Option<String>, |
| 6671 | #[serde(default)] |
| 6672 | input_cache_write: Option<String>, |
| 6673 | } |
| 6674 | |
| 6675 | #[derive(Debug, Deserialize)] |
| 6676 | struct OpenRouterTopProvider { |
| 6677 | #[serde(default)] |
| 6678 | context_length: Option<u32>, |
| 6679 | #[serde(default)] |
| 6680 | max_completion_tokens: Option<u32>, |
| 6681 | } |
| 6682 | |
| 6683 | #[derive(Debug, Deserialize)] |
| 6684 | struct OpenRouterArchitecture { |
| 6685 | #[serde(default)] |
| 6686 | modality: Option<String>, |
| 6687 | #[serde(default)] |
| 6688 | input_modalities: Option<Vec<String>>, |
| 6689 | #[serde(default)] |
| 6690 | output_modalities: Option<Vec<String>>, |
| 6691 | } |
| 6692 | |
| 6693 | /// Baseten Model APIs `/v1/models` item. |
| 6694 | /// |
| 6695 | /// Baseten publishes OpenAI-style ids and per-token prices, while current |
| 6696 | /// serving limits and feature fields are additive. Numeric fields accept JSON |
| 6697 | /// numbers or numeric strings because both appear in provider catalogs in the |
| 6698 | /// wild; malformed or negative known fields reject the refresh so the durable |
| 6699 | /// last-known-good snapshot remains authoritative. |
| 6700 | #[derive(Debug, Deserialize)] |
| 6701 | struct BasetenModelsResponse { |
| 6702 | data: Vec<BasetenModelItem>, |
| 6703 | } |
| 6704 | |
| 6705 | #[derive(Debug, Deserialize)] |
| 6706 | struct BasetenModelItem { |
| 6707 | id: String, |
| 6708 | #[serde(default)] |
| 6709 | context_length: Option<CatalogNumber>, |
| 6710 | #[serde(default)] |
| 6711 | context_window: Option<CatalogNumber>, |
| 6712 | #[serde(default)] |
| 6713 | max_output_tokens: Option<CatalogNumber>, |
| 6714 | #[serde(default)] |
| 6715 | max_completion_tokens: Option<CatalogNumber>, |
| 6716 | #[serde(default)] |
| 6717 | limits: Option<BasetenLimits>, |
| 6718 | #[serde(default)] |
| 6719 | top_provider: Option<BasetenTopProvider>, |
| 6720 | #[serde(default)] |
| 6721 | pricing: Option<BasetenPricing>, |
| 6722 | #[serde(default)] |
| 6723 | supported_parameters: Option<Vec<String>>, |
| 6724 | #[serde(default)] |
| 6725 | supported_features: Option<Vec<String>>, |
| 6726 | #[serde(default)] |
| 6727 | features: Option<Vec<String>>, |
| 6728 | #[serde(default)] |
| 6729 | architecture: Option<BasetenArchitecture>, |
| 6730 | #[serde(default)] |
| 6731 | input_modalities: Option<Vec<String>>, |
| 6732 | #[serde(default)] |
| 6733 | output_modalities: Option<Vec<String>>, |
| 6734 | #[serde(default)] |
| 6735 | reasoning: Option<bool>, |
| 6736 | #[serde(default)] |
| 6737 | supports_reasoning: Option<bool>, |
| 6738 | #[serde(default)] |
| 6739 | supports_tools: Option<bool>, |
| 6740 | #[serde(default)] |
| 6741 | supports_structured_output: Option<bool>, |
| 6742 | #[serde(default)] |
| 6743 | reasoning_options: Option<Vec<serde_json::Value>>, |
| 6744 | } |
| 6745 | |
| 6746 | #[derive(Debug, Deserialize)] |
| 6747 | #[serde(untagged)] |
| 6748 | enum CatalogNumber { |
| 6749 | Number(serde_json::Number), |
| 6750 | Text(String), |
| 6751 | } |
| 6752 | |
| 6753 | #[derive(Debug, Default, Deserialize)] |
| 6754 | struct BasetenLimits { |
| 6755 | #[serde(default)] |
| 6756 | context: Option<CatalogNumber>, |
| 6757 | #[serde(default)] |
| 6758 | output: Option<CatalogNumber>, |
| 6759 | } |
| 6760 | |
| 6761 | #[derive(Debug, Default, Deserialize)] |
| 6762 | struct BasetenTopProvider { |
| 6763 | #[serde(default)] |
| 6764 | context_length: Option<CatalogNumber>, |
| 6765 | #[serde(default)] |
| 6766 | max_completion_tokens: Option<CatalogNumber>, |
| 6767 | } |
| 6768 | |
| 6769 | #[derive(Debug, Default, Deserialize)] |
| 6770 | struct BasetenPricing { |
| 6771 | #[serde(default)] |
| 6772 | prompt: Option<CatalogNumber>, |
| 6773 | #[serde(default)] |
| 6774 | completion: Option<CatalogNumber>, |
| 6775 | #[serde(default)] |
| 6776 | input_cache_read: Option<CatalogNumber>, |
| 6777 | #[serde(default)] |
| 6778 | input_cache_write: Option<CatalogNumber>, |
| 6779 | } |
| 6780 | |
| 6781 | #[derive(Debug, Default, Deserialize)] |
| 6782 | struct BasetenArchitecture { |
| 6783 | #[serde(default)] |
| 6784 | input_modalities: Option<Vec<String>>, |
| 6785 | #[serde(default)] |
| 6786 | output_modalities: Option<Vec<String>>, |
| 6787 | } |
| 6788 | |
| 6789 | #[derive(Debug, Deserialize)] |
| 6790 | struct PrimeIntellectModelsResponse { |
| 6791 | data: Vec<Box<serde_json::value::RawValue>>, |
| 6792 | } |
| 6793 | |
| 6794 | #[derive(Debug, Deserialize)] |
| 6795 | struct PrimeIntellectModelItem { |
| 6796 | id: String, |
| 6797 | #[serde(default)] |
| 6798 | context_length: Option<CatalogNumber>, |
| 6799 | #[serde(default)] |
| 6800 | context_window: Option<CatalogNumber>, |
| 6801 | #[serde(default)] |
| 6802 | max_output_length: Option<CatalogNumber>, |
| 6803 | #[serde(default)] |
| 6804 | max_output_tokens: Option<CatalogNumber>, |
| 6805 | #[serde(default)] |
| 6806 | input_modalities: Option<Vec<String>>, |
| 6807 | #[serde(default)] |
| 6808 | output_modalities: Option<Vec<String>>, |
| 6809 | #[serde(default)] |
| 6810 | supported_parameters: Option<Vec<String>>, |
| 6811 | #[serde(default)] |
| 6812 | pricing: Option<PrimeIntellectPricing>, |
| 6813 | #[serde(default)] |
| 6814 | specs: Option<PrimeIntellectSpecs>, |
| 6815 | } |
| 6816 | |
| 6817 | #[derive(Debug, Default, Deserialize)] |
| 6818 | struct PrimeIntellectPricing { |
| 6819 | #[serde(default)] |
| 6820 | input_usd_per_mtok: Option<CatalogNumber>, |
| 6821 | #[serde(default)] |
| 6822 | output_usd_per_mtok: Option<CatalogNumber>, |
| 6823 | #[serde(default)] |
| 6824 | cache_read_usd_per_mtok: Option<CatalogNumber>, |
| 6825 | #[serde(default)] |
| 6826 | cache_write_usd_per_mtok: Option<CatalogNumber>, |
| 6827 | } |
| 6828 | |
| 6829 | #[derive(Debug, Default, Deserialize)] |
| 6830 | struct PrimeIntellectSpecs { |
| 6831 | #[serde(default)] |
| 6832 | context_window: Option<CatalogNumber>, |
| 6833 | #[serde(default)] |
| 6834 | max_output_tokens: Option<CatalogNumber>, |
| 6835 | #[serde(default)] |
| 6836 | modalities: Option<PrimeIntellectModalities>, |
| 6837 | #[serde(default)] |
| 6838 | supports_reasoning: Option<bool>, |
| 6839 | } |
| 6840 | |
| 6841 | #[derive(Debug, Default, Deserialize)] |
| 6842 | struct PrimeIntellectModalities { |
| 6843 | #[serde(default)] |
| 6844 | input: Option<Vec<String>>, |
| 6845 | #[serde(default)] |
| 6846 | output: Option<Vec<String>>, |
| 6847 | } |
| 6848 | |
| 6849 | fn parse_chatgpt_context_window_value(value: &Value) -> Option<u32> { |
| 6850 | let raw = value |
| 6851 | .as_u64() |
| 6852 | .or_else(|| value.as_str().and_then(|s| s.trim().parse::<u64>().ok()))?; |
| 6853 | u32::try_from(raw) |
| 6854 | .ok() |
| 6855 | .filter(|window| (1..=16_000_000).contains(window)) |
| 6856 | } |
| 6857 | |
| 6858 | fn parse_chatgpt_row_context_window(fields: &serde_json::Map<String, Value>) -> Option<u32> { |
| 6859 | if let Some(primary) = fields |
| 6860 | .get("context_window") |
| 6861 | .filter(|value| !value.is_null()) |
| 6862 | { |
| 6863 | return parse_chatgpt_context_window_value(primary); |
| 6864 | } |
| 6865 | ["max_context_tokens", "context_length"] |
| 6866 | .into_iter() |
| 6867 | .find_map(|key| fields.get(key).filter(|value| !value.is_null())) |
| 6868 | .and_then(parse_chatgpt_context_window_value) |
| 6869 | } |
| 6870 | |
| 6871 | fn parse_chatgpt_row_reasoning( |
| 6872 | fields: &serde_json::Map<String, Value>, |
| 6873 | ) -> (Option<bool>, Vec<String>) { |
| 6874 | let explicit_reasoning = fields.get("reasoning").and_then(Value::as_bool); |
| 6875 | let Some(levels_val) = fields |
| 6876 | .get("supported_reasoning_levels") |
| 6877 | .or_else(|| fields.get("reasoning_levels")) |
| 6878 | else { |
| 6879 | return (explicit_reasoning, Vec::new()); |
| 6880 | }; |
| 6881 | let Some(items) = levels_val.as_array() else { |
| 6882 | return (explicit_reasoning, Vec::new()); |
| 6883 | }; |
| 6884 | let mut efforts = Vec::new(); |
| 6885 | for item in items { |
| 6886 | let raw = item.as_str().or_else(|| { |
| 6887 | item.as_object().and_then(|map| { |
| 6888 | map.get("effort") |
| 6889 | .or_else(|| map.get("level")) |
| 6890 | .and_then(Value::as_str) |
| 6891 | }) |
| 6892 | }); |
| 6893 | let Some(raw) = raw else { |
| 6894 | continue; |
| 6895 | }; |
| 6896 | let Some(effort) = crate::reasoning_preference::ReasoningEffort::from_catalog_token(raw) |
| 6897 | else { |
| 6898 | continue; |
| 6899 | }; |
| 6900 | if matches!( |
| 6901 | effort, |
| 6902 | crate::reasoning_preference::ReasoningEffort::Off |
| 6903 | | crate::reasoning_preference::ReasoningEffort::Auto |
| 6904 | ) { |
| 6905 | continue; |
| 6906 | } |
| 6907 | let canonical = effort.as_setting().to_string(); |
| 6908 | if efforts.len() < 16 && !efforts.contains(&canonical) { |
| 6909 | efforts.push(canonical); |
| 6910 | } |
| 6911 | } |
| 6912 | let reasoning = explicit_reasoning.or(if !efforts.is_empty() { |
| 6913 | Some(true) |
| 6914 | } else if items.is_empty() { |
| 6915 | Some(false) |
| 6916 | } else { |
| 6917 | None |
| 6918 | }); |
| 6919 | (reasoning, efforts) |
| 6920 | } |
| 6921 | |
| 6922 | pub fn parse_models_response_for_provider( |
| 6923 | payload: &str, |
| 6924 | provider: ProviderKind, |
| 6925 | ) -> Result<Vec<AvailableModel>> { |
| 6926 | if provider != ProviderKind::OpenaiCodex { |
| 6927 | return parse_models_response(payload); |
| 6928 | } |
| 6929 | #[derive(Deserialize)] |
| 6930 | struct Roster { |
| 6931 | models: Vec<Row>, |
| 6932 | } |
| 6933 | #[derive(Deserialize)] |
| 6934 | struct Row { |
| 6935 | slug: String, |
| 6936 | display_name: String, |
| 6937 | visibility: String, |
| 6938 | #[serde(flatten)] |
| 6939 | fields: serde_json::Map<String, Value>, |
| 6940 | } |
| 6941 | let roster: Roster = serde_json::from_str(payload).context("Invalid ChatGPT model roster")?; |
| 6942 | anyhow::ensure!( |
| 6943 | roster.models.len() <= PROVIDER_CATALOG_MAX_ROWS, |
| 6944 | "ChatGPT model roster exceeds row limit" |
| 6945 | ); |
| 6946 | let mut seen = std::collections::HashSet::new(); |
| 6947 | let mut models = Vec::new(); |
| 6948 | let mut logged_missing_window = false; |
| 6949 | for row in roster.models { |
| 6950 | if row.visibility != "list" { |
| 6951 | continue; |
| 6952 | } |
| 6953 | anyhow::ensure!( |
| 6954 | codewhale_runtime::catalog_cache::valid_catalog_model_id(&row.slug) |
| 6955 | && !row.display_name.trim().is_empty() |
| 6956 | && row.display_name.len() <= 256 |
| 6957 | && !row.display_name.chars().any(char::is_control), |
| 6958 | "Invalid ChatGPT model row" |
| 6959 | ); |
| 6960 | if seen.insert(row.slug.clone()) { |
| 6961 | let context_window = parse_chatgpt_row_context_window(&row.fields); |
| 6962 | if !logged_missing_window && context_window.is_none() { |
| 6963 | logged_missing_window = true; |
| 6964 | let mut keys: Vec<&str> = vec!["display_name", "slug", "visibility"]; |
| 6965 | keys.extend(row.fields.keys().map(String::as_str)); |
| 6966 | keys.sort_unstable(); |
| 6967 | keys.dedup(); |
| 6968 | tracing::debug!( |
| 6969 | keys = ?keys, |
| 6970 | "ChatGPT visible model row omitted verified context_window" |
| 6971 | ); |
| 6972 | } |
| 6973 | let effective_context_window_percent = row |
| 6974 | .fields |
| 6975 | .get("effective_context_window_percent") |
| 6976 | .and_then(Value::as_u64) |
| 6977 | .and_then(|pct| u8::try_from(pct).ok()) |
| 6978 | .filter(|pct| (1..=100).contains(pct)); |
| 6979 | let (reasoning, efforts) = parse_chatgpt_row_reasoning(&row.fields); |
| 6980 | models.push(AvailableModel { |
| 6981 | id: row.slug, |
| 6982 | display_name: Some(row.display_name), |
| 6983 | owned_by: None, |
| 6984 | created: None, |
| 6985 | context_window, |
| 6986 | effective_context_window_percent, |
| 6987 | reasoning, |
| 6988 | efforts, |
| 6989 | }); |
| 6990 | } |
| 6991 | } |
| 6992 | Ok(models) |
| 6993 | } |
| 6994 | |
| 6995 | pub fn parse_models_response(payload: &str) -> Result<Vec<AvailableModel>> { |
| 6996 | let parsed: ModelsListResponse = |
| 6997 | serde_json::from_str(payload).context("Failed to parse model list JSON")?; |
| 6998 | |
| 6999 | let mut models = parsed |
| 7000 | .data |
| 7001 | .into_iter() |
| 7002 | .map(|item| AvailableModel { |
| 7003 | id: item.id, |
| 7004 | owned_by: item.owned_by, |
| 7005 | created: item.created, |
| 7006 | display_name: None, |
| 7007 | context_window: None, |
| 7008 | effective_context_window_percent: None, |
| 7009 | reasoning: None, |
| 7010 | efforts: Vec::new(), |
| 7011 | }) |
| 7012 | .collect::<Vec<_>>(); |
| 7013 | models.sort_by(|a, b| a.id.cmp(&b.id)); |
| 7014 | models.dedup_by(|a, b| a.id == b.id); |
| 7015 | Ok(models) |
| 7016 | } |
| 7017 | |
| 7018 | fn is_stepfun_non_chat_media_model(model_id: &str) -> bool { |
| 7019 | let lower = model_id.trim().to_ascii_lowercase(); |
| 7020 | lower.starts_with("step-tts-") |
| 7021 | || lower.starts_with("stepaudio-") |
| 7022 | || lower.starts_with("step-audio-") |
| 7023 | || lower.starts_with("step-1x-") |
| 7024 | || lower.starts_with("step-2x-") |
| 7025 | || lower.starts_with("step-image-") |
| 7026 | || lower.ends_with("-tts") |
| 7027 | || lower.ends_with("-asr") |
| 7028 | || lower.ends_with("-image") |
| 7029 | || lower.ends_with("-video") |
| 7030 | } |
| 7031 | |
| 7032 | /// Keep both live-model consumers on each provider's documented coding roster. |
| 7033 | /// Unknown models remain hidden until their wire contract is known. |
| 7034 | fn apply_provider_model_cutline( |
| 7035 | provider: ProviderKind, |
| 7036 | models: Vec<AvailableModel>, |
| 7037 | ) -> Vec<AvailableModel> { |
| 7038 | if provider == ProviderKind::Stepfun { |
| 7039 | return models |
| 7040 | .into_iter() |
| 7041 | .filter(|model| { |
| 7042 | if let Some(row) = crate::provider_lake::catalog_offering_for_model( |
| 7043 | ProviderKind::Stepfun, |
| 7044 | &model.id, |
| 7045 | ) { |
| 7046 | row.tool_call == Some(true) |
| 7047 | } else { |
| 7048 | !is_stepfun_non_chat_media_model(&model.id) |
| 7049 | } |
| 7050 | }) |
| 7051 | .collect(); |
| 7052 | } |
| 7053 | if provider != ProviderKind::OpencodeGo { |
| 7054 | return models; |
| 7055 | } |
| 7056 | |
| 7057 | let mut models: Vec<_> = models |
| 7058 | .into_iter() |
| 7059 | .filter_map(|mut model| { |
| 7060 | let canonical = codewhale_runtime::config::opencode_go_model_id(&model.id)?; |
| 7061 | model.id = canonical.to_string(); |
| 7062 | Some(model) |
| 7063 | }) |
| 7064 | .collect(); |
| 7065 | models.sort_by(|left, right| left.id.cmp(&right.id)); |
| 7066 | models.dedup_by(|left, right| left.id == right.id); |
| 7067 | models |
| 7068 | } |
| 7069 | |
| 7070 | fn codewhale_row_pricing_to_cost( |
| 7071 | pricing: &serde_json::Value, |
| 7072 | fetched_at: u64, |
| 7073 | ) -> Option<codewhale_config::models_dev::ModelsDevCost> { |
| 7074 | let obj = pricing.as_object()?; |
| 7075 | let currency = obj.get("currency")?.as_str()?.trim(); |
| 7076 | if !currency.eq_ignore_ascii_case("USD") { |
| 7077 | return None; |
| 7078 | } |
| 7079 | if let Some(raw_expires) = obj.get("expiresAt").filter(|value| !value.is_null()) { |
| 7080 | let expires_str = raw_expires.as_str()?; |
| 7081 | let expires_unix = codewhale_config::cloud_facts::verify::parse_rfc3339_utc(expires_str)?; |
| 7082 | let reference_unix = if fetched_at > 0 { |
| 7083 | fetched_at |
| 7084 | } else { |
| 7085 | now_unix() |
| 7086 | }; |
| 7087 | if expires_unix <= reference_unix { |
| 7088 | return None; |
| 7089 | } |
| 7090 | } |
| 7091 | let rates = obj.get("ratesMicrosPerMillion")?.as_object()?; |
| 7092 | let parse_micros = |field: &str| -> Option<Option<f64>> { |
| 7093 | let Some(raw) = rates.get(field).filter(|value| !value.is_null()) else { |
| 7094 | return Some(None); |
| 7095 | }; |
| 7096 | let micros = raw |
| 7097 | .as_f64() |
| 7098 | .filter(|value| value.is_finite() && *value >= 0.0)?; |
| 7099 | let usd_per_million = micros / 1_000_000.0; |
| 7100 | usd_per_million.is_finite().then_some(Some(usd_per_million)) |
| 7101 | }; |
| 7102 | let input = parse_micros("input")??; |
| 7103 | let output = parse_micros("output")??; |
| 7104 | let cached_input = parse_micros("cachedInput")?; |
| 7105 | let cache_read_alias = parse_micros("cacheRead")?; |
| 7106 | let cache_read = match (cached_input, cache_read_alias) { |
| 7107 | (Some(a), Some(b)) if a != b => return None, |
| 7108 | (Some(a), _) => Some(a), |
| 7109 | (None, b) => b, |
| 7110 | }; |
| 7111 | let cache_write = parse_micros("cacheWrite")?; |
| 7112 | let cost = codewhale_config::models_dev::ModelsDevCost { |
| 7113 | input: Some(input), |
| 7114 | output: Some(output), |
| 7115 | cache_read, |
| 7116 | cache_write, |
| 7117 | ..Default::default() |
| 7118 | }; |
| 7119 | codewhale_config::pricing::catalog_cost_is_valid(&cost).then_some(cost) |
| 7120 | } |
| 7121 | |
| 7122 | /// Convert a named gateway's `/models` response into truthful provider-scoped |
| 7123 | /// catalog rows. Matching model ids on other providers prove no capabilities, |
| 7124 | /// limits, or prices; only an explicit same-provider bundled row may enrich a |
| 7125 | /// live offering. |
| 7126 | /// Parse the Codewhale API's authenticated `GET {base}/models` listing. |
| 7127 | /// |
| 7128 | /// The account control plane returns the OpenAI list shape, but every row |
| 7129 | /// carries a `codewhale` block naming the wire protocol Codewhale will use for |
| 7130 | /// that model (`chat-completions` → `{base}/chat/completions`, |
| 7131 | /// `anthropic-messages` → `{base}/messages`, `responses` → |
| 7132 | /// `{base}/responses`). That block is the whole reason this route is |
| 7133 | /// model-aware, so the protocol is read from the response rather |
| 7134 | /// than inferred — the namespace inference in |
| 7135 | /// [`codewhale_config::route::codewhale_endpoint_key_for_model`] is only the |
| 7136 | /// offline fallback for a row this listing did not describe. |
| 7137 | /// |
| 7138 | /// The listing is untrusted remote data: unusable rows are dropped rather than |
| 7139 | /// failing the refresh, and nothing here claims capabilities, limits, or |
| 7140 | /// pricing the account service did not state. |
| 7141 | fn codewhale_catalog_offerings_from_body( |
| 7142 | body: &str, |
| 7143 | provider: &str, |
| 7144 | fingerprint: &str, |
| 7145 | fetched_at: u64, |
| 7146 | ) -> Result<Vec<CatalogOffering>, CatalogRefreshError> { |
| 7147 | #[derive(serde::Deserialize)] |
| 7148 | struct Listing { |
| 7149 | data: Vec<Row>, |
| 7150 | } |
| 7151 | #[derive(serde::Deserialize)] |
| 7152 | struct Row { |
| 7153 | #[serde(default)] |
| 7154 | id: String, |
| 7155 | #[serde(default)] |
| 7156 | codewhale: Option<RowMeta>, |
| 7157 | #[serde(flatten)] |
| 7158 | capabilities: ListedCapabilitiesFields, |
| 7159 | } |
| 7160 | #[derive(serde::Deserialize)] |
| 7161 | struct RowMeta { |
| 7162 | #[serde(default)] |
| 7163 | protocol: Option<String>, |
| 7164 | #[serde(default)] |
| 7165 | default: bool, |
| 7166 | #[serde(default)] |
| 7167 | limits: Option<RowLimits>, |
| 7168 | #[serde(default)] |
| 7169 | pricing: Option<serde_json::Value>, |
| 7170 | #[serde(default)] |
| 7171 | reasoning: Option<bool>, |
| 7172 | #[serde(default)] |
| 7173 | tool_call: Option<bool>, |
| 7174 | #[serde(default)] |
| 7175 | supports_tools: Option<bool>, |
| 7176 | #[serde(default)] |
| 7177 | structured_output: Option<bool>, |
| 7178 | #[serde(default)] |
| 7179 | supports_structured_output: Option<bool>, |
| 7180 | #[serde(default)] |
| 7181 | reasoning_options: Option<Vec<Value>>, |
| 7182 | #[serde(default)] |
| 7183 | supported_reasoning_levels: Option<Value>, |
| 7184 | #[serde(default)] |
| 7185 | default_reasoning_level: Option<String>, |
| 7186 | #[serde(default)] |
| 7187 | capabilities: Option<ListedCapabilitiesBlock>, |
| 7188 | } |
| 7189 | #[derive(serde::Deserialize)] |
| 7190 | struct RowLimits { |
| 7191 | #[serde(default, rename = "maxInputTokens")] |
| 7192 | max_input_tokens: Option<u64>, |
| 7193 | #[serde(default, rename = "maxOutputTokens")] |
| 7194 | max_output_tokens: Option<u64>, |
| 7195 | #[serde(default, rename = "maxContextTokens")] |
| 7196 | max_context_tokens: Option<u64>, |
| 7197 | } |
| 7198 | |
| 7199 | let listing: Listing = |
| 7200 | serde_json::from_str(body).map_err(|_| CatalogRefreshError::InvalidResponse)?; |
| 7201 | let listed = listing.data.len(); |
| 7202 | let mut offerings: Vec<CatalogOffering> = Vec::with_capacity(listed); |
| 7203 | let mut seen: std::collections::BTreeSet<String> = std::collections::BTreeSet::new(); |
| 7204 | for row in listing.data { |
| 7205 | let id = row.id.trim().to_string(); |
| 7206 | if id.is_empty() || !seen.insert(id.clone()) { |
| 7207 | continue; |
| 7208 | } |
| 7209 | // An unstated or unknown protocol falls back to the namespace rule |
| 7210 | // rather than being dropped: the account already proved it serves this |
| 7211 | // model by listing it, and a protocol label this build predates must |
| 7212 | // not make the row unreachable. |
| 7213 | let endpoint_key = match row |
| 7214 | .codewhale |
| 7215 | .as_ref() |
| 7216 | .and_then(|meta| meta.protocol.as_deref()) |
| 7217 | .map(str::trim) |
| 7218 | { |
| 7219 | Some("anthropic-messages") => "messages", |
| 7220 | Some("chat-completions") => "chat", |
| 7221 | Some("responses") => "responses", |
| 7222 | _ => codewhale_config::route::codewhale_endpoint_key_for_model(&id), |
| 7223 | }; |
| 7224 | let limit = row |
| 7225 | .codewhale |
| 7226 | .as_ref() |
| 7227 | .and_then(|meta| meta.limits.as_ref()) |
| 7228 | .map(|limits| codewhale_config::models_dev::ModelsDevLimit { |
| 7229 | context: limits.max_context_tokens.filter(|tokens| *tokens > 0), |
| 7230 | input: limits.max_input_tokens.filter(|tokens| *tokens > 0), |
| 7231 | output: limits.max_output_tokens.filter(|tokens| *tokens > 0), |
| 7232 | }) |
| 7233 | .filter(|limit| *limit != codewhale_config::models_dev::ModelsDevLimit::default()); |
| 7234 | let cost = row |
| 7235 | .codewhale |
| 7236 | .as_ref() |
| 7237 | .and_then(|meta| meta.pricing.as_ref()) |
| 7238 | .and_then(|pricing| codewhale_row_pricing_to_cost(pricing, fetched_at)); |
| 7239 | let top_caps = extract_row_capabilities(&row.capabilities); |
| 7240 | let meta = row.codewhale.as_ref(); |
| 7241 | let meta_options = meta.and_then(|meta| { |
| 7242 | if let Some(options) = meta.reasoning_options.as_ref() { |
| 7243 | Some(options.clone()) |
| 7244 | } else if let Some(levels) = meta.supported_reasoning_levels.as_ref() { |
| 7245 | reasoning_options_from_levels(levels, meta.default_reasoning_level.as_deref()) |
| 7246 | } else { |
| 7247 | meta.capabilities |
| 7248 | .as_ref() |
| 7249 | .and_then(|caps| caps.effort.as_ref()) |
| 7250 | .and_then(reasoning_options_from_capabilities_effort) |
| 7251 | } |
| 7252 | }); |
| 7253 | let (reasoning_options, reasoning_options_present) = if let Some(options) = meta_options { |
| 7254 | (options, true) |
| 7255 | } else { |
| 7256 | ( |
| 7257 | top_caps.reasoning_options, |
| 7258 | top_caps.reasoning_options_present, |
| 7259 | ) |
| 7260 | }; |
| 7261 | let reasoning = meta |
| 7262 | .and_then(|meta| { |
| 7263 | meta.reasoning.or_else(|| { |
| 7264 | meta.capabilities.as_ref().and_then(|caps| { |
| 7265 | caps.reasoning |
| 7266 | .as_ref() |
| 7267 | .and_then(value_supported_flag) |
| 7268 | .or_else(|| caps.thinking.as_ref().and_then(value_supported_flag)) |
| 7269 | }) |
| 7270 | }) |
| 7271 | }) |
| 7272 | .or(top_caps.reasoning) |
| 7273 | .or_else(|| (!reasoning_options.is_empty()).then_some(true)); |
| 7274 | let tool_call = meta |
| 7275 | .and_then(|meta| { |
| 7276 | meta.tool_call.or(meta.supports_tools).or_else(|| { |
| 7277 | meta.capabilities.as_ref().and_then(|caps| { |
| 7278 | caps.function_calling |
| 7279 | .as_ref() |
| 7280 | .and_then(value_supported_flag) |
| 7281 | .or_else(|| caps.tools.as_ref().and_then(value_supported_flag)) |
| 7282 | }) |
| 7283 | }) |
| 7284 | }) |
| 7285 | .or(top_caps.tool_call); |
| 7286 | let structured_output = meta |
| 7287 | .and_then(|meta| meta.structured_output.or(meta.supports_structured_output)) |
| 7288 | .or(top_caps.structured_output); |
| 7289 | offerings.push(CatalogOffering { |
| 7290 | cost_source: None, |
| 7291 | modalities_source: None, |
| 7292 | provider: provider.to_string(), |
| 7293 | wire_model_id: id, |
| 7294 | canonical_model: None, |
| 7295 | endpoint_key: endpoint_key.to_string(), |
| 7296 | default_for_provider: row.codewhale.is_some_and(|meta| meta.default), |
| 7297 | family: None, |
| 7298 | limit, |
| 7299 | cost, |
| 7300 | modalities: None, |
| 7301 | attachment: None, |
| 7302 | reasoning, |
| 7303 | tool_call, |
| 7304 | structured_output, |
| 7305 | reasoning_options, |
| 7306 | reasoning_options_present, |
| 7307 | source: CatalogSource::Live { |
| 7308 | base_url_fingerprint: fingerprint.to_string(), |
| 7309 | fetched_at, |
| 7310 | }, |
| 7311 | ..Default::default() |
| 7312 | }); |
| 7313 | } |
| 7314 | if listed > 0 && offerings.is_empty() { |
| 7315 | return Err(CatalogRefreshError::InvalidResponse); |
| 7316 | } |
| 7317 | Ok(offerings) |
| 7318 | } |
| 7319 | |
| 7320 | /// Whether a route speaks Baseten's `/models` dialect: recognized by |
| 7321 | /// endpoint, never by table name (#6289). |
| 7322 | fn catalog_endpoint_is_baseten(api_provider: ProviderKind, base_url: &str) -> bool { |
| 7323 | api_provider == ProviderKind::Custom && codewhale_config::catalog::endpoint_is_baseten(base_url) |
| 7324 | } |
| 7325 | |
| 7326 | fn catalog_endpoint_is_prime_intellect(api_provider: ProviderKind, base_url: &str) -> bool { |
| 7327 | api_provider == ProviderKind::Custom |
| 7328 | && codewhale_config::catalog::endpoint_is_prime_intellect(base_url) |
| 7329 | } |
| 7330 | |
| 7331 | /// Project one `/models` document onto a secret-free, endpoint-scoped roster |
| 7332 | /// delta (#3385). Shared by [`CodewhaleClient::fetch_catalog_delta`] and the |
| 7333 | /// guided-setup key probe ([`verify_provider_api_key`]), so the listing a key |
| 7334 | /// check already downloaded is read by exactly the rules a refresh uses. |
| 7335 | fn catalog_delta_from_models_body( |
| 7336 | api_provider: ProviderKind, |
| 7337 | provider: String, |
| 7338 | base_url: &str, |
| 7339 | body: &str, |
| 7340 | model_bound_secret_values: &[String], |
| 7341 | ) -> Result<ProviderCatalogDelta, CatalogRefreshError> { |
| 7342 | let fingerprint = base_url_fingerprint(base_url); |
| 7343 | let fetched_at = now_unix(); |
| 7344 | |
| 7345 | // OpenRouter returns extended capability metadata in its /models |
| 7346 | // response (#3385). Capture limits, pricing, reasoning, and modalities |
| 7347 | // from the live API instead of leaving them unknown. |
| 7348 | let mut offerings: Vec<CatalogOffering> = if api_provider == ProviderKind::OpencodeGo |
| 7349 | && let Some(typed) = opencode_catalog::parse( |
| 7350 | body, |
| 7351 | &provider, |
| 7352 | base_url, |
| 7353 | &fingerprint, |
| 7354 | fetched_at, |
| 7355 | model_bound_secret_values, |
| 7356 | )? { |
| 7357 | typed |
| 7358 | } else if api_provider == ProviderKind::Orcarouter { |
| 7359 | // OrcaRouter serves the extended capability shape too, and adds |
| 7360 | // `supported_endpoint_types` on every row. That field is what keeps a |
| 7361 | // gateway model list — which mixes chat with image/video generation — |
| 7362 | // from dumping non-text rows into the text selector. A row that does |
| 7363 | // not advertise the Chat Completions dialect this route speaks is |
| 7364 | // dropped here, so the roster the picker and `/model` read is |
| 7365 | // servable chat only. |
| 7366 | let listed = parse_orcarouter_models_response(body)?; |
| 7367 | let chat_rows: Vec<_> = listed |
| 7368 | .iter() |
| 7369 | .filter(|item| orcarouter_row_is_chat(item)) |
| 7370 | .collect(); |
| 7371 | let non_chat = listed.len() - chat_rows.len(); |
| 7372 | if non_chat > 0 { |
| 7373 | tracing::info!( |
| 7374 | dropped = non_chat, |
| 7375 | listed = listed.len(), |
| 7376 | "OrcaRouter catalog refresh kept chat rows and dropped non-chat dialects" |
| 7377 | ); |
| 7378 | } |
| 7379 | let offerings: Vec<_> = chat_rows |
| 7380 | .iter() |
| 7381 | .filter_map(|item| { |
| 7382 | orcarouter_to_catalog_offering(item, &provider, &fingerprint, fetched_at).ok() |
| 7383 | }) |
| 7384 | .collect(); |
| 7385 | if offerings.is_empty() && !listed.is_empty() { |
| 7386 | return Err(CatalogRefreshError::InvalidResponse); |
| 7387 | } |
| 7388 | offerings |
| 7389 | } else if api_provider == ProviderKind::Openrouter { |
| 7390 | let or_models = parse_openrouter_models_response(body)?; |
| 7391 | // A row with an unreadable or implausible price is skipped and |
| 7392 | // counted, not allowed to fail every other row (#6690). |
| 7393 | let offerings: Vec<_> = or_models |
| 7394 | .iter() |
| 7395 | .filter_map(|item| { |
| 7396 | openrouter_to_catalog_offering(item, &provider, &fingerprint, fetched_at).ok() |
| 7397 | }) |
| 7398 | .collect(); |
| 7399 | let skipped = or_models.len() - offerings.len(); |
| 7400 | if skipped > 0 { |
| 7401 | tracing::warn!( |
| 7402 | skipped, |
| 7403 | listed = or_models.len(), |
| 7404 | "skipped OpenRouter model rows with invalid pricing" |
| 7405 | ); |
| 7406 | } |
| 7407 | if offerings.is_empty() && !or_models.is_empty() { |
| 7408 | return Err(CatalogRefreshError::InvalidResponse); |
| 7409 | } |
| 7410 | offerings |
| 7411 | } else if catalog_endpoint_is_baseten(api_provider, base_url) { |
| 7412 | let baseten_models = parse_baseten_models_response(body)?; |
| 7413 | baseten_models |
| 7414 | .iter() |
| 7415 | .map(|item| baseten_to_catalog_offering(item, &provider, &fingerprint, fetched_at)) |
| 7416 | .collect::<Result<Vec<_>, _>>()? |
| 7417 | } else if catalog_endpoint_is_prime_intellect(api_provider, base_url) { |
| 7418 | let listed = parse_prime_intellect_models_response(body)?; |
| 7419 | let chat_rows: Vec<_> = listed |
| 7420 | .iter() |
| 7421 | .filter(|item| prime_intellect_row_is_chat(item)) |
| 7422 | .collect(); |
| 7423 | let non_chat = listed.len() - chat_rows.len(); |
| 7424 | if non_chat > 0 { |
| 7425 | tracing::info!( |
| 7426 | dropped = non_chat, |
| 7427 | listed = listed.len(), |
| 7428 | "Prime Intellect catalog refresh kept chat rows and dropped non-chat modalities" |
| 7429 | ); |
| 7430 | } |
| 7431 | let offerings: Vec<_> = chat_rows |
| 7432 | .iter() |
| 7433 | .map(|item| { |
| 7434 | prime_intellect_to_catalog_offering(item, &provider, &fingerprint, fetched_at) |
| 7435 | }) |
| 7436 | .collect(); |
| 7437 | if offerings.is_empty() && !listed.is_empty() { |
| 7438 | return Err(CatalogRefreshError::InvalidResponse); |
| 7439 | } |
| 7440 | offerings |
| 7441 | } else if provider == "codewhale" { |
| 7442 | // The Codewhale API's own listing states the wire protocol per |
| 7443 | // model, so it is the catalog authority for this route. |
| 7444 | codewhale_catalog_offerings_from_body(body, &provider, &fingerprint, fetched_at)? |
| 7445 | } else { |
| 7446 | let mut listed_limits = listed_limits_by_model_id(body); |
| 7447 | let mut listed_caps = listed_capabilities_by_model_id(body); |
| 7448 | let listed_efforts = if api_provider == ProviderKind::Deepseek |
| 7449 | && codewhale_config::provider_base_url_is_official(api_provider, base_url) |
| 7450 | { |
| 7451 | listed_deepseek_efforts_by_model_id(body)? |
| 7452 | } else { |
| 7453 | std::collections::BTreeMap::new() |
| 7454 | }; |
| 7455 | let models = apply_provider_model_cutline( |
| 7456 | api_provider, |
| 7457 | parse_models_response_for_provider(body, api_provider) |
| 7458 | .map_err(|_| CatalogRefreshError::InvalidResponse)?, |
| 7459 | ); |
| 7460 | // OpenCode Go's cutline rewrites a listed id to its canonical spelling. |
| 7461 | // Key the limits map the same way so a row keeps the numbers the |
| 7462 | // provider stated for it. |
| 7463 | if api_provider == ProviderKind::OpencodeGo { |
| 7464 | listed_limits = listed_limits |
| 7465 | .into_iter() |
| 7466 | .map(|(id, limit)| { |
| 7467 | let canonical = codewhale_runtime::config::opencode_go_model_id(&id) |
| 7468 | .map_or_else(|| id.clone(), str::to_string); |
| 7469 | (canonical, limit) |
| 7470 | }) |
| 7471 | .collect(); |
| 7472 | listed_caps = listed_caps |
| 7473 | .into_iter() |
| 7474 | .map(|(id, caps)| { |
| 7475 | let canonical = codewhale_runtime::config::opencode_go_model_id(&id) |
| 7476 | .map_or_else(|| id.clone(), str::to_string); |
| 7477 | (canonical, caps) |
| 7478 | }) |
| 7479 | .collect(); |
| 7480 | } |
| 7481 | models |
| 7482 | .into_iter() |
| 7483 | .map(|model| { |
| 7484 | let caps = listed_caps.remove(&model.id); |
| 7485 | let deepseek_options = listed_efforts.get(&model.id); |
| 7486 | let (reasoning_options, reasoning_options_present) = |
| 7487 | if let Some(options) = deepseek_options { |
| 7488 | (options.clone(), true) |
| 7489 | } else if let Some(caps) = caps.as_ref() |
| 7490 | && caps.reasoning_options_present |
| 7491 | { |
| 7492 | (caps.reasoning_options.clone(), true) |
| 7493 | } else { |
| 7494 | (Vec::new(), false) |
| 7495 | }; |
| 7496 | CatalogOffering { |
| 7497 | cost_source: None, |
| 7498 | modalities_source: None, |
| 7499 | provider: provider.clone(), |
| 7500 | endpoint_key: if api_provider == ProviderKind::OpencodeGo { |
| 7501 | codewhale_config::opencode_go_endpoint_key(&model.id) |
| 7502 | .expect("filtered Go roster") |
| 7503 | } else { |
| 7504 | "chat" |
| 7505 | } |
| 7506 | .to_string(), |
| 7507 | limit: listed_limits.get(&model.id).cloned(), |
| 7508 | wire_model_id: model.id, |
| 7509 | canonical_model: None, |
| 7510 | default_for_provider: false, |
| 7511 | family: None, |
| 7512 | cost: None, |
| 7513 | model_type: caps.as_ref().and_then(|caps| caps.model_type.clone()), |
| 7514 | status: caps.as_ref().and_then(|caps| caps.status.clone()), |
| 7515 | modalities: caps.as_ref().and_then(|caps| caps.modalities.clone()), |
| 7516 | attachment: None, |
| 7517 | reasoning: caps.as_ref().and_then(|caps| caps.reasoning), |
| 7518 | tool_call: caps.as_ref().and_then(|caps| caps.tool_call), |
| 7519 | structured_output: caps.as_ref().and_then(|caps| caps.structured_output), |
| 7520 | reasoning_options, |
| 7521 | reasoning_options_present, |
| 7522 | source: CatalogSource::Live { |
| 7523 | base_url_fingerprint: fingerprint.clone(), |
| 7524 | fetched_at, |
| 7525 | }, |
| 7526 | ..Default::default() |
| 7527 | } |
| 7528 | }) |
| 7529 | .collect() |
| 7530 | }; |
| 7531 | if !offerings.iter().any(|row| row.default_for_provider) { |
| 7532 | let listed: Vec<&str> = offerings |
| 7533 | .iter() |
| 7534 | .map(|row| row.wire_model_id.as_str()) |
| 7535 | .collect(); |
| 7536 | let identified = codewhale_config::catalog::identify_listed_default( |
| 7537 | &provider, |
| 7538 | api_provider.provider().default_model(), |
| 7539 | &listed, |
| 7540 | ); |
| 7541 | if listed.iter().any(|id| id.eq_ignore_ascii_case(&identified)) { |
| 7542 | for row in &mut offerings { |
| 7543 | row.default_for_provider = row.wire_model_id.eq_ignore_ascii_case(&identified); |
| 7544 | } |
| 7545 | } |
| 7546 | } |
| 7547 | |
| 7548 | if offerings.iter().any(|row| { |
| 7549 | let extra_text = [row.model_type.as_deref(), row.status.as_deref()] |
| 7550 | .into_iter() |
| 7551 | .flatten() |
| 7552 | .chain(row.modalities.as_ref().into_iter().flat_map(|modalities| { |
| 7553 | modalities |
| 7554 | .input |
| 7555 | .iter() |
| 7556 | .chain(&modalities.output) |
| 7557 | .map(String::as_str) |
| 7558 | })); |
| 7559 | model_bound_secret_values.iter().any(|secret| { |
| 7560 | !secret.is_empty() |
| 7561 | && (row.wire_model_id.contains(secret) |
| 7562 | || extra_text.clone().any(|text| text.contains(secret)) |
| 7563 | || (api_provider == ProviderKind::OpencodeGo |
| 7564 | && [row.provider_api.as_deref(), row.name.as_deref()] |
| 7565 | .into_iter() |
| 7566 | .flatten() |
| 7567 | .any(|text| text.contains(secret)))) |
| 7568 | }) |
| 7569 | }) { |
| 7570 | return Err(CatalogRefreshError::InvalidResponse); |
| 7571 | } |
| 7572 | if offerings.len() > PROVIDER_CATALOG_MAX_ROWS { |
| 7573 | return Err(CatalogRefreshError::InvalidResponse); |
| 7574 | } |
| 7575 | Ok(ProviderCatalogDelta { |
| 7576 | provider, |
| 7577 | base_url_fingerprint: fingerprint, |
| 7578 | fetched_at, |
| 7579 | offerings, |
| 7580 | }) |
| 7581 | } |
| 7582 | |
| 7583 | /// Parse an OpenRouter `/models` response, preserving server-side ordering and |
| 7584 | /// capturing full capability metadata (#3385). |
| 7585 | fn parse_openrouter_models_response( |
| 7586 | payload: &str, |
| 7587 | ) -> Result<Vec<OpenRouterModelItem>, CatalogRefreshError> { |
| 7588 | let parsed: OpenRouterModelsResponse = |
| 7589 | serde_json::from_str(payload).map_err(|_| CatalogRefreshError::InvalidResponse)?; |
| 7590 | let listed = parsed.data.len(); |
| 7591 | let mut seen = std::collections::HashSet::new(); |
| 7592 | let mut malformed = 0usize; |
| 7593 | let mut models = Vec::with_capacity(listed); |
| 7594 | for row in parsed.data { |
| 7595 | // `~`-prefixed ids (`~deepseek/deepseek-pro-latest`) are OpenRouter's |
| 7596 | // moving "latest" aliases, not billing identities, so they are dropped |
| 7597 | // silently. Any other row that does not decode or carries an id the |
| 7598 | // catalog cannot hold is skipped and counted: one such row used to |
| 7599 | // fail the whole roster closed, so no OpenRouter route could ever be |
| 7600 | // priced from the lake (#6690). |
| 7601 | let Ok(item) = serde_json::from_str::<OpenRouterModelItem>(row.get()) else { |
| 7602 | malformed += 1; |
| 7603 | continue; |
| 7604 | }; |
| 7605 | if item.id.starts_with('~') { |
| 7606 | continue; |
| 7607 | } |
| 7608 | if !codewhale_runtime::catalog_cache::valid_catalog_model_id(&item.id) { |
| 7609 | malformed += 1; |
| 7610 | continue; |
| 7611 | } |
| 7612 | if seen.insert(item.id.clone()) { |
| 7613 | models.push(item); |
| 7614 | } |
| 7615 | } |
| 7616 | if malformed > 0 { |
| 7617 | tracing::warn!( |
| 7618 | malformed, |
| 7619 | listed, |
| 7620 | "skipped malformed OpenRouter model rows in the catalog refresh" |
| 7621 | ); |
| 7622 | } |
| 7623 | // Rows were listed but not one survived: the response is not a roster. |
| 7624 | if models.is_empty() && malformed > 0 { |
| 7625 | return Err(CatalogRefreshError::InvalidResponse); |
| 7626 | } |
| 7627 | Ok(models) |
| 7628 | } |
| 7629 | |
| 7630 | /// Endpoint dialects that mean "a chat/completions text turn can be served". |
| 7631 | /// |
| 7632 | /// OrcaRouter publishes `supported_endpoint_types`, and this route speaks only |
| 7633 | /// Chat Completions, which it advertises as `openai`. A row offered only on |
| 7634 | /// another dialect (`anthropic`, `gemini`, `openai-response`) or on a non-chat |
| 7635 | /// one (`image-generation`, `openai-video`, `jina-rerank`, `embeddings`) is |
| 7636 | /// kept out of the chat selector. |
| 7637 | const ORCAROUTER_CHAT_ENDPOINT_TYPES: &[&str] = &["openai"]; |
| 7638 | |
| 7639 | /// Whether an OrcaRouter row is offered on a chat/completions dialect. |
| 7640 | /// |
| 7641 | /// Fail-closed on silence: a row that declares no `supported_endpoint_types` |
| 7642 | /// is **not** assumed to be chat. On a gateway that mixes chat with image and |
| 7643 | /// video generation, guessing by omission would put a generation model in the |
| 7644 | /// text selector. |
| 7645 | fn orcarouter_row_is_chat(item: &OpenRouterModelItem) -> bool { |
| 7646 | item.supported_endpoint_types.as_ref().is_some_and(|types| { |
| 7647 | types.iter().any(|endpoint| { |
| 7648 | let endpoint = endpoint.trim(); |
| 7649 | ORCAROUTER_CHAT_ENDPOINT_TYPES |
| 7650 | .iter() |
| 7651 | .any(|chat| endpoint.eq_ignore_ascii_case(chat)) |
| 7652 | }) |
| 7653 | }) |
| 7654 | } |
| 7655 | |
| 7656 | /// Parse OrcaRouter's `/v1/models` body. |
| 7657 | /// |
| 7658 | /// The gateway serves the OpenRouter extended shape: every row carries |
| 7659 | /// `supported_endpoint_types`, and text models add `architecture`, |
| 7660 | /// `context_length`, `top_provider` and `pricing`. Rows are accepted or |
| 7661 | /// skipped by the same id rules as [`parse_openrouter_models_response`], so one |
| 7662 | /// malformed row cannot fail the whole roster. |
| 7663 | fn parse_orcarouter_models_response( |
| 7664 | payload: &str, |
| 7665 | ) -> Result<Vec<OpenRouterModelItem>, CatalogRefreshError> { |
| 7666 | let parsed: OpenRouterModelsResponse = |
| 7667 | serde_json::from_str(payload).map_err(|_| CatalogRefreshError::InvalidResponse)?; |
| 7668 | let listed = parsed.data.len(); |
| 7669 | let mut seen = std::collections::HashSet::new(); |
| 7670 | let mut malformed = 0usize; |
| 7671 | let mut models = Vec::with_capacity(listed); |
| 7672 | for row in parsed.data { |
| 7673 | let Ok(item) = serde_json::from_str::<OpenRouterModelItem>(row.get()) else { |
| 7674 | malformed += 1; |
| 7675 | continue; |
| 7676 | }; |
| 7677 | if item.id.starts_with('~') { |
| 7678 | continue; |
| 7679 | } |
| 7680 | if !codewhale_runtime::catalog_cache::valid_catalog_model_id(&item.id) { |
| 7681 | malformed += 1; |
| 7682 | continue; |
| 7683 | } |
| 7684 | if seen.insert(item.id.clone()) { |
| 7685 | models.push(item); |
| 7686 | } |
| 7687 | } |
| 7688 | if malformed > 0 { |
| 7689 | tracing::warn!( |
| 7690 | malformed, |
| 7691 | listed, |
| 7692 | "skipped malformed OrcaRouter model rows in the catalog refresh" |
| 7693 | ); |
| 7694 | } |
| 7695 | if models.is_empty() && malformed > 0 { |
| 7696 | return Err(CatalogRefreshError::InvalidResponse); |
| 7697 | } |
| 7698 | Ok(models) |
| 7699 | } |
| 7700 | |
| 7701 | /// Project one OrcaRouter `/v1/models` row onto a catalog offering. |
| 7702 | /// |
| 7703 | /// Pricing and limits reuse the OpenRouter projection (OrcaRouter bills the |
| 7704 | /// same extended fields). Three differences matter: |
| 7705 | /// |
| 7706 | /// - OrcaRouter does not publish `supported_parameters` on its rows, so the |
| 7707 | /// OpenRouter projection's `reasoning`/`tool_call` would become a factual |
| 7708 | /// "no reasoning, no tools". It strips them back to unclaimed instead: on |
| 7709 | /// this gateway an absent parameter list is silence, not a refusal. That |
| 7710 | /// also keeps Codewhale's tools enabled for OrcaRouter chat models. |
| 7711 | /// - A row whose `architecture` names an explicit input set keeps it verbatim, |
| 7712 | /// so the multimodal gate downstream is reading a stated fact. Rows with no |
| 7713 | /// `architecture` stay unclaimed rather than inheriting a "text" default. |
| 7714 | /// - `pricing.tiers` become context tiers. A tier list that cannot be read |
| 7715 | /// withholds the row's price rather than quoting long prompts at the base |
| 7716 | /// rate. |
| 7717 | fn orcarouter_to_catalog_offering( |
| 7718 | item: &OpenRouterModelItem, |
| 7719 | provider: &str, |
| 7720 | base_url_fingerprint: &str, |
| 7721 | fetched_at: u64, |
| 7722 | ) -> Result<CatalogOffering, CatalogRefreshError> { |
| 7723 | let mut offering = |
| 7724 | openrouter_to_catalog_offering(item, provider, base_url_fingerprint, fetched_at)?; |
| 7725 | if item.supported_parameters.is_none() { |
| 7726 | offering.reasoning = None; |
| 7727 | offering.tool_call = None; |
| 7728 | offering.structured_output = None; |
| 7729 | } |
| 7730 | if item.architecture.is_none() { |
| 7731 | offering.modalities = None; |
| 7732 | } |
| 7733 | let tiers = item |
| 7734 | .pricing |
| 7735 | .as_ref() |
| 7736 | .and_then(|pricing| pricing.tiers.as_ref()); |
| 7737 | if let Some(tiers) = tiers |
| 7738 | && let Some(base) = offering.cost.clone() |
| 7739 | { |
| 7740 | let tiered = orcarouter_context_tiers(tiers, &base).map(|tiers| { |
| 7741 | codewhale_config::models_dev::ModelsDevCost { |
| 7742 | tiers: (!tiers.is_empty()).then_some(tiers), |
| 7743 | ..base |
| 7744 | } |
| 7745 | }); |
| 7746 | match tiered { |
| 7747 | Some(cost) if codewhale_config::pricing::catalog_cost_is_valid(&cost) => { |
| 7748 | offering.cost = Some(cost); |
| 7749 | } |
| 7750 | _ => offering.cost = None, |
| 7751 | } |
| 7752 | } |
| 7753 | Ok(offering) |
| 7754 | } |
| 7755 | |
| 7756 | fn orcarouter_context_tiers( |
| 7757 | tiers: &Value, |
| 7758 | base: &codewhale_config::models_dev::ModelsDevCost, |
| 7759 | ) -> Option<Vec<codewhale_config::models_dev::ModelsDevCostTier>> { |
| 7760 | use codewhale_config::models_dev::{ModelsDevContextTier, ModelsDevCost, ModelsDevCostTier}; |
| 7761 | |
| 7762 | let tiers: Vec<OrcaRouterPriceTier> = serde_json::from_value(tiers.clone()).ok()?; |
| 7763 | let rate = |value: &Option<String>| -> Option<Option<f64>> { |
| 7764 | match value { |
| 7765 | None => Some(None), |
| 7766 | Some(value) => value |
| 7767 | .trim() |
| 7768 | .parse::<f64>() |
| 7769 | .ok() |
| 7770 | .filter(|value| value.is_finite()) |
| 7771 | .and_then(|value| checked_per_token_to_per_million(value).ok()) |
| 7772 | .map(Some), |
| 7773 | } |
| 7774 | }; |
| 7775 | let mut mapped = Vec::with_capacity(tiers.len().saturating_sub(1)); |
| 7776 | let mut floor: Option<u64> = None; |
| 7777 | for (index, tier) in tiers.iter().enumerate() { |
| 7778 | let cost = ModelsDevCost { |
| 7779 | input: rate(&tier.prompt)?, |
| 7780 | output: rate(&tier.completion)?, |
| 7781 | cache_read: rate(&tier.input_cache_read)?, |
| 7782 | cache_write: rate(&tier.input_cache_write)?, |
| 7783 | ..Default::default() |
| 7784 | }; |
| 7785 | if index == 0 { |
| 7786 | if (cost.input, cost.output) != (base.input, base.output) { |
| 7787 | return None; |
| 7788 | } |
| 7789 | } else { |
| 7790 | mapped.push(ModelsDevCostTier { |
| 7791 | tier: ModelsDevContextTier { |
| 7792 | kind: "context".to_string(), |
| 7793 | size: floor?, |
| 7794 | }, |
| 7795 | cost, |
| 7796 | }); |
| 7797 | } |
| 7798 | floor = match tier.max_input_tokens { |
| 7799 | Some(max) if max > floor.unwrap_or(0) => Some(max), |
| 7800 | Some(0) | None if index + 1 == tiers.len() => None, |
| 7801 | _ => return None, |
| 7802 | }; |
| 7803 | } |
| 7804 | Some(mapped) |
| 7805 | } |
| 7806 | |
| 7807 | /// Parse Baseten's authenticated Model APIs catalog without inferring facts |
| 7808 | /// from an identically named model on another provider. |
| 7809 | fn parse_baseten_models_response( |
| 7810 | payload: &str, |
| 7811 | ) -> Result<Vec<BasetenModelItem>, CatalogRefreshError> { |
| 7812 | let parsed: BasetenModelsResponse = |
| 7813 | serde_json::from_str(payload).map_err(|_| CatalogRefreshError::InvalidResponse)?; |
| 7814 | let mut seen = std::collections::HashSet::new(); |
| 7815 | let mut models = Vec::with_capacity(parsed.data.len()); |
| 7816 | for mut item in parsed.data { |
| 7817 | item.id = item.id.trim().to_string(); |
| 7818 | if item.id.is_empty() || !seen.insert(item.id.clone()) { |
| 7819 | return Err(CatalogRefreshError::InvalidResponse); |
| 7820 | } |
| 7821 | models.push(item); |
| 7822 | } |
| 7823 | Ok(models) |
| 7824 | } |
| 7825 | |
| 7826 | fn prime_intellect_row_is_chat(item: &PrimeIntellectModelItem) -> bool { |
| 7827 | let outputs = item |
| 7828 | .output_modalities |
| 7829 | .as_deref() |
| 7830 | .filter(|modalities| !modalities.is_empty()) |
| 7831 | .or_else(|| { |
| 7832 | item.specs |
| 7833 | .as_ref() |
| 7834 | .and_then(|specs| specs.modalities.as_ref()) |
| 7835 | .and_then(|modalities| modalities.output.as_deref()) |
| 7836 | .filter(|modalities| !modalities.is_empty()) |
| 7837 | }); |
| 7838 | match outputs { |
| 7839 | Some(outputs) => outputs |
| 7840 | .iter() |
| 7841 | .any(|modality| modality.trim().eq_ignore_ascii_case("text")), |
| 7842 | None => true, |
| 7843 | } |
| 7844 | } |
| 7845 | |
| 7846 | fn parse_prime_intellect_models_response( |
| 7847 | payload: &str, |
| 7848 | ) -> Result<Vec<PrimeIntellectModelItem>, CatalogRefreshError> { |
| 7849 | let parsed: PrimeIntellectModelsResponse = |
| 7850 | serde_json::from_str(payload).map_err(|_| CatalogRefreshError::InvalidResponse)?; |
| 7851 | let listed = parsed.data.len(); |
| 7852 | let mut seen = std::collections::HashSet::new(); |
| 7853 | let mut malformed = 0usize; |
| 7854 | let mut models = Vec::with_capacity(listed); |
| 7855 | for row in parsed.data { |
| 7856 | let Ok(mut item) = serde_json::from_str::<PrimeIntellectModelItem>(row.get()) else { |
| 7857 | malformed += 1; |
| 7858 | continue; |
| 7859 | }; |
| 7860 | item.id = item.id.trim().to_string(); |
| 7861 | if !codewhale_runtime::catalog_cache::valid_catalog_model_id(&item.id) { |
| 7862 | malformed += 1; |
| 7863 | continue; |
| 7864 | } |
| 7865 | if seen.insert(item.id.clone()) { |
| 7866 | models.push(item); |
| 7867 | } |
| 7868 | } |
| 7869 | if malformed > 0 { |
| 7870 | tracing::warn!( |
| 7871 | malformed, |
| 7872 | listed, |
| 7873 | "skipped malformed Prime Intellect model rows in the catalog refresh" |
| 7874 | ); |
| 7875 | } |
| 7876 | if models.is_empty() && malformed > 0 { |
| 7877 | return Err(CatalogRefreshError::InvalidResponse); |
| 7878 | } |
| 7879 | Ok(models) |
| 7880 | } |
| 7881 | |
| 7882 | fn prime_intellect_rate(value: Option<&CatalogNumber>) -> Result<Option<f64>, CatalogRefreshError> { |
| 7883 | let Some(value) = value else { |
| 7884 | return Ok(None); |
| 7885 | }; |
| 7886 | let rate = catalog_number_f64(Some(value))?.ok_or(CatalogRefreshError::InvalidResponse)?; |
| 7887 | if (0.0..=codewhale_config::pricing::MAX_PLAUSIBLE_PRICE_PER_MILLION).contains(&rate) { |
| 7888 | Ok(Some(rate)) |
| 7889 | } else { |
| 7890 | Err(CatalogRefreshError::InvalidResponse) |
| 7891 | } |
| 7892 | } |
| 7893 | |
| 7894 | fn prime_intellect_to_catalog_offering( |
| 7895 | item: &PrimeIntellectModelItem, |
| 7896 | provider: &str, |
| 7897 | base_url_fingerprint: &str, |
| 7898 | fetched_at: u64, |
| 7899 | ) -> CatalogOffering { |
| 7900 | use codewhale_config::models_dev::{ModelsDevCost, ModelsDevLimit, ModelsDevModalities}; |
| 7901 | |
| 7902 | let context = [ |
| 7903 | item.context_length.as_ref(), |
| 7904 | item.context_window.as_ref(), |
| 7905 | item.specs |
| 7906 | .as_ref() |
| 7907 | .and_then(|specs| specs.context_window.as_ref()), |
| 7908 | ] |
| 7909 | .into_iter() |
| 7910 | .find_map(stated_token_count); |
| 7911 | let output = [ |
| 7912 | item.max_output_length.as_ref(), |
| 7913 | item.max_output_tokens.as_ref(), |
| 7914 | item.specs |
| 7915 | .as_ref() |
| 7916 | .and_then(|specs| specs.max_output_tokens.as_ref()), |
| 7917 | ] |
| 7918 | .into_iter() |
| 7919 | .find_map(stated_token_count); |
| 7920 | let limit = (context.is_some() || output.is_some()).then_some(ModelsDevLimit { |
| 7921 | context, |
| 7922 | input: context, |
| 7923 | output, |
| 7924 | }); |
| 7925 | |
| 7926 | let cost = item.pricing.as_ref().and_then(|pricing| { |
| 7927 | let cost = ModelsDevCost { |
| 7928 | input: prime_intellect_rate(pricing.input_usd_per_mtok.as_ref()).ok()?, |
| 7929 | output: prime_intellect_rate(pricing.output_usd_per_mtok.as_ref()).ok()?, |
| 7930 | cache_read: prime_intellect_rate(pricing.cache_read_usd_per_mtok.as_ref()).ok()?, |
| 7931 | cache_write: prime_intellect_rate(pricing.cache_write_usd_per_mtok.as_ref()).ok()?, |
| 7932 | ..Default::default() |
| 7933 | }; |
| 7934 | (codewhale_config::pricing::catalog_cost_is_valid(&cost) |
| 7935 | && (cost.input.is_some() |
| 7936 | || cost.output.is_some() |
| 7937 | || cost.cache_read.is_some() |
| 7938 | || cost.cache_write.is_some())) |
| 7939 | .then_some(cost) |
| 7940 | }); |
| 7941 | |
| 7942 | let input_modalities = item |
| 7943 | .input_modalities |
| 7944 | .as_ref() |
| 7945 | .filter(|modalities| !modalities.is_empty()) |
| 7946 | .cloned() |
| 7947 | .or_else(|| { |
| 7948 | item.specs |
| 7949 | .as_ref() |
| 7950 | .and_then(|specs| specs.modalities.as_ref()) |
| 7951 | .and_then(|modalities| modalities.input.as_ref()) |
| 7952 | .filter(|modalities| !modalities.is_empty()) |
| 7953 | .cloned() |
| 7954 | }); |
| 7955 | let output_modalities = item |
| 7956 | .output_modalities |
| 7957 | .as_ref() |
| 7958 | .filter(|modalities| !modalities.is_empty()) |
| 7959 | .cloned() |
| 7960 | .or_else(|| { |
| 7961 | item.specs |
| 7962 | .as_ref() |
| 7963 | .and_then(|specs| specs.modalities.as_ref()) |
| 7964 | .and_then(|modalities| modalities.output.as_ref()) |
| 7965 | .filter(|modalities| !modalities.is_empty()) |
| 7966 | .cloned() |
| 7967 | }); |
| 7968 | let attachment = input_modalities.as_ref().map(|inputs| { |
| 7969 | inputs.iter().any(|modality| { |
| 7970 | let trimmed = modality.trim(); |
| 7971 | !trimmed.is_empty() && !trimmed.eq_ignore_ascii_case("text") |
| 7972 | }) |
| 7973 | }); |
| 7974 | let modalities = if input_modalities.is_some() || output_modalities.is_some() { |
| 7975 | Some(ModelsDevModalities { |
| 7976 | input: input_modalities.unwrap_or_default(), |
| 7977 | output: output_modalities.unwrap_or_default(), |
| 7978 | }) |
| 7979 | } else { |
| 7980 | None |
| 7981 | }; |
| 7982 | |
| 7983 | let params = item |
| 7984 | .supported_parameters |
| 7985 | .as_deref() |
| 7986 | .filter(|params| !params.is_empty()); |
| 7987 | let has_param = |pred: &dyn Fn(&str) -> bool| { |
| 7988 | params.map(|items| items.iter().any(|item| pred(item.trim()))) |
| 7989 | }; |
| 7990 | let reasoning = item |
| 7991 | .specs |
| 7992 | .as_ref() |
| 7993 | .and_then(|specs| specs.supports_reasoning) |
| 7994 | .or_else(|| { |
| 7995 | has_param(&|param| { |
| 7996 | matches!( |
| 7997 | param, |
| 7998 | "reasoning" | "include_reasoning" | "reasoning_effort" |
| 7999 | ) |
| 8000 | }) |
| 8001 | }); |
| 8002 | let tool_call = has_param(&|param| matches!(param, "tools" | "tool_choice")); |
| 8003 | let structured_output = |
| 8004 | has_param(&|param| matches!(param, "response_format" | "structured_outputs")); |
| 8005 | |
| 8006 | CatalogOffering { |
| 8007 | cost_source: None, |
| 8008 | modalities_source: None, |
| 8009 | provider: provider.to_string(), |
| 8010 | wire_model_id: item.id.clone(), |
| 8011 | canonical_model: None, |
| 8012 | endpoint_key: "chat".to_string(), |
| 8013 | default_for_provider: item |
| 8014 | .id |
| 8015 | .eq_ignore_ascii_case(codewhale_config::catalog::PRIME_INTELLECT_DEFAULT_MODEL), |
| 8016 | family: None, |
| 8017 | limit, |
| 8018 | cost, |
| 8019 | modalities, |
| 8020 | attachment, |
| 8021 | reasoning, |
| 8022 | tool_call, |
| 8023 | structured_output, |
| 8024 | reasoning_options: Vec::new(), |
| 8025 | reasoning_options_present: false, |
| 8026 | source: CatalogSource::Live { |
| 8027 | base_url_fingerprint: base_url_fingerprint.to_string(), |
| 8028 | fetched_at, |
| 8029 | }, |
| 8030 | ..Default::default() |
| 8031 | } |
| 8032 | } |
| 8033 | |
| 8034 | fn catalog_number_f64(value: Option<&CatalogNumber>) -> Result<Option<f64>, CatalogRefreshError> { |
| 8035 | let Some(value) = value else { |
| 8036 | return Ok(None); |
| 8037 | }; |
| 8038 | let parsed = match value { |
| 8039 | CatalogNumber::Number(number) => number.as_f64(), |
| 8040 | CatalogNumber::Text(text) => text.trim().parse::<f64>().ok(), |
| 8041 | } |
| 8042 | .filter(|number| number.is_finite() && *number >= 0.0) |
| 8043 | .ok_or(CatalogRefreshError::InvalidResponse)?; |
| 8044 | Ok(Some(parsed)) |
| 8045 | } |
| 8046 | |
| 8047 | fn catalog_number_u64(value: Option<&CatalogNumber>) -> Result<Option<u64>, CatalogRefreshError> { |
| 8048 | let Some(number) = catalog_number_f64(value)? else { |
| 8049 | return Ok(None); |
| 8050 | }; |
| 8051 | if number.fract() != 0.0 || number > u64::MAX as f64 { |
| 8052 | return Err(CatalogRefreshError::InvalidResponse); |
| 8053 | } |
| 8054 | Ok(Some(number as u64)) |
| 8055 | } |
| 8056 | |
| 8057 | fn checked_per_token_to_per_million(value: f64) -> Result<f64, CatalogRefreshError> { |
| 8058 | let scaled = value * 1_000_000.0; |
| 8059 | (scaled.is_finite() |
| 8060 | && (0.0..=codewhale_config::pricing::MAX_PLAUSIBLE_PRICE_PER_MILLION).contains(&scaled)) |
| 8061 | .then_some(scaled) |
| 8062 | .ok_or(CatalogRefreshError::InvalidResponse) |
| 8063 | } |
| 8064 | |
| 8065 | fn catalog_price_per_million( |
| 8066 | value: Option<&CatalogNumber>, |
| 8067 | ) -> Result<Option<f64>, CatalogRefreshError> { |
| 8068 | catalog_number_f64(value)? |
| 8069 | .map(checked_per_token_to_per_million) |
| 8070 | .transpose() |
| 8071 | } |
| 8072 | |
| 8073 | fn feature_matches_any(feature: &str, aliases: &[&str]) -> bool { |
| 8074 | let normalized = feature.replace('-', "_"); |
| 8075 | aliases.iter().any(|alias| normalized == *alias) |
| 8076 | } |
| 8077 | |
| 8078 | fn baseten_features(item: &BasetenModelItem) -> Option<Vec<String>> { |
| 8079 | let sources = [ |
| 8080 | item.supported_parameters.as_ref(), |
| 8081 | item.supported_features.as_ref(), |
| 8082 | item.features.as_ref(), |
| 8083 | ]; |
| 8084 | let mut features = Vec::new(); |
| 8085 | let mut published = false; |
| 8086 | for source in sources.into_iter().flatten() { |
| 8087 | published = true; |
| 8088 | for feature in source { |
| 8089 | let normalized = feature.trim().to_ascii_lowercase(); |
| 8090 | if !normalized.is_empty() && !features.contains(&normalized) { |
| 8091 | features.push(normalized); |
| 8092 | } |
| 8093 | } |
| 8094 | } |
| 8095 | published.then_some(features) |
| 8096 | } |
| 8097 | |
| 8098 | fn baseten_to_catalog_offering( |
| 8099 | item: &BasetenModelItem, |
| 8100 | provider: &str, |
| 8101 | base_url_fingerprint: &str, |
| 8102 | fetched_at: u64, |
| 8103 | ) -> Result<CatalogOffering, CatalogRefreshError> { |
| 8104 | use codewhale_config::models_dev::{ModelsDevCost, ModelsDevLimit, ModelsDevModalities}; |
| 8105 | |
| 8106 | let context = catalog_number_u64( |
| 8107 | item.top_provider |
| 8108 | .as_ref() |
| 8109 | .and_then(|provider| provider.context_length.as_ref()) |
| 8110 | .or(item.context_length.as_ref()) |
| 8111 | .or(item.context_window.as_ref()) |
| 8112 | .or_else(|| { |
| 8113 | item.limits |
| 8114 | .as_ref() |
| 8115 | .and_then(|limits| limits.context.as_ref()) |
| 8116 | }), |
| 8117 | )?; |
| 8118 | let output = catalog_number_u64( |
| 8119 | item.top_provider |
| 8120 | .as_ref() |
| 8121 | .and_then(|provider| provider.max_completion_tokens.as_ref()) |
| 8122 | .or(item.max_output_tokens.as_ref()) |
| 8123 | .or(item.max_completion_tokens.as_ref()) |
| 8124 | .or_else(|| { |
| 8125 | item.limits |
| 8126 | .as_ref() |
| 8127 | .and_then(|limits| limits.output.as_ref()) |
| 8128 | }), |
| 8129 | )?; |
| 8130 | let limit = (context.is_some() || output.is_some()).then_some(ModelsDevLimit { |
| 8131 | context, |
| 8132 | input: context, |
| 8133 | output, |
| 8134 | }); |
| 8135 | |
| 8136 | let cost = if let Some(pricing) = item.pricing.as_ref() { |
| 8137 | let cost = ModelsDevCost { |
| 8138 | input: catalog_price_per_million(pricing.prompt.as_ref())?, |
| 8139 | output: catalog_price_per_million(pricing.completion.as_ref())?, |
| 8140 | cache_read: catalog_price_per_million(pricing.input_cache_read.as_ref())?, |
| 8141 | cache_write: catalog_price_per_million(pricing.input_cache_write.as_ref())?, |
| 8142 | ..Default::default() |
| 8143 | }; |
| 8144 | if !codewhale_config::pricing::catalog_cost_is_valid(&cost) { |
| 8145 | return Err(CatalogRefreshError::InvalidResponse); |
| 8146 | } |
| 8147 | (cost.input.is_some() |
| 8148 | || cost.output.is_some() |
| 8149 | || cost.cache_read.is_some() |
| 8150 | || cost.cache_write.is_some()) |
| 8151 | .then_some(cost) |
| 8152 | } else { |
| 8153 | None |
| 8154 | }; |
| 8155 | |
| 8156 | let features = baseten_features(item); |
| 8157 | let has_feature = |needles: &[&str]| { |
| 8158 | features.as_ref().is_some_and(|features| { |
| 8159 | features |
| 8160 | .iter() |
| 8161 | .any(|feature| feature_matches_any(feature, needles)) |
| 8162 | }) |
| 8163 | }; |
| 8164 | let mut input_modalities = item |
| 8165 | .architecture |
| 8166 | .as_ref() |
| 8167 | .and_then(|architecture| architecture.input_modalities.clone()) |
| 8168 | .or_else(|| item.input_modalities.clone()); |
| 8169 | let mut output_modalities = item |
| 8170 | .architecture |
| 8171 | .as_ref() |
| 8172 | .and_then(|architecture| architecture.output_modalities.clone()) |
| 8173 | .or_else(|| item.output_modalities.clone()); |
| 8174 | if input_modalities.is_none() { |
| 8175 | let supports_vision = has_feature(&["vision", "image", "image_input"]); |
| 8176 | let supports_audio = has_feature(&["audio", "audio_input"]); |
| 8177 | if supports_vision || supports_audio { |
| 8178 | let mut derived = vec!["text".to_string()]; |
| 8179 | if supports_vision { |
| 8180 | derived.push("image".to_string()); |
| 8181 | } |
| 8182 | if supports_audio { |
| 8183 | derived.push("audio".to_string()); |
| 8184 | } |
| 8185 | input_modalities = Some(derived); |
| 8186 | output_modalities.get_or_insert_with(|| vec!["text".to_string()]); |
| 8187 | } |
| 8188 | } |
| 8189 | let modalities = if input_modalities.is_some() || output_modalities.is_some() { |
| 8190 | Some(ModelsDevModalities { |
| 8191 | input: input_modalities.unwrap_or_default(), |
| 8192 | output: output_modalities.unwrap_or_default(), |
| 8193 | }) |
| 8194 | } else { |
| 8195 | None |
| 8196 | }; |
| 8197 | let attachment = modalities.as_ref().map(|modalities| { |
| 8198 | modalities |
| 8199 | .input |
| 8200 | .iter() |
| 8201 | .any(|modality| !modality.eq_ignore_ascii_case("text") && !modality.trim().is_empty()) |
| 8202 | }); |
| 8203 | |
| 8204 | let feature_support = |needles: &[&str]| { |
| 8205 | features.as_ref().map(|features| { |
| 8206 | features |
| 8207 | .iter() |
| 8208 | .any(|feature| feature_matches_any(feature, needles)) |
| 8209 | }) |
| 8210 | }; |
| 8211 | let reasoning = item |
| 8212 | .reasoning |
| 8213 | .or(item.supports_reasoning) |
| 8214 | .or_else(|| feature_support(&["reasoning", "include_reasoning"])); |
| 8215 | // Baseten's current Model APIs contract states every catalog model supports |
| 8216 | // tool calling and structured outputs. Explicit upstream booleans still |
| 8217 | // win if the endpoint publishes a narrower model-specific fact. |
| 8218 | // Baseten's Model APIs contract applies these two capabilities to every |
| 8219 | // catalog model. `supported_features` is additive and may list only |
| 8220 | // model-variable facts such as `reasoning` or `vision`; absence from that |
| 8221 | // list is therefore not an explicit false. Only an upstream boolean may |
| 8222 | // narrow the universal contract for a specific row. |
| 8223 | let tool_call = item.supports_tools.or(Some(true)); |
| 8224 | let structured_output = item.supports_structured_output.or(Some(true)); |
| 8225 | |
| 8226 | Ok(CatalogOffering { |
| 8227 | cost_source: None, |
| 8228 | modalities_source: None, |
| 8229 | provider: provider.to_string(), |
| 8230 | wire_model_id: item.id.clone(), |
| 8231 | canonical_model: None, |
| 8232 | endpoint_key: "chat".to_string(), |
| 8233 | default_for_provider: item |
| 8234 | .id |
| 8235 | .eq_ignore_ascii_case(codewhale_config::catalog::BASETEN_DEFAULT_MODEL), |
| 8236 | family: None, |
| 8237 | limit, |
| 8238 | cost, |
| 8239 | modalities, |
| 8240 | attachment, |
| 8241 | reasoning, |
| 8242 | tool_call, |
| 8243 | structured_output, |
| 8244 | reasoning_options: item.reasoning_options.clone().unwrap_or_default(), |
| 8245 | reasoning_options_present: item.reasoning_options.is_some(), |
| 8246 | source: CatalogSource::Live { |
| 8247 | base_url_fingerprint: base_url_fingerprint.to_string(), |
| 8248 | fetched_at, |
| 8249 | }, |
| 8250 | ..Default::default() |
| 8251 | }) |
| 8252 | } |
| 8253 | |
| 8254 | #[cfg(any(test, feature = "test-support"))] |
| 8255 | fn publish_provider_lake_scope(cache: &ProviderCatalogCache, provider: &str, fingerprint: &str) { |
| 8256 | // Publish fresh *and* stale/prior rows so pickers keep live catalog coverage |
| 8257 | // after TTL expiry or a failed refresh (#4139). Exact replacement is |
| 8258 | // essential: a successful smaller roster must remove upstream-retired ids, |
| 8259 | // while a failure preserves the rows already stored in this cache scope. |
| 8260 | let offerings = cache |
| 8261 | .get(provider, fingerprint) |
| 8262 | .map(|entry| entry.offerings.clone()) |
| 8263 | .unwrap_or_default(); |
| 8264 | crate::provider_lake::replace_provider_live_snapshot(provider, CatalogSnapshot { offerings }); |
| 8265 | } |
| 8266 | |
| 8267 | /// Convert an OpenRouter model item into a [`CatalogOffering`] with live-sourced |
| 8268 | /// limits, pricing, reasoning, and modalities (#3385). |
| 8269 | fn openrouter_to_catalog_offering( |
| 8270 | item: &OpenRouterModelItem, |
| 8271 | provider: &str, |
| 8272 | base_url_fingerprint: &str, |
| 8273 | fetched_at: u64, |
| 8274 | ) -> Result<CatalogOffering, CatalogRefreshError> { |
| 8275 | use codewhale_config::models_dev::{ModelsDevCost, ModelsDevLimit, ModelsDevModalities}; |
| 8276 | |
| 8277 | let context_length = item |
| 8278 | .top_provider |
| 8279 | .as_ref() |
| 8280 | .and_then(|tp| tp.context_length) |
| 8281 | .or(item.context_length); |
| 8282 | |
| 8283 | let max_output = item |
| 8284 | .top_provider |
| 8285 | .as_ref() |
| 8286 | .and_then(|tp| tp.max_completion_tokens); |
| 8287 | |
| 8288 | let limit = if context_length.is_some() || max_output.is_some() { |
| 8289 | Some(ModelsDevLimit { |
| 8290 | context: context_length.map(u64::from), |
| 8291 | input: context_length.map(u64::from), |
| 8292 | output: max_output.map(u64::from), |
| 8293 | }) |
| 8294 | } else { |
| 8295 | None |
| 8296 | }; |
| 8297 | |
| 8298 | let cost = if let Some(p) = item.pricing.as_ref() { |
| 8299 | // OpenRouter quotes per-token USD strings; ModelsDevCost is per million. |
| 8300 | // Its routers (`openrouter/auto`, `openrouter/fusion`, ...) publish |
| 8301 | // `"-1"`: the price depends on the model the router picks. A negative |
| 8302 | // price therefore means "no fixed rate" for the whole row, never a |
| 8303 | // partial one. |
| 8304 | let parse_price = |value: &Option<String>| -> Result<Option<f64>, CatalogRefreshError> { |
| 8305 | value |
| 8306 | .as_ref() |
| 8307 | .map(|value| { |
| 8308 | value |
| 8309 | .trim() |
| 8310 | .parse::<f64>() |
| 8311 | .ok() |
| 8312 | .filter(|value| value.is_finite()) |
| 8313 | .ok_or(CatalogRefreshError::InvalidResponse) |
| 8314 | }) |
| 8315 | .transpose() |
| 8316 | }; |
| 8317 | let raw = [ |
| 8318 | parse_price(&p.prompt)?, |
| 8319 | parse_price(&p.completion)?, |
| 8320 | parse_price(&p.input_cache_read)?, |
| 8321 | parse_price(&p.input_cache_write)?, |
| 8322 | ]; |
| 8323 | if raw.iter().flatten().any(|price| *price < 0.0) { |
| 8324 | None |
| 8325 | } else { |
| 8326 | let per_million = |
| 8327 | |price: Option<f64>| price.map(checked_per_token_to_per_million).transpose(); |
| 8328 | let cost = ModelsDevCost { |
| 8329 | input: per_million(raw[0])?, |
| 8330 | output: per_million(raw[1])?, |
| 8331 | cache_read: per_million(raw[2])?, |
| 8332 | cache_write: per_million(raw[3])?, |
| 8333 | ..Default::default() |
| 8334 | }; |
| 8335 | if !codewhale_config::pricing::catalog_cost_is_valid(&cost) { |
| 8336 | return Err(CatalogRefreshError::InvalidResponse); |
| 8337 | } |
| 8338 | Some(cost) |
| 8339 | } |
| 8340 | } else { |
| 8341 | None |
| 8342 | }; |
| 8343 | |
| 8344 | let reasoning = item.supported_parameters.as_ref().map(|params| { |
| 8345 | params |
| 8346 | .iter() |
| 8347 | .any(|p| p == "reasoning" || p == "include_reasoning" || p.contains("reasoning")) |
| 8348 | }); |
| 8349 | |
| 8350 | let tool_call = item.supported_parameters.as_ref().map(|params| { |
| 8351 | params |
| 8352 | .iter() |
| 8353 | .any(|p| p == "tools" || p == "tool_choice" || p == "functions" || p.contains("tool")) |
| 8354 | }); |
| 8355 | |
| 8356 | let structured_output = item.supported_parameters.as_ref().map(|params| { |
| 8357 | params |
| 8358 | .iter() |
| 8359 | .any(|p| matches!(p.as_str(), "response_format" | "structured_outputs")) |
| 8360 | }); |
| 8361 | |
| 8362 | let (reasoning_options, reasoning_options_present) = |
| 8363 | if let Some(options) = item.reasoning_options.as_ref() { |
| 8364 | (options.clone(), true) |
| 8365 | } else if let Some(options) = item.supported_reasoning_levels.as_ref().and_then(|levels| { |
| 8366 | reasoning_options_from_levels(levels, item.default_reasoning_level.as_deref()) |
| 8367 | }) { |
| 8368 | (options, true) |
| 8369 | } else { |
| 8370 | (Vec::new(), false) |
| 8371 | }; |
| 8372 | |
| 8373 | let modalities = item.architecture.as_ref().map(|arch| { |
| 8374 | let mut input = arch.input_modalities.clone().unwrap_or_default(); |
| 8375 | let mut output = arch.output_modalities.clone().unwrap_or_default(); |
| 8376 | if input.is_empty() |
| 8377 | && output.is_empty() |
| 8378 | && let Some((left, right)) = arch |
| 8379 | .modality |
| 8380 | .as_deref() |
| 8381 | .and_then(|value| value.split_once("->")) |
| 8382 | { |
| 8383 | input.extend( |
| 8384 | left.split('+') |
| 8385 | .map(str::trim) |
| 8386 | .filter(|value| !value.is_empty()) |
| 8387 | .map(str::to_string), |
| 8388 | ); |
| 8389 | output.extend( |
| 8390 | right |
| 8391 | .split('+') |
| 8392 | .map(str::trim) |
| 8393 | .filter(|value| !value.is_empty()) |
| 8394 | .map(str::to_string), |
| 8395 | ); |
| 8396 | } |
| 8397 | ModelsDevModalities { input, output } |
| 8398 | }); |
| 8399 | |
| 8400 | Ok(CatalogOffering { |
| 8401 | cost_source: None, |
| 8402 | modalities_source: None, |
| 8403 | provider: provider.to_string(), |
| 8404 | wire_model_id: item.id.clone(), |
| 8405 | canonical_model: None, |
| 8406 | endpoint_key: "chat".to_string(), |
| 8407 | default_for_provider: false, |
| 8408 | family: None, |
| 8409 | limit, |
| 8410 | cost, |
| 8411 | modalities, |
| 8412 | attachment: None, |
| 8413 | reasoning, |
| 8414 | tool_call, |
| 8415 | structured_output, |
| 8416 | reasoning_options, |
| 8417 | reasoning_options_present, |
| 8418 | source: CatalogSource::Live { |
| 8419 | base_url_fingerprint: base_url_fingerprint.to_string(), |
| 8420 | fetched_at, |
| 8421 | }, |
| 8422 | ..Default::default() |
| 8423 | }) |
| 8424 | } |
| 8425 | |
| 8426 | /// The rate a main interactive turn freezes at its dispatch boundary (#6690). |
| 8427 | /// An operator-declared `[[custom_models]]` rate wins, exactly as on the |
| 8428 | /// background envelope path; `client` must be installed on the endpoint this |
| 8429 | /// turn dispatches to, so a declaration never leaks onto another endpoint. A |
| 8430 | /// declaration with no rates yields to the catalog price for that endpoint. |
| 8431 | pub fn main_turn_pricing_quote_at( |
| 8432 | client: Option<&CodewhaleClient>, |
| 8433 | provider: ProviderKind, |
| 8434 | provider_identity: &str, |
| 8435 | model: &str, |
| 8436 | endpoint_fingerprint: &str, |
| 8437 | dispatched_at: u64, |
| 8438 | ) -> Option<crate::provider_catalog_live::ProviderLivePricingQuote> { |
| 8439 | let client = client.filter(|client| { |
| 8440 | crate::cost_status::endpoint_fingerprint(client.base_url()).as_deref() |
| 8441 | == Some(endpoint_fingerprint) |
| 8442 | }); |
| 8443 | let declared = client.and_then(|client| { |
| 8444 | client.configured_pricing_quote_at(provider, provider_identity, model, dispatched_at) |
| 8445 | }); |
| 8446 | crate::provider_catalog_live::declared_or_catalog_quote(declared, || match client { |
| 8447 | Some(client) => crate::provider_catalog_live::fresh_dispatch_pricing_quote_at( |
| 8448 | provider, |
| 8449 | provider_identity, |
| 8450 | model, |
| 8451 | client.base_url(), |
| 8452 | dispatched_at, |
| 8453 | ), |
| 8454 | None => crate::provider_catalog_live::fresh_provider_live_pricing_quote_at( |
| 8455 | provider, |
| 8456 | provider_identity, |
| 8457 | model, |
| 8458 | endpoint_fingerprint, |
| 8459 | dispatched_at, |
| 8460 | ), |
| 8461 | }) |
| 8462 | } |
| 8463 | |
| 8464 | impl CodewhaleClient { |
| 8465 | pub fn can_request_fim_completion(&self) -> bool { |
| 8466 | self.api_provider != ProviderKind::OpencodeZen |
| 8467 | && self.wire_format == WireFormat::ChatCompletions |
| 8468 | } |
| 8469 | |
| 8470 | /// Call the DeepSeek `/beta/completions` FIM endpoint. |
| 8471 | pub async fn fim_completion( |
| 8472 | &self, |
| 8473 | model: &str, |
| 8474 | prompt: &str, |
| 8475 | suffix: &str, |
| 8476 | max_tokens: u32, |
| 8477 | ) -> anyhow::Result<String> { |
| 8478 | let _inference = self.acquire_remote_control_inference_permit().await; |
| 8479 | let _permit = self.acquire_provider_request_permit().await; |
| 8480 | if !self.can_request_fim_completion() { |
| 8481 | bail!( |
| 8482 | "FIM completion is not supported for {} because the route has no proven FIM wire contract ({:?})", |
| 8483 | self.api_provider.provider().display_name(), |
| 8484 | self.wire_format |
| 8485 | ); |
| 8486 | } |
| 8487 | let url = api_url_with_suffix(&self.base_url, "beta/completions", None); |
| 8488 | let model = self.wire_model_for_route(model); |
| 8489 | let max_tokens = self.bounded_output_tokens( |
| 8490 | &model, |
| 8491 | self.route_limits_for_model(&model), |
| 8492 | max_tokens.min(self.effective_max_output_tokens(&model)), |
| 8493 | crate::compaction::estimate_text_tokens_conservative(prompt) |
| 8494 | .saturating_add(crate::compaction::estimate_text_tokens_conservative(suffix)), |
| 8495 | )?; |
| 8496 | let body = json!({ |
| 8497 | "model": model, |
| 8498 | "prompt": prompt, |
| 8499 | "suffix": suffix, |
| 8500 | "max_tokens": max_tokens, |
| 8501 | }); |
| 8502 | let response = self.send_json_with_retry(&url, &body).await?; |
| 8503 | let status = response.status(); |
| 8504 | if !status.is_success() { |
| 8505 | let raw_error_text = bounded_error_text(response, ERROR_BODY_MAX_BYTES).await; |
| 8506 | let error_text = sanitize_http_error_body( |
| 8507 | Some(self.api_provider.provider().display_name()), |
| 8508 | status.as_u16(), |
| 8509 | &raw_error_text, |
| 8510 | ); |
| 8511 | anyhow::bail!("FIM API error: HTTP {status}: {error_text}"); |
| 8512 | } |
| 8513 | let response_text = response |
| 8514 | .text() |
| 8515 | .await |
| 8516 | .context("Failed to read FIM API response body")?; |
| 8517 | let value: serde_json::Value = |
| 8518 | serde_json::from_str(&response_text).context("Failed to parse FIM API response")?; |
| 8519 | let text = value |
| 8520 | .pointer("/choices/0/text") |
| 8521 | .and_then(serde_json::Value::as_str) |
| 8522 | .ok_or_else(|| anyhow::anyhow!("FIM response missing choices[0].text"))?; |
| 8523 | Ok(text.to_string()) |
| 8524 | } |
| 8525 | } |
| 8526 | |
| 8527 | mod anthropic; |
| 8528 | mod chat; |
| 8529 | mod claude_org; |
| 8530 | mod deepseek_effort; |
| 8531 | mod deepseek_tools; |
| 8532 | pub mod gemini; |
| 8533 | pub(crate) mod minimax_speech; |
| 8534 | pub(crate) mod opencode_catalog; |
| 8535 | pub use deepseek_tools::{ |
| 8536 | DEEPSEEK_READ_URL_TOOL, DEEPSEEK_WEB_SEARCH_TOOL, DeepseekFilesPurpose, DeepseekUploadedFile, |
| 8537 | }; |
| 8538 | #[cfg(test)] |
| 8539 | mod ds4_tests; |
| 8540 | pub mod ollama_catalog; |
| 8541 | mod prepared; |
| 8542 | mod provider_native_search; |
| 8543 | pub mod reasoning_effort; |
| 8544 | mod responses; |
| 8545 | mod role_placement; |
| 8546 | mod stream_entry; |
| 8547 | pub mod system_one; |
| 8548 | |
| 8549 | /// Longest a request may take to open its stream and deliver the first body |
| 8550 | /// byte before the client itself times out (#6184): the first-byte bound plus |
| 8551 | /// two header waits, because a proven pre-dispatch failure on the dual client |
| 8552 | /// may use the HTTP/1.1 twin under its own header wait. HTTP retries |
| 8553 | /// inside one open attempt run within that attempt's header wait. The engine |
| 8554 | /// heartbeat uses this as its awaiting-model bound, so it must cover the |
| 8555 | /// fallback or an in-progress recovery reads as a stall (#6711). |
| 8556 | #[must_use] |
| 8557 | pub fn stream_first_response_bound(open: Duration, idle: Duration) -> Duration { |
| 8558 | open.saturating_mul(2) |
| 8559 | .saturating_add(stream_entry::first_byte_timeout(idle)) |
| 8560 | } |
| 8561 | |
| 8562 | pub use stream_entry::first_byte_timeout as stream_first_byte_timeout; |
| 8563 | pub use stream_entry::{is_stream_open_transport_failure, stream_open_header_timeout}; |
| 8564 | pub mod wire; |
| 8565 | |
| 8566 | // Retain the crate-visible accounting helpers at the existing client seam. |
| 8567 | #[cfg(test)] |
| 8568 | use reasoning_effort::apply_reasoning_effort; |
| 8569 | use wire::{ERROR_BODY_MAX_BYTES, bounded_error_text}; |
| 8570 | #[cfg(test)] |
| 8571 | use wire::{ |
| 8572 | SSE_MAX_LINES_PER_CHUNK, acquire_stream_buffer, from_api_tool_name, release_stream_buffer, |
| 8573 | to_api_tool_name, |
| 8574 | }; |
| 8575 | pub(super) use wire::{parse_usage, saturating_u32}; |
| 8576 | |
| 8577 | #[cfg(any(test, feature = "test-support"))] |
| 8578 | pub fn anthropic_tool_result_content_for_test( |
| 8579 | content: &str, |
| 8580 | content_blocks: Option<&[Value]>, |
| 8581 | ) -> Value { |
| 8582 | anthropic::anthropic_tool_result_content(content, content_blocks) |
| 8583 | } |
| 8584 | |
| 8585 | #[cfg(any(test, feature = "test-support"))] |
| 8586 | pub fn responses_tool_output_for_test(content: &str, content_blocks: Option<&[Value]>) -> Value { |
| 8587 | responses::responses_tool_output(content, content_blocks) |
| 8588 | } |
| 8589 | |
| 8590 | #[cfg(any(test, feature = "test-support"))] |
| 8591 | pub fn chat_messages_for_test(messages: &[codewhale_models::Message]) -> Vec<Value> { |
| 8592 | chat::build_chat_messages(None, messages, "gpt-4o") |
| 8593 | } |
| 8594 | |
| 8595 | pub use chat::{ |
| 8596 | CacheWarmupKey, PromptInspection, PromptLayerInspection, PromptLayerStability, |
| 8597 | ToolResultInspection, TurnMetaInspection, |
| 8598 | }; |
| 8599 | pub use prepared::{ |
| 8600 | CallerStreamMode, EndpointIdentity, PreparedOutboundRequest, RouteShape, WireBodyView, |
| 8601 | WireDialect, |
| 8602 | }; |
| 8603 | pub use provider_native_search::{ProviderNativeSearchClient, ProviderNativeSearchRequest}; |
| 8604 | |
| 8605 | /// Whether a route speaks ordinary `/chat/completions` (not Messages or Responses). |
| 8606 | #[must_use] |
| 8607 | pub fn provider_speaks_chat_completions(api_provider: ProviderKind) -> bool { |
| 8608 | provider_default_wire_format(api_provider) == WireFormat::ChatCompletions |
| 8609 | } |
| 8610 | |
| 8611 | pub fn inspect_prompt_for_request(request: &MessageRequest) -> PromptInspection { |
| 8612 | chat::inspect_prompt_for_request(request) |
| 8613 | } |
| 8614 | |
| 8615 | pub fn build_cache_warmup_request(request: &MessageRequest) -> MessageRequest { |
| 8616 | chat::build_cache_warmup_request(request) |
| 8617 | } |
| 8618 | |
| 8619 | pub use chat::CACHE_WARMUP_MAX_TOKENS; |
| 8620 | pub use chat::is_reasoning_replay_placeholder; |
| 8621 | |
| 8622 | #[cfg(test)] |
| 8623 | mod tests { |
| 8624 | include!("client/rate_limit_tests.rs"); |
| 8625 | include!("client/test_cases_01.rs"); |
| 8626 | |
| 8627 | include!("client/test_cases_02.rs"); |
| 8628 | |
| 8629 | include!("client/test_cases_03.rs"); |
| 8630 | |
| 8631 | include!("client/test_cases_04.rs"); |
| 8632 | |
| 8633 | include!("client/test_cases_05.rs"); |
| 8634 | |
| 8635 | include!("client/test_cases_06.rs"); |
| 8636 | |
| 8637 | include!("client/test_cases_07.rs"); |
| 8638 | |
| 8639 | include!("client/test_cases_08.rs"); |
| 8640 | |
| 8641 | include!("client/test_cases_09.rs"); |
| 8642 | } |
| 8643 | |
| 8644 | #[cfg(test)] |
| 8645 | mod configured_model_client_tests { |
| 8646 | use super::*; |
| 8647 | use codewhale_runtime::config::{ProviderConfig, ProvidersConfig}; |
| 8648 | |
| 8649 | fn config() -> Config { |
| 8650 | { |
| 8651 | let __cw_config_init_0_0 = Some("deepseek".into()); |
| 8652 | let __cw_config_init_0_1 = Some(ProvidersConfig { |
| 8653 | deepseek: ProviderConfig { |
| 8654 | api_key: Some("configured-model-local-fixture".into()), |
| 8655 | base_url: Some("https://api.deepseek.com".into()), |
| 8656 | ..ProviderConfig::default() |
| 8657 | }, |
| 8658 | ..ProvidersConfig::default() |
| 8659 | }); |
| 8660 | let __cw_config_init_0_2 = Some(vec![ |
| 8661 | toml::from_str( |
| 8662 | r#" |
| 8663 | provider = "deepseek" |
| 8664 | base_url = "https://api.deepseek.com" |
| 8665 | id = "deepseek-v4pro" |
| 8666 | limit = { context = 96000, output = 32 } |
| 8667 | cost = { input = 1.0, output = 2.0 } |
| 8668 | "#, |
| 8669 | ) |
| 8670 | .unwrap(), |
| 8671 | ]); |
| 8672 | let mut __cw_config_init_0_value: Config = Config::default(); |
| 8673 | __cw_config_init_0_value.provider = __cw_config_init_0_0; |
| 8674 | __cw_config_init_0_value.providers = __cw_config_init_0_1; |
| 8675 | __cw_config_init_0_value.custom_models = __cw_config_init_0_2; |
| 8676 | __cw_config_init_0_value |
| 8677 | } |
| 8678 | } |
| 8679 | |
| 8680 | #[test] |
| 8681 | fn alternate_declared_model_freezes_wire_limits_and_price() { |
| 8682 | let _env = crate::test_support::lock_test_env(); |
| 8683 | let mut config = config(); |
| 8684 | let mut initial = config.custom_models.as_ref().unwrap()[0].clone(); |
| 8685 | initial.id = "initial-model".into(); |
| 8686 | initial.tool_call = Some(true); |
| 8687 | config.custom_models.as_mut().unwrap()[0].tool_call = Some(false); |
| 8688 | config.custom_models.as_mut().unwrap().push(initial); |
| 8689 | let client = CodewhaleClient::from_parts( |
| 8690 | "https://api.deepseek.com".into(), |
| 8691 | "initial-model".into(), |
| 8692 | WireFormat::ChatCompletions, |
| 8693 | None, |
| 8694 | None, |
| 8695 | false, |
| 8696 | &config, |
| 8697 | ) |
| 8698 | .unwrap(); |
| 8699 | let model = "deepseek-v4pro"; |
| 8700 | config.providers.as_mut().unwrap().deepseek.model = Some(model.into()); |
| 8701 | codewhale_runtime::config::normalize_model_config_for_test(&mut config); |
| 8702 | assert_eq!(config.default_model(), model); |
| 8703 | assert_eq!( |
| 8704 | config.providers.as_ref().unwrap().deepseek.model.as_deref(), |
| 8705 | Some(model) |
| 8706 | ); |
| 8707 | config.custom_models.as_mut().unwrap()[0] |
| 8708 | .limit |
| 8709 | .as_mut() |
| 8710 | .unwrap() |
| 8711 | .output = Some(512); |
| 8712 | config.custom_models.as_mut().unwrap()[0] |
| 8713 | .cost |
| 8714 | .as_mut() |
| 8715 | .unwrap() |
| 8716 | .output = Some(99.0); |
| 8717 | config.custom_models.as_mut().unwrap()[0].tool_call = Some(true); |
| 8718 | |
| 8719 | assert_eq!(client.effective_max_output_tokens(model), 32); |
| 8720 | let prepared = client |
| 8721 | .prepare_outbound_request( |
| 8722 | translation_message_request("hello", model.into(), "English", 4096), |
| 8723 | false, |
| 8724 | ) |
| 8725 | .unwrap(); |
| 8726 | assert_eq!(prepared.wire_model, model); |
| 8727 | assert_eq!(prepared.body["model"], model); |
| 8728 | assert_eq!(prepared.body["max_tokens"], 32); |
| 8729 | let mut tool_request = translation_message_request("hello", model.into(), "English", 4096); |
| 8730 | tool_request.tools = Some(vec![codewhale_models::Tool { |
| 8731 | tool_type: None, |
| 8732 | name: "fixture".into(), |
| 8733 | description: "read-only fixture".into(), |
| 8734 | input_schema: json!({ "type": "object", "properties": {} }), |
| 8735 | allowed_callers: None, |
| 8736 | defer_loading: Some(false), |
| 8737 | input_examples: None, |
| 8738 | strict: Some(true), |
| 8739 | cache_control: None, |
| 8740 | }]); |
| 8741 | assert!( |
| 8742 | client |
| 8743 | .prepare_outbound_request(tool_request.clone(), false) |
| 8744 | .is_err() |
| 8745 | ); |
| 8746 | let mut initial_request = tool_request.clone(); |
| 8747 | initial_request.model = "initial-model".into(); |
| 8748 | assert!( |
| 8749 | client |
| 8750 | .prepare_outbound_request(initial_request, false) |
| 8751 | .is_ok() |
| 8752 | ); |
| 8753 | let rebound = client |
| 8754 | .rebound_for_model_protocol(Some(&config), model) |
| 8755 | .unwrap() |
| 8756 | .unwrap(); |
| 8757 | assert_eq!(rebound.default_model, model); |
| 8758 | assert_eq!(rebound.route_limits.unwrap().output_tokens, Some(32)); |
| 8759 | assert!( |
| 8760 | rebound |
| 8761 | .prepare_outbound_request(tool_request, false) |
| 8762 | .is_err() |
| 8763 | ); |
| 8764 | let envelope = rebound.effective_route_envelope(model, chrono::Utc::now()); |
| 8765 | assert_eq!(envelope.model, model); |
| 8766 | let quote = serde_json::to_value(envelope.provider_live_pricing.unwrap()).unwrap(); |
| 8767 | assert_eq!(quote["output_per_million"], "2"); |
| 8768 | |
| 8769 | let mut wrong_endpoint = client.clone(); |
| 8770 | wrong_endpoint.base_url = "https://other.example.test/v1".into(); |
| 8771 | assert_eq!(wrong_endpoint.declared_wire_model(model), None); |
| 8772 | assert_ne!(wrong_endpoint.effective_max_output_tokens(model), 32); |
| 8773 | let mut wrong_identity = client; |
| 8774 | wrong_identity.admitted_identity.key = "other-provider".into(); |
| 8775 | assert_eq!(wrong_identity.declared_wire_model(model), None); |
| 8776 | } |
| 8777 | |
| 8778 | #[test] |
| 8779 | fn declaration_does_not_open_opencode_go_protocol_roster() { |
| 8780 | let _env = crate::test_support::lock_test_env(); |
| 8781 | let mut config = config(); |
| 8782 | config.provider = Some("opencode-go".into()); |
| 8783 | config.providers.as_mut().unwrap().opencode_go = ProviderConfig { |
| 8784 | api_key: Some("configured-model-local-fixture".into()), |
| 8785 | ..ProviderConfig::default() |
| 8786 | }; |
| 8787 | let base_url = ProviderKind::OpencodeGo.provider().default_base_url(); |
| 8788 | let declaration = &mut config.custom_models.as_mut().unwrap()[0]; |
| 8789 | declaration.provider = "opencode-go".into(); |
| 8790 | declaration.base_url = base_url.into(); |
| 8791 | declaration.id = "claude-sonnet-unproven".into(); |
| 8792 | let client = CodewhaleClient::from_parts( |
| 8793 | base_url.into(), |
| 8794 | config.default_model(), |
| 8795 | WireFormat::ChatCompletions, |
| 8796 | None, |
| 8797 | None, |
| 8798 | false, |
| 8799 | &config, |
| 8800 | ) |
| 8801 | .unwrap(); |
| 8802 | assert_eq!(client.declared_wire_model("claude-sonnet-unproven"), None); |
| 8803 | assert!( |
| 8804 | client |
| 8805 | .rebound_for_model_protocol(None, "claude-sonnet-unproven") |
| 8806 | .is_err() |
| 8807 | ); |
| 8808 | assert!( |
| 8809 | client |
| 8810 | .prepare_outbound_request( |
| 8811 | translation_message_request( |
| 8812 | "hello", |
| 8813 | "claude-sonnet-unproven".into(), |
| 8814 | "English", |
| 8815 | 64 |
| 8816 | ), |
| 8817 | false, |
| 8818 | ) |
| 8819 | .is_err() |
| 8820 | ); |
| 8821 | } |
| 8822 | } |
| 8823 | |
| 8824 | #[cfg(test)] |
| 8825 | mod openrouter_vendor_tests { |
| 8826 | use super::*; |
| 8827 | use codewhale_config::catalog::reviewed::constants::OPENROUTER_QWEN_3_6_FLASH_MODEL; |
| 8828 | use codewhale_runtime::config::{ProviderConfig, ProvidersConfig}; |
| 8829 | use futures_util::StreamExt; |
| 8830 | use wiremock::{Mock, MockServer, ResponseTemplate, matchers::method}; |
| 8831 | |
| 8832 | fn config(base_url: &str, vendor: Option<&str>) -> Config { |
| 8833 | { |
| 8834 | let __cw_config_init_1_0 = Some("openrouter".into()); |
| 8835 | let __cw_config_init_1_1 = Some(ProvidersConfig { |
| 8836 | openrouter: ProviderConfig { |
| 8837 | api_key: Some("vendor-pin-local-fixture".into()), |
| 8838 | base_url: Some(base_url.into()), |
| 8839 | model: Some("deepseek/deepseek-v4-pro".into()), |
| 8840 | vendor: vendor.map(str::to_string), |
| 8841 | ..ProviderConfig::default() |
| 8842 | }, |
| 8843 | ..ProvidersConfig::default() |
| 8844 | }); |
| 8845 | let mut __cw_config_init_1_value: Config = Config::default(); |
| 8846 | __cw_config_init_1_value.provider = __cw_config_init_1_0; |
| 8847 | __cw_config_init_1_value.providers = __cw_config_init_1_1; |
| 8848 | __cw_config_init_1_value |
| 8849 | } |
| 8850 | } |
| 8851 | |
| 8852 | fn request() -> MessageRequest { |
| 8853 | translation_message_request("hello", "deepseek/deepseek-v4-pro".into(), "English", 64) |
| 8854 | } |
| 8855 | |
| 8856 | #[tokio::test] |
| 8857 | async fn openrouter_vendor_is_serialized_on_stream_blocking_and_translation_requests() { |
| 8858 | let _env = crate::test_support::lock_test_env(); |
| 8859 | for streaming in [false, true] { |
| 8860 | let server = MockServer::start().await; |
| 8861 | let response = if streaming { |
| 8862 | ResponseTemplate::new(200) |
| 8863 | .insert_header("content-type", "text/event-stream") |
| 8864 | .set_body_string("data: [DONE]\n\n") |
| 8865 | } else { |
| 8866 | ResponseTemplate::new(200).set_body_json(json!({ |
| 8867 | "id": "chatcmpl-vendor-pin", "object": "chat.completion", |
| 8868 | "model": "deepseek/deepseek-v4-pro", |
| 8869 | "choices": [{"index": 0, "message": {"role": "assistant", "content": "ok"}, "finish_reason": "stop"}], |
| 8870 | "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2} |
| 8871 | })) |
| 8872 | }; |
| 8873 | Mock::given(method("POST")) |
| 8874 | .respond_with(response) |
| 8875 | .expect(if streaming { 1 } else { 2 }) |
| 8876 | .mount(&server) |
| 8877 | .await; |
| 8878 | let client = |
| 8879 | CodewhaleClient::new(&config(&server.uri(), Some("deepinfra/turbo"))).unwrap(); |
| 8880 | let mut input = request(); |
| 8881 | input.stream = Some(streaming); |
| 8882 | let preview = client |
| 8883 | .prepare_outbound_request(input.clone(), streaming) |
| 8884 | .unwrap(); |
| 8885 | if streaming { |
| 8886 | let mut stream = client.create_message_stream(input).await.unwrap(); |
| 8887 | while let Some(event) = stream.next().await { |
| 8888 | event.unwrap(); |
| 8889 | } |
| 8890 | } else { |
| 8891 | client.create_message(input).await.unwrap(); |
| 8892 | assert_eq!( |
| 8893 | client |
| 8894 | .translate("hello", "deepseek/deepseek-v4-pro", "English") |
| 8895 | .await |
| 8896 | .unwrap(), |
| 8897 | "ok" |
| 8898 | ); |
| 8899 | } |
| 8900 | let captured = server.received_requests().await.unwrap(); |
| 8901 | for outbound in &captured { |
| 8902 | let body: Value = serde_json::from_slice(&outbound.body).unwrap(); |
| 8903 | assert_eq!( |
| 8904 | body["provider"], |
| 8905 | json!({"order": ["deepinfra/turbo"], "allow_fallbacks": false}) |
| 8906 | ); |
| 8907 | assert_eq!(body["provider"], preview.body["provider"]); |
| 8908 | assert_eq!(body["model"], "deepseek/deepseek-v4-pro"); |
| 8909 | } |
| 8910 | } |
| 8911 | } |
| 8912 | |
| 8913 | #[test] |
| 8914 | fn openrouter_vendor_freezes_rebinds_and_partitions_cached_requests() { |
| 8915 | let _env = crate::test_support::lock_test_env(); |
| 8916 | let initial = config("https://openrouter.ai/api/v1", Some("deepinfra/turbo")); |
| 8917 | let client = CodewhaleClient::new(&initial).unwrap(); |
| 8918 | let mut updated = initial.clone(); |
| 8919 | updated.providers.as_mut().unwrap().openrouter.vendor = |
| 8920 | Some("another-vendor/region".into()); |
| 8921 | let fresh = CodewhaleClient::new(&updated).unwrap(); |
| 8922 | let rebound = client |
| 8923 | .rebound_for_model_protocol(Some(&updated), OPENROUTER_QWEN_3_6_FLASH_MODEL) |
| 8924 | .unwrap() |
| 8925 | .unwrap(); |
| 8926 | assert_eq!(rebound.openrouter_vendor(), Some("deepinfra/turbo")); |
| 8927 | assert_eq!(client.clone().openrouter_vendor(), Some("deepinfra/turbo")); |
| 8928 | let key = |client: &CodewhaleClient| { |
| 8929 | let body = client |
| 8930 | .prepare_outbound_request(request(), false) |
| 8931 | .unwrap() |
| 8932 | .body; |
| 8933 | codewhale_runtime::llm_response_cache::ResponseCache::make_key( |
| 8934 | "openrouter", |
| 8935 | &client.base_url, |
| 8936 | None, |
| 8937 | &client.api_key, |
| 8938 | &serde_json::to_vec(&body).unwrap(), |
| 8939 | ) |
| 8940 | }; |
| 8941 | assert_ne!(key(&client), key(&fresh)); |
| 8942 | updated.providers.as_mut().unwrap().openrouter.vendor = Some(String::new()); |
| 8943 | let cleared = CodewhaleClient::new(&updated).unwrap(); |
| 8944 | assert!( |
| 8945 | cleared |
| 8946 | .prepare_outbound_request(request(), false) |
| 8947 | .unwrap() |
| 8948 | .body |
| 8949 | .get("provider") |
| 8950 | .is_none() |
| 8951 | ); |
| 8952 | assert_ne!(key(&fresh), key(&cleared)); |
| 8953 | assert_eq!( |
| 8954 | client.turn_route_receipt().openrouter_vendor(), |
| 8955 | Some("deepinfra/turbo") |
| 8956 | ); |
| 8957 | assert!( |
| 8958 | CodewhaleClient::new(&config("https://openrouter.ai/api/v1", Some("bad vendor"))) |
| 8959 | .is_err() |
| 8960 | ); |
| 8961 | updated.provider = Some("openai".into()); |
| 8962 | updated.providers.as_mut().unwrap().openai = ProviderConfig { |
| 8963 | api_key: Some("other-provider-fixture".into()), |
| 8964 | base_url: Some("https://openrouter.ai/api/v1".into()), |
| 8965 | model: Some("deepseek/deepseek-v4-pro".into()), |
| 8966 | ..ProviderConfig::default() |
| 8967 | }; |
| 8968 | let other = CodewhaleClient::new(&updated).unwrap(); |
| 8969 | assert!( |
| 8970 | other |
| 8971 | .prepare_outbound_request(request(), false) |
| 8972 | .unwrap() |
| 8973 | .body |
| 8974 | .get("provider") |
| 8975 | .is_none() |
| 8976 | ); |
| 8977 | } |
| 8978 | |
| 8979 | #[test] |
| 8980 | fn codewhale_catalog_offerings_populates_valid_usd_managed_pricing_and_keeps_byok_unpriced() { |
| 8981 | let fetched_at = chrono::DateTime::parse_from_rfc3339("2026-11-18T00:00:00Z") |
| 8982 | .unwrap() |
| 8983 | .timestamp() as u64; |
| 8984 | let payload = serde_json::json!({ |
| 8985 | "object": "list", |
| 8986 | "data": [ |
| 8987 | { |
| 8988 | "id": "deepseek/deepseek-v4-flash", |
| 8989 | "object": "model", |
| 8990 | "owned_by": "deepseek", |
| 8991 | "codewhale": { |
| 8992 | "provider": "deepseek", |
| 8993 | "model": "deepseek-v4-flash", |
| 8994 | "protocol": "chat-completions", |
| 8995 | "default": true, |
| 8996 | "usable": true, |
| 8997 | "pricing": { |
| 8998 | "currency": "USD", |
| 8999 | "pricingPolicy": "pass_through", |
| 9000 | "ratesMicrosPerMillion": { |
| 9001 | "input": 220_000, |
| 9002 | "cachedInput": 7_000, |
| 9003 | "output": 660_000 |
| 9004 | }, |
| 9005 | "serviceFeeBasisPoints": 0, |
| 9006 | "rateCardRevision": "card-rev-1", |
| 9007 | "checkedAt": "2026-11-17T00:00:00Z", |
| 9008 | "expiresAt": "2026-12-17T00:00:00Z" |
| 9009 | } |
| 9010 | } |
| 9011 | }, |
| 9012 | { |
| 9013 | "id": "anthropic/claude-sonnet-5", |
| 9014 | "object": "model", |
| 9015 | "owned_by": "anthropic", |
| 9016 | "codewhale": { |
| 9017 | "provider": "anthropic", |
| 9018 | "model": "claude-sonnet-5", |
| 9019 | "protocol": "anthropic-messages", |
| 9020 | "pricing": { |
| 9021 | "currency": "usd", |
| 9022 | "ratesMicrosPerMillion": { |
| 9023 | "input": 3_000_000, |
| 9024 | "cacheRead": 300_000, |
| 9025 | "cacheWrite": 3_750_000, |
| 9026 | "output": 15_000_000 |
| 9027 | } |
| 9028 | } |
| 9029 | } |
| 9030 | }, |
| 9031 | { |
| 9032 | "id": "openai/gpt-5.6", |
| 9033 | "object": "model", |
| 9034 | "owned_by": "openai", |
| 9035 | "codewhale": { |
| 9036 | "provider": "openai", |
| 9037 | "model": "gpt-5.6", |
| 9038 | "protocol": "responses", |
| 9039 | "billingMode": "byok_external" |
| 9040 | } |
| 9041 | }, |
| 9042 | { |
| 9043 | "id": "xai/grok-4.6", |
| 9044 | "object": "model" |
| 9045 | } |
| 9046 | ] |
| 9047 | }) |
| 9048 | .to_string(); |
| 9049 | |
| 9050 | let rows = codewhale_catalog_offerings_from_body(&payload, "codewhale", "fp", fetched_at) |
| 9051 | .expect("managed and BYOK listing should parse"); |
| 9052 | assert_eq!(rows.len(), 4); |
| 9053 | |
| 9054 | let flash = rows |
| 9055 | .iter() |
| 9056 | .find(|row| row.wire_model_id == "deepseek/deepseek-v4-flash") |
| 9057 | .unwrap(); |
| 9058 | let flash_cost = flash.cost.as_ref().expect("managed USD pricing"); |
| 9059 | assert_eq!(flash_cost.input, Some(0.22)); |
| 9060 | assert_eq!(flash_cost.cache_read, Some(0.007)); |
| 9061 | assert_eq!(flash_cost.output, Some(0.66)); |
| 9062 | assert_eq!(flash_cost.cache_write, None); |
| 9063 | assert_eq!(flash.cost_source, None); |
| 9064 | |
| 9065 | let sonnet = rows |
| 9066 | .iter() |
| 9067 | .find(|row| row.wire_model_id == "anthropic/claude-sonnet-5") |
| 9068 | .unwrap(); |
| 9069 | let sonnet_cost = sonnet.cost.as_ref().expect("case-insensitive USD pricing"); |
| 9070 | assert_eq!(sonnet_cost.input, Some(3.0)); |
| 9071 | assert_eq!(sonnet_cost.cache_read, Some(0.3)); |
| 9072 | assert_eq!(sonnet_cost.cache_write, Some(3.75)); |
| 9073 | assert_eq!(sonnet_cost.output, Some(15.0)); |
| 9074 | |
| 9075 | for byok_id in ["openai/gpt-5.6", "xai/grok-4.6"] { |
| 9076 | let row = rows |
| 9077 | .iter() |
| 9078 | .find(|row| row.wire_model_id == byok_id) |
| 9079 | .unwrap(); |
| 9080 | assert!(row.cost.is_none()); |
| 9081 | } |
| 9082 | |
| 9083 | let invalid_payload = serde_json::json!({ |
| 9084 | "object": "list", |
| 9085 | "data": [ |
| 9086 | { |
| 9087 | "id": "expired/past", |
| 9088 | "codewhale": { |
| 9089 | "pricing": { |
| 9090 | "currency": "USD", |
| 9091 | "ratesMicrosPerMillion": { "input": 200_000, "output": 600_000 }, |
| 9092 | "expiresAt": "2026-11-17T23:59:59Z" |
| 9093 | } |
| 9094 | } |
| 9095 | }, |
| 9096 | { |
| 9097 | "id": "expired/exact-boundary", |
| 9098 | "codewhale": { |
| 9099 | "pricing": { |
| 9100 | "currency": "USD", |
| 9101 | "ratesMicrosPerMillion": { "input": 200_000, "output": 600_000 }, |
| 9102 | "expiresAt": "2026-11-18T00:00:00Z" |
| 9103 | } |
| 9104 | } |
| 9105 | }, |
| 9106 | { |
| 9107 | "id": "expired/malformed-ts", |
| 9108 | "codewhale": { |
| 9109 | "pricing": { |
| 9110 | "currency": "USD", |
| 9111 | "ratesMicrosPerMillion": { "input": 200_000, "output": 600_000 }, |
| 9112 | "expiresAt": "2026-12-01T00:00:00+08:00" |
| 9113 | } |
| 9114 | } |
| 9115 | }, |
| 9116 | { |
| 9117 | "id": "currency/non-usd", |
| 9118 | "codewhale": { |
| 9119 | "pricing": { |
| 9120 | "currency": "CNY", |
| 9121 | "ratesMicrosPerMillion": { "input": 200_000, "output": 600_000 }, |
| 9122 | "expiresAt": "2026-12-18T00:00:00Z" |
| 9123 | } |
| 9124 | } |
| 9125 | }, |
| 9126 | { |
| 9127 | "id": "rate/negative-input", |
| 9128 | "codewhale": { |
| 9129 | "pricing": { |
| 9130 | "currency": "USD", |
| 9131 | "ratesMicrosPerMillion": { "input": -1, "output": 600_000 } |
| 9132 | } |
| 9133 | } |
| 9134 | }, |
| 9135 | { |
| 9136 | "id": "rate/negative-cache", |
| 9137 | "codewhale": { |
| 9138 | "pricing": { |
| 9139 | "currency": "USD", |
| 9140 | "ratesMicrosPerMillion": { "input": 200_000, "cachedInput": -5, "output": 600_000 } |
| 9141 | } |
| 9142 | } |
| 9143 | }, |
| 9144 | { |
| 9145 | "id": "rate/missing-output", |
| 9146 | "codewhale": { |
| 9147 | "pricing": { |
| 9148 | "currency": "USD", |
| 9149 | "ratesMicrosPerMillion": { "input": 200_000 } |
| 9150 | } |
| 9151 | } |
| 9152 | }, |
| 9153 | { |
| 9154 | "id": "rate/non-object", |
| 9155 | "codewhale": { |
| 9156 | "pricing": "not-an-object" |
| 9157 | } |
| 9158 | } |
| 9159 | ] |
| 9160 | }) |
| 9161 | .to_string(); |
| 9162 | |
| 9163 | let invalid_rows = |
| 9164 | codewhale_catalog_offerings_from_body(&invalid_payload, "codewhale", "fp", fetched_at) |
| 9165 | .expect("invalid pricing must not fail the catalog refresh"); |
| 9166 | assert_eq!(invalid_rows.len(), 8); |
| 9167 | assert!(invalid_rows.iter().all(|row| row.cost.is_none())); |
| 9168 | |
| 9169 | let _env = crate::test_support::lock_test_env(); |
| 9170 | let _live = crate::provider_lake::lock_live_snapshot(); |
| 9171 | let home = tempfile::tempdir().expect("home"); |
| 9172 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", home.path()); |
| 9173 | let _base_override = crate::test_support::EnvVarGuard::remove("CODEWHALE_API_BASE"); |
| 9174 | crate::provider_catalog_live::reset_cache_for_test(); |
| 9175 | crate::provider_lake::clear_live_snapshot(); |
| 9176 | |
| 9177 | let now = chrono::Utc::now(); |
| 9178 | let live_fetched_at = u64::try_from(now.timestamp()).unwrap(); |
| 9179 | let expires_at = |
| 9180 | (now + chrono::Duration::hours(24)).to_rfc3339_opts(chrono::SecondsFormat::Secs, true); |
| 9181 | let base = ProviderKind::Codewhale.provider().default_base_url(); |
| 9182 | let fingerprint = base_url_fingerprint(base); |
| 9183 | let live_payload = serde_json::json!({ |
| 9184 | "object": "list", |
| 9185 | "data": [ |
| 9186 | { |
| 9187 | "id": "deepseek/deepseek-v4-flash", |
| 9188 | "object": "model", |
| 9189 | "codewhale": { |
| 9190 | "protocol": "chat-completions", |
| 9191 | "default": true, |
| 9192 | "pricing": { |
| 9193 | "currency": "USD", |
| 9194 | "pricingPolicy": "pass_through", |
| 9195 | "ratesMicrosPerMillion": { |
| 9196 | "input": 220_000, |
| 9197 | "cachedInput": 7_000, |
| 9198 | "output": 660_000 |
| 9199 | }, |
| 9200 | "expiresAt": expires_at |
| 9201 | } |
| 9202 | } |
| 9203 | }, |
| 9204 | { |
| 9205 | "id": "openai/gpt-5.6", |
| 9206 | "object": "model", |
| 9207 | "codewhale": { |
| 9208 | "protocol": "responses", |
| 9209 | "billingMode": "byok_external" |
| 9210 | } |
| 9211 | } |
| 9212 | ] |
| 9213 | }) |
| 9214 | .to_string(); |
| 9215 | |
| 9216 | let offerings = codewhale_catalog_offerings_from_body( |
| 9217 | &live_payload, |
| 9218 | "codewhale", |
| 9219 | &fingerprint, |
| 9220 | live_fetched_at, |
| 9221 | ) |
| 9222 | .unwrap(); |
| 9223 | crate::provider_catalog_live::record_success(ProviderCatalogDelta { |
| 9224 | provider: "codewhale".to_string(), |
| 9225 | base_url_fingerprint: fingerprint.clone(), |
| 9226 | fetched_at: live_fetched_at, |
| 9227 | offerings, |
| 9228 | }); |
| 9229 | |
| 9230 | let quote = crate::provider_catalog_live::fresh_dispatch_pricing_quote_at( |
| 9231 | ProviderKind::Codewhale, |
| 9232 | "codewhale", |
| 9233 | "deepseek/deepseek-v4-flash", |
| 9234 | base, |
| 9235 | live_fetched_at, |
| 9236 | ) |
| 9237 | .expect("managed row should freeze a live dispatch pricing quote"); |
| 9238 | assert_eq!(quote.input_per_million.as_deref(), Some("0.22")); |
| 9239 | assert_eq!(quote.cache_read_per_million.as_deref(), Some("0.007")); |
| 9240 | assert_eq!(quote.output_per_million.as_deref(), Some("0.66")); |
| 9241 | assert_eq!( |
| 9242 | quote.provenance, |
| 9243 | codewhale_config::pricing::PricingProvenance::ProviderLive |
| 9244 | ); |
| 9245 | |
| 9246 | let usage = codewhale_models::Usage { |
| 9247 | input_tokens: 2_000_000, |
| 9248 | prompt_cache_hit_tokens: Some(1_000_000), |
| 9249 | output_tokens: 1_000_000, |
| 9250 | ..codewhale_models::Usage::default() |
| 9251 | }; |
| 9252 | let surface = |
| 9253 | crate::pricing::billing_surface_for_route(ProviderKind::Codewhale, Some(base)); |
| 9254 | let priced_audit = crate::pricing::audit_turn_cost_for_route_on_endpoint_for_identity_at( |
| 9255 | ProviderKind::Codewhale, |
| 9256 | Some("codewhale"), |
| 9257 | "deepseek/deepseek-v4-flash", |
| 9258 | surface, |
| 9259 | Some(&fingerprint), |
| 9260 | Some("e), |
| 9261 | &usage, |
| 9262 | now, |
| 9263 | ); |
| 9264 | let estimate = priced_audit |
| 9265 | .estimate |
| 9266 | .expect("managed turn should be priced"); |
| 9267 | assert!((estimate.usd - 0.887).abs() < 1e-12, "got {}", estimate.usd); |
| 9268 | |
| 9269 | assert!( |
| 9270 | crate::provider_catalog_live::fresh_dispatch_pricing_quote_at( |
| 9271 | ProviderKind::Codewhale, |
| 9272 | "codewhale", |
| 9273 | "openai/gpt-5.6", |
| 9274 | base, |
| 9275 | live_fetched_at, |
| 9276 | ) |
| 9277 | .is_none() |
| 9278 | ); |
| 9279 | let byok_audit = crate::pricing::audit_turn_cost_for_route_on_endpoint_for_identity_at( |
| 9280 | ProviderKind::Codewhale, |
| 9281 | Some("codewhale"), |
| 9282 | "openai/gpt-5.6", |
| 9283 | surface, |
| 9284 | Some(&fingerprint), |
| 9285 | None, |
| 9286 | &usage, |
| 9287 | now, |
| 9288 | ); |
| 9289 | assert!(byok_audit.estimate.is_none()); |
| 9290 | |
| 9291 | crate::provider_catalog_live::reset_cache_for_test(); |
| 9292 | crate::provider_lake::clear_live_snapshot(); |
| 9293 | } |
| 9294 | } |
| 9295 |