| 1 | //! Model selection and auto-routing. |
| 2 | //! |
| 3 | //! The CLI, TUI, runtime threads, subagents, and command handlers all need |
| 4 | //! this behavior, so it intentionally lives outside the command tree. |
| 5 | |
| 6 | use std::collections::BTreeMap; |
| 7 | use std::time::{Duration, Instant}; |
| 8 | |
| 9 | use anyhow::Result; |
| 10 | use serde::{Deserialize, Serialize}; |
| 11 | |
| 12 | use crate::client::CodewhaleClient; |
| 13 | use crate::client::system_one::{DecisionRouterRoute, SystemOneAnswer, SystemOneResponse}; |
| 14 | use crate::cost_status::{EffectiveRouteEnvelope, RuntimeUsageDropRecord, RuntimeUsageRecord}; |
| 15 | use crate::llm_client::LlmClient; |
| 16 | use crate::model_inventory::{ModelInventory, probability_bp}; |
| 17 | use crate::reasoning_preference::ReasoningEffort; |
| 18 | use codewhale_config::ProviderKind; |
| 19 | use codewhale_models::auto_route_evidence::AutoRouteDecisionEvidence; |
| 20 | use codewhale_models::{ContentBlock, Message, MessageRequest, MessageResponse, SystemPrompt}; |
| 21 | use codewhale_models::{Role, Usage}; |
| 22 | use codewhale_runtime::config::{AutoRouterKind, Config, ProviderIdentity}; |
| 23 | |
| 24 | /// Big/cheap model pair the auto-router may choose between for the active |
| 25 | /// provider (#3018). |
| 26 | /// |
| 27 | /// `cheap == None` means the provider has no known cheap tier: the local |
| 28 | /// fallback stays on the current model (only thinking effort varies) and the |
| 29 | /// network router is skipped entirely (#1549). |
| 30 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 31 | pub struct RouterCandidates { |
| 32 | pub big: String, |
| 33 | pub cheap: Option<String>, |
| 34 | } |
| 35 | |
| 36 | impl RouterCandidates { |
| 37 | pub fn deepseek() -> Self { |
| 38 | Self { |
| 39 | big: "deepseek-v4-pro".to_string(), |
| 40 | cheap: Some("deepseek-flash".to_string()), |
| 41 | } |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | /// Return a provider-owned strong/fast pair for model families whose catalog |
| 46 | /// exposes more than one tier. The ids here are deliberately explicit: a |
| 47 | /// model name alone is not evidence that another provider can serve its |
| 48 | /// sibling, so unknown providers and unknown families remain single-tier. |
| 49 | fn catalog_family_candidates( |
| 50 | provider: ProviderKind, |
| 51 | current_model: &str, |
| 52 | ) -> Option<RouterCandidates> { |
| 53 | let normalized = codewhale_config::route::resolve_model(provider, current_model, None) |
| 54 | .map_or_else( |
| 55 | |_| current_model.trim().to_string(), |
| 56 | |resolved| resolved.wire_id, |
| 57 | ); |
| 58 | let lower = normalized.to_ascii_lowercase(); |
| 59 | |
| 60 | let cheap = match provider { |
| 61 | ProviderKind::Openai | ProviderKind::OpenaiCodex |
| 62 | if matches!(lower.as_str(), "gpt-5.6" | "gpt-5.6-sol" | "gpt-5.6-terra") => |
| 63 | { |
| 64 | Some("gpt-5.6-luna".to_string()) |
| 65 | } |
| 66 | ProviderKind::Anthropic |
| 67 | if matches!( |
| 68 | lower.as_str(), |
| 69 | "claude-opus-4-8" |
| 70 | | "claude-sonnet-4-6" |
| 71 | | "claude-sonnet-5" |
| 72 | | "claude-opus-5-5" |
| 73 | | "claude-sonnet-5-5" |
| 74 | ) => |
| 75 | { |
| 76 | Some("claude-haiku-4-5".to_string()) |
| 77 | } |
| 78 | ProviderKind::XiaomiMimo if lower == "mimo-v2.6-pro" => Some("mimo-v2.6-flash".to_string()), |
| 79 | ProviderKind::Arcee |
| 80 | if matches!( |
| 81 | lower.as_str(), |
| 82 | "trinity-large-thinking" | "trinity-large-preview" |
| 83 | ) => |
| 84 | { |
| 85 | Some("trinity-mini".to_string()) |
| 86 | } |
| 87 | ProviderKind::Moonshot if lower == "kimi-k2.7-code" => Some("kimi-k2.6".to_string()), |
| 88 | ProviderKind::Minimax | ProviderKind::MinimaxAnthropic if lower == "minimax-m2.7" => { |
| 89 | Some("MiniMax-M2.7-highspeed".to_string()) |
| 90 | } |
| 91 | ProviderKind::OpencodeGo if lower == "kimi-k3" => Some("kimi-k2.7-code".to_string()), |
| 92 | ProviderKind::Openrouter |
| 93 | if lower == "qwen/qwen3.6-max-preview" |
| 94 | || lower == "qwen/qwen3.6-plus" |
| 95 | || lower == "qwen/qwen3.6-27b" |
| 96 | || lower == "qwen/qwen3.6-35b-a3b" => |
| 97 | { |
| 98 | Some("qwen/qwen3.6-flash".to_string()) |
| 99 | } |
| 100 | ProviderKind::Openrouter if lower == "xiaomi/mimo-v2.5-pro" => { |
| 101 | Some("xiaomi/mimo-v2.5".to_string()) |
| 102 | } |
| 103 | ProviderKind::Openrouter |
| 104 | if matches!( |
| 105 | lower.as_str(), |
| 106 | "arcee-ai/trinity-large-thinking" | "arcee-ai/trinity-large-preview" |
| 107 | ) => |
| 108 | { |
| 109 | Some("arcee-ai/trinity-mini".to_string()) |
| 110 | } |
| 111 | ProviderKind::Openrouter if lower == "moonshotai/kimi-k2.7-code" => { |
| 112 | Some("moonshotai/kimi-k2.6".to_string()) |
| 113 | } |
| 114 | ProviderKind::Openrouter |
| 115 | if lower == "anthropic/claude-opus-4-8" |
| 116 | || lower == "anthropic/claude-sonnet-4-6" |
| 117 | || lower == "anthropic/claude-sonnet-5" => |
| 118 | { |
| 119 | Some("anthropic/claude-haiku-4-5".to_string()) |
| 120 | } |
| 121 | _ => None, |
| 122 | }?; |
| 123 | |
| 124 | Some(RouterCandidates { |
| 125 | big: normalized, |
| 126 | cheap: Some(cheap), |
| 127 | }) |
| 128 | } |
| 129 | |
| 130 | /// Derive the auto-router's candidate pair for the active provider (#3018). |
| 131 | /// |
| 132 | /// DeepSeek providers route between the canonical pro/flash pair. Hosted |
| 133 | /// routes with known wire ids for that pair (NVIDIA NIM, OpenRouter, Novita, |
| 134 | /// SiliconFlow, SGLang, vLLM, Wanjie Ark, Volcengine) use their provider |
| 135 | /// spellings. Every other provider has no known cheap tier: `big` is the |
| 136 | /// session model and `cheap` is `None`, so auto mode never fabricates a |
| 137 | /// DeepSeek id for a provider that cannot serve it. |
| 138 | pub fn provider_router_candidates( |
| 139 | provider: codewhale_config::ProviderKind, |
| 140 | current_model: &str, |
| 141 | ) -> RouterCandidates { |
| 142 | use codewhale_config::ProviderKind; |
| 143 | if let Some(candidates) = catalog_family_candidates(provider, current_model) { |
| 144 | return candidates; |
| 145 | } |
| 146 | |
| 147 | if provider == ProviderKind::Zai { |
| 148 | let normalized = codewhale_config::route::resolve_model(provider, current_model, None) |
| 149 | .map_or_else(|_| current_model.to_string(), |resolved| resolved.wire_id); |
| 150 | return RouterCandidates { |
| 151 | cheap: if normalized |
| 152 | == codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_3_MODEL |
| 153 | { |
| 154 | Some( |
| 155 | codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_3_FLASH_MODEL |
| 156 | .to_string(), |
| 157 | ) |
| 158 | } else if normalized |
| 159 | == codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_2_MODEL |
| 160 | { |
| 161 | Some( |
| 162 | codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_TURBO_MODEL |
| 163 | .to_string(), |
| 164 | ) |
| 165 | } else { |
| 166 | None |
| 167 | }, |
| 168 | big: normalized, |
| 169 | }; |
| 170 | } |
| 171 | |
| 172 | if provider == ProviderKind::Openrouter |
| 173 | && let Ok(resolved) = codewhale_config::route::resolve_model(provider, current_model, None) |
| 174 | && matches!( |
| 175 | resolved.wire_id.as_str(), |
| 176 | codewhale_config::catalog::reviewed::constants::OPENROUTER_GLM_5_1_MODEL |
| 177 | | codewhale_config::catalog::reviewed::constants::OPENROUTER_GLM_5_2_MODEL |
| 178 | | codewhale_config::catalog::reviewed::constants::OPENROUTER_GLM_5_3_MODEL |
| 179 | | codewhale_config::catalog::reviewed::constants::OPENROUTER_GLM_5_3_FLASH_MODEL |
| 180 | | codewhale_config::catalog::reviewed::constants::OPENROUTER_GLM_5_TURBO_MODEL |
| 181 | ) |
| 182 | { |
| 183 | let normalized = resolved.wire_id; |
| 184 | return RouterCandidates { |
| 185 | cheap: if normalized |
| 186 | == codewhale_config::catalog::reviewed::constants::OPENROUTER_GLM_5_3_MODEL |
| 187 | { |
| 188 | Some( |
| 189 | codewhale_config::catalog::reviewed::constants::OPENROUTER_GLM_5_3_FLASH_MODEL |
| 190 | .to_string(), |
| 191 | ) |
| 192 | } else if normalized |
| 193 | == codewhale_config::catalog::reviewed::constants::OPENROUTER_GLM_5_2_MODEL |
| 194 | { |
| 195 | Some( |
| 196 | codewhale_config::catalog::reviewed::constants::OPENROUTER_GLM_5_TURBO_MODEL |
| 197 | .to_string(), |
| 198 | ) |
| 199 | } else { |
| 200 | None |
| 201 | }, |
| 202 | big: normalized, |
| 203 | }; |
| 204 | } |
| 205 | |
| 206 | match provider { |
| 207 | ProviderKind::Deepseek => RouterCandidates::deepseek(), |
| 208 | ProviderKind::NvidiaNim |
| 209 | | ProviderKind::Openrouter |
| 210 | | ProviderKind::Novita |
| 211 | | ProviderKind::Siliconflow |
| 212 | | ProviderKind::SiliconflowCN |
| 213 | | ProviderKind::Sglang |
| 214 | | ProviderKind::Vllm |
| 215 | | ProviderKind::WanjieArk |
| 216 | if current_model.to_ascii_lowercase().contains("deepseek") => |
| 217 | { |
| 218 | RouterCandidates { |
| 219 | big: codewhale_config::route::resolve_model(provider, "deepseek-v4-pro", None) |
| 220 | .map_or_else( |
| 221 | |_| "deepseek-v4-pro".to_string(), |
| 222 | |resolved| resolved.wire_id, |
| 223 | ), |
| 224 | cheap: Some( |
| 225 | codewhale_config::route::resolve_model(provider, "deepseek-v4-flash", None) |
| 226 | .map_or_else( |
| 227 | |_| "deepseek-v4-flash".to_string(), |
| 228 | |resolved| resolved.wire_id, |
| 229 | ), |
| 230 | ), |
| 231 | } |
| 232 | } |
| 233 | ProviderKind::Volcengine if current_model.to_ascii_lowercase().contains("deepseek") => { |
| 234 | RouterCandidates { |
| 235 | big: codewhale_config::descriptors::defaults::DEFAULT_VOLCENGINE_MODEL.to_string(), |
| 236 | cheap: Some( |
| 237 | codewhale_config::descriptors::defaults::DEFAULT_VOLCENGINE_FLASH_MODEL |
| 238 | .to_string(), |
| 239 | ), |
| 240 | } |
| 241 | } |
| 242 | _ => RouterCandidates { |
| 243 | big: current_model.to_string(), |
| 244 | cheap: None, |
| 245 | }, |
| 246 | } |
| 247 | } |
| 248 | |
| 249 | /// The loud half of `RouterCandidates::cheap == None`. |
| 250 | /// |
| 251 | /// `None` is a legitimate answer for a pair this router knows to be |
| 252 | /// single-tier, and a misconfiguration for a pair it has never heard of; both |
| 253 | /// land the child on the parent model at the parent's price. A caller that was |
| 254 | /// asked for a fast lane attaches this where the route is shown, so |
| 255 | /// `Faster`/`Auto` never resolves to full price without saying so. |
| 256 | #[must_use] |
| 257 | pub fn missing_fast_sibling_note(provider: ProviderKind, model: &str) -> String { |
| 258 | // The model id is bounded so an absurd route cannot crowd the receipt it |
| 259 | // travels on (`ChildRouteReceipt::fallback_note`, 1 KiB gate). |
| 260 | let model: String = model.trim().chars().take(64).collect(); |
| 261 | format!( |
| 262 | "no cheap sibling for {}/{}; the child runs on the parent model at parent price — pin a child model to choose", |
| 263 | provider.as_str(), |
| 264 | model |
| 265 | ) |
| 266 | } |
| 267 | |
| 268 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 269 | pub enum AutoRouteSource { |
| 270 | FlashRouter, |
| 271 | Heuristic, |
| 272 | } |
| 273 | |
| 274 | impl AutoRouteSource { |
| 275 | #[must_use] |
| 276 | pub fn label(self) -> &'static str { |
| 277 | match self { |
| 278 | AutoRouteSource::FlashRouter => "classifier", |
| 279 | AutoRouteSource::Heuristic => "heuristic", |
| 280 | } |
| 281 | } |
| 282 | } |
| 283 | |
| 284 | /// Provider-safe tier reported for the concrete Auto route. |
| 285 | /// |
| 286 | /// `Selected` is deliberately neutral: a classifier may choose a runnable |
| 287 | /// inventory model that is not part of a known strong/fast pair, and the UI |
| 288 | /// must not invent a tier from the model id. |
| 289 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] |
| 290 | #[serde(rename_all = "snake_case")] |
| 291 | pub enum AutoRouteTier { |
| 292 | Strong, |
| 293 | Fast, |
| 294 | Only, |
| 295 | Selected, |
| 296 | } |
| 297 | |
| 298 | impl AutoRouteTier { |
| 299 | #[must_use] |
| 300 | pub fn label(self) -> &'static str { |
| 301 | match self { |
| 302 | Self::Strong => "strong", |
| 303 | Self::Fast => "fast", |
| 304 | Self::Only => "only model", |
| 305 | Self::Selected => "selected", |
| 306 | } |
| 307 | } |
| 308 | } |
| 309 | |
| 310 | /// Scope from which the concrete Auto route was selected. |
| 311 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] |
| 312 | #[serde(rename_all = "snake_case")] |
| 313 | pub enum AutoRouteScope { |
| 314 | /// The network classifier could choose any runnable provider/model pair in |
| 315 | /// the redacted inventory. Only reachable under the persisted |
| 316 | /// `[auto] cross_provider = true` opt-in (#4411). |
| 317 | RunnableProviders, |
| 318 | /// The network classifier saw only the active provider's runnable routes — |
| 319 | /// the default Auto scope (#4411). |
| 320 | ActiveProvider, |
| 321 | /// The local declared fallback selected within one resolved route. |
| 322 | ResolvedProvider, |
| 323 | } |
| 324 | |
| 325 | impl AutoRouteScope { |
| 326 | #[must_use] |
| 327 | pub fn label(self) -> &'static str { |
| 328 | match self { |
| 329 | Self::RunnableProviders => "runnable providers", |
| 330 | Self::ActiveProvider => "active provider only", |
| 331 | Self::ResolvedProvider => "resolved provider", |
| 332 | } |
| 333 | } |
| 334 | } |
| 335 | |
| 336 | /// Non-secret data path used to make an Auto decision. |
| 337 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 338 | pub enum AutoRouteDataPath { |
| 339 | LocalHeuristic, |
| 340 | Classifier { |
| 341 | provider: codewhale_config::route::ProviderId, |
| 342 | provider_kind: ProviderKind, |
| 343 | model: String, |
| 344 | }, |
| 345 | /// A System One decision model (#6525). Additive: older binaries cannot |
| 346 | /// read a session that persisted this variant. |
| 347 | Decision { |
| 348 | route: DecisionRouterRoute, |
| 349 | model: String, |
| 350 | }, |
| 351 | } |
| 352 | |
| 353 | // Persistence/source facts only. Deserializing this projection never admits a route. |
| 354 | #[derive(Serialize, Deserialize)] |
| 355 | #[serde(rename_all = "snake_case")] |
| 356 | enum AutoRouteDataPathWire { |
| 357 | LocalHeuristic, |
| 358 | Classifier { |
| 359 | provider: String, |
| 360 | model: String, |
| 361 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 362 | provider_id: Option<String>, |
| 363 | }, |
| 364 | Decision { |
| 365 | route: DecisionRouterRoute, |
| 366 | model: String, |
| 367 | }, |
| 368 | } |
| 369 | impl Serialize for AutoRouteDataPath { |
| 370 | fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { |
| 371 | let wire = match self { |
| 372 | Self::LocalHeuristic => AutoRouteDataPathWire::LocalHeuristic, |
| 373 | Self::Decision { route, model } => AutoRouteDataPathWire::Decision { |
| 374 | route: *route, |
| 375 | model: model.clone(), |
| 376 | }, |
| 377 | Self::Classifier { |
| 378 | provider, |
| 379 | provider_kind, |
| 380 | model, |
| 381 | } => { |
| 382 | let tag = codewhale_config::descriptors::tui_wire_tag_for_route( |
| 383 | *provider_kind, |
| 384 | provider.as_str(), |
| 385 | ) |
| 386 | .ok_or_else(|| { |
| 387 | serde::ser::Error::custom("contradictory classifier source identity") |
| 388 | })?; |
| 389 | AutoRouteDataPathWire::Classifier { |
| 390 | provider: tag.into(), |
| 391 | model: model.clone(), |
| 392 | provider_id: (*provider_kind == ProviderKind::Custom |
| 393 | && provider.as_str() != "custom") |
| 394 | .then(|| provider.to_string()), |
| 395 | } |
| 396 | } |
| 397 | }; |
| 398 | wire.serialize(serializer) |
| 399 | } |
| 400 | } |
| 401 | impl<'de> Deserialize<'de> for AutoRouteDataPath { |
| 402 | fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { |
| 403 | Ok(match AutoRouteDataPathWire::deserialize(deserializer)? { |
| 404 | AutoRouteDataPathWire::LocalHeuristic => Self::LocalHeuristic, |
| 405 | AutoRouteDataPathWire::Decision { route, model } => Self::Decision { route, model }, |
| 406 | AutoRouteDataPathWire::Classifier { |
| 407 | provider, |
| 408 | model, |
| 409 | provider_id, |
| 410 | } => { |
| 411 | let row = codewhale_config::descriptors::compatibility_from_wire_tag(&provider) |
| 412 | .ok_or_else(|| { |
| 413 | serde::de::Error::custom("unknown classifier source identity") |
| 414 | })?; |
| 415 | let id = provider_id.as_deref().unwrap_or(row.id); |
| 416 | let kind = codewhale_config::descriptors::kind_from_tui_wire_tag(&provider, id) |
| 417 | .ok_or_else(|| { |
| 418 | serde::de::Error::custom("contradictory classifier source identity") |
| 419 | })?; |
| 420 | Self::Classifier { |
| 421 | provider: id.into(), |
| 422 | provider_kind: kind, |
| 423 | model, |
| 424 | } |
| 425 | } |
| 426 | }) |
| 427 | } |
| 428 | } |
| 429 | |
| 430 | impl AutoRouteDataPath { |
| 431 | #[must_use] |
| 432 | pub fn label(&self) -> String { |
| 433 | match self { |
| 434 | Self::LocalHeuristic => "local only (no router request)".to_string(), |
| 435 | Self::Classifier { |
| 436 | provider, |
| 437 | provider_kind, |
| 438 | model, |
| 439 | } => format!( |
| 440 | "latest request + bounded recent context -> {} / {model}", |
| 441 | codewhale_config::descriptors::compatibility_for_id(provider.as_str()) |
| 442 | .filter(|row| row.kind == *provider_kind) |
| 443 | .map_or(provider.as_str(), |row| row.label) |
| 444 | ), |
| 445 | Self::Decision { route, model } => format!( |
| 446 | "latest request + bounded recent context -> {} / {model} (decision model)", |
| 447 | route.display_name() |
| 448 | ), |
| 449 | } |
| 450 | } |
| 451 | } |
| 452 | |
| 453 | /// Local signal that selected the provider-safe strong/fast candidate. |
| 454 | /// |
| 455 | /// Since the #6290 rework the local fallback never judges request content: |
| 456 | /// without the flash classifier there is no per-request signal, so the route |
| 457 | /// is the configured default (or the runnable fast sibling under the explicit |
| 458 | /// `[auto] cost_saving` opt-in). The content-derived variants below are never |
| 459 | /// constructed for new routes; they are retained so saved sessions from before |
| 460 | /// the rework still deserialize. |
| 461 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] |
| 462 | #[serde(rename_all = "snake_case")] |
| 463 | pub enum AutoRouteHeuristicReason { |
| 464 | /// Legacy: the deleted keyword/length classifier judged the request |
| 465 | /// complex. Retained for saved-session serde compat only. |
| 466 | ComplexRequest, |
| 467 | /// Legacy: the deleted length rule judged the request short. Retained |
| 468 | /// for saved-session serde compat only. |
| 469 | ShortRequest, |
| 470 | /// Legacy: the deleted length rule judged the request long. Retained |
| 471 | /// for saved-session serde compat only. |
| 472 | LongRequest, |
| 473 | CostSavingPolicy, |
| 474 | /// Legacy: the deleted classifier judged the request routine. Retained |
| 475 | /// for saved-session serde compat only. |
| 476 | RoutineRequest, |
| 477 | NoFastSibling, |
| 478 | NoRunnableCandidate, |
| 479 | /// The configured default model: no classifier was available and no |
| 480 | /// content signal was consulted. |
| 481 | DeclaredDefault, |
| 482 | /// A decision router answered below `[auto.router] min_confidence`. |
| 483 | LowConfidence, |
| 484 | } |
| 485 | |
| 486 | impl AutoRouteHeuristicReason { |
| 487 | #[must_use] |
| 488 | fn label(self) -> &'static str { |
| 489 | match self { |
| 490 | Self::ComplexRequest => "complex request", |
| 491 | Self::ShortRequest => "short request", |
| 492 | Self::LongRequest => "long request", |
| 493 | Self::CostSavingPolicy => "cost-saving policy", |
| 494 | Self::RoutineRequest => "routine request", |
| 495 | Self::NoFastSibling => "no runnable fast sibling", |
| 496 | Self::NoRunnableCandidate => "no runnable inventory candidate", |
| 497 | Self::DeclaredDefault => "configured default (no classifier)", |
| 498 | Self::LowConfidence => "decision confidence below threshold", |
| 499 | } |
| 500 | } |
| 501 | } |
| 502 | |
| 503 | /// Why the route was selected. Classifier failures are intentionally |
| 504 | /// collapsed to a non-secret reason; provider errors and response bodies must |
| 505 | /// never enter diagnostics. |
| 506 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] |
| 507 | #[serde(rename_all = "snake_case")] |
| 508 | pub enum AutoRouteReason { |
| 509 | ClassifierRecommendation, |
| 510 | /// The `local_heuristic` alias keeps sessions saved before the #6290 |
| 511 | /// rework loadable; new sessions persist `local_fallback`. |
| 512 | #[serde(alias = "local_heuristic")] |
| 513 | LocalFallback(AutoRouteHeuristicReason), |
| 514 | ClassifierFallback(AutoRouteHeuristicReason), |
| 515 | } |
| 516 | |
| 517 | impl AutoRouteReason { |
| 518 | #[must_use] |
| 519 | pub fn label(self) -> String { |
| 520 | match self { |
| 521 | Self::ClassifierRecommendation => "classifier recommendation".to_string(), |
| 522 | Self::LocalFallback(reason) => format!("local fallback: {}", reason.label()), |
| 523 | Self::ClassifierFallback(reason) => { |
| 524 | format!("classifier fallback: {}", reason.label()) |
| 525 | } |
| 526 | } |
| 527 | } |
| 528 | } |
| 529 | |
| 530 | /// Effective provider-scoped model pair used to classify the selected tier. |
| 531 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 532 | pub struct AutoRoutePair { |
| 533 | pub strong: String, |
| 534 | pub fast: Option<String>, |
| 535 | } |
| 536 | |
| 537 | /// Per-turn Auto routing diagnostics. Provider/model identity remains owned by |
| 538 | /// the authoritative runtime `TurnRoute`; this receipt only records how the |
| 539 | /// concrete route was chosen. |
| 540 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 541 | pub struct AutoRouteReceipt { |
| 542 | pub tier: AutoRouteTier, |
| 543 | pub pair: AutoRoutePair, |
| 544 | pub scope: AutoRouteScope, |
| 545 | pub data_path: AutoRouteDataPath, |
| 546 | pub reason: AutoRouteReason, |
| 547 | /// Decision-model evidence (#6525); absent for chat routers and for |
| 548 | /// sessions saved before it existed. |
| 549 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 550 | pub decision: Option<AutoRouteDecisionEvidence>, |
| 551 | /// Why a configured router did not produce this route. Set by both router |
| 552 | /// kinds, so a configured-but-failing router is shown as failing. |
| 553 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 554 | pub router_failure: Option<AutoRouterFailure>, |
| 555 | } |
| 556 | |
| 557 | /// Non-secret failure class for a configured router. Provider error bodies |
| 558 | /// never enter this type. |
| 559 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] |
| 560 | #[serde(rename_all = "snake_case", tag = "kind")] |
| 561 | pub enum AutoRouterFailure { |
| 562 | /// Declared but unusable: missing key, unknown kind, or client setup. |
| 563 | NotRunnable, |
| 564 | Timeout, |
| 565 | Cancelled, |
| 566 | Http { |
| 567 | status: u16, |
| 568 | }, |
| 569 | QuotaExhausted, |
| 570 | /// The provider rejected the request (model, size, or policy). |
| 571 | Rejected, |
| 572 | Transport, |
| 573 | /// The response could not be decoded or failed validation. |
| 574 | InvalidAnswer, |
| 575 | } |
| 576 | |
| 577 | impl AutoRouterFailure { |
| 578 | #[must_use] |
| 579 | pub fn label(self) -> String { |
| 580 | match self { |
| 581 | Self::NotRunnable => { |
| 582 | "not runnable (check the router key and [auto.router])".to_string() |
| 583 | } |
| 584 | Self::Timeout => "timed out".to_string(), |
| 585 | Self::Cancelled => "cancelled".to_string(), |
| 586 | Self::Http { status } => format!("HTTP {status}"), |
| 587 | Self::QuotaExhausted => "provider quota or credits exhausted".to_string(), |
| 588 | Self::Rejected => "request rejected by the provider".to_string(), |
| 589 | Self::Transport => "network error".to_string(), |
| 590 | Self::InvalidAnswer => "invalid answer".to_string(), |
| 591 | } |
| 592 | } |
| 593 | } |
| 594 | |
| 595 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 596 | pub struct AutoRouteSelection { |
| 597 | pub provider: ProviderIdentity, |
| 598 | pub model: String, |
| 599 | pub reasoning_effort: Option<ReasoningEffort>, |
| 600 | pub source: AutoRouteSource, |
| 601 | /// Present for Auto decisions; explicit inventory lookups intentionally do |
| 602 | /// not pretend to be Auto routing receipts. |
| 603 | pub receipt: Option<AutoRouteReceipt>, |
| 604 | /// Provider calls made to choose this route. These are deliberately kept |
| 605 | /// separate from the selected parent route: a classifier may run on a |
| 606 | /// different provider/model/quote, so pricing it under the eventual turn |
| 607 | /// would double-charge the parent and lose the classifier's real route. |
| 608 | /// |
| 609 | /// Auto currently admits at most one classifier request per selection. |
| 610 | pub routed_usage: Vec<RuntimeUsageRecord>, |
| 611 | /// Exact frozen routes for admitted classifier calls whose provider |
| 612 | /// response omitted usage. The count below remains authoritative and may |
| 613 | /// exceed this bounded vector after overflow. |
| 614 | pub routed_usage_drop_records: Vec<RuntimeUsageDropRecord>, |
| 615 | /// Classifier requests admitted to dispatch whose response usage could not |
| 616 | /// be recovered (timeout/transport failure). Consumers must surface this |
| 617 | /// as incomplete coverage rather than silently treating it as zero spend. |
| 618 | pub routed_usage_dropped_records: u64, |
| 619 | } |
| 620 | |
| 621 | fn extract_first_json_object(raw: &str) -> Option<&str> { |
| 622 | let start = raw.find('{')?; |
| 623 | let end = raw.rfind('}')?; |
| 624 | (end >= start).then_some(&raw[start..=end]) |
| 625 | } |
| 626 | |
| 627 | fn parse_auto_route_reasoning_effort(effort: &str) -> Option<ReasoningEffort> { |
| 628 | ReasoningEffort::parse_strict(effort).ok() |
| 629 | } |
| 630 | |
| 631 | /// Normalize an Auto-route effort when only the provider is known. |
| 632 | /// |
| 633 | /// This delegates to the one authoritative normalizer, |
| 634 | /// [`ReasoningEffort::normalize_for_route`], with an unresolved route (empty |
| 635 | /// endpoint and wire model), so the Auto path cannot carry a second copy of |
| 636 | /// the historic `low | medium -> high` provider collapse (Slice 4, D2). |
| 637 | #[must_use] |
| 638 | pub fn normalize_auto_route_effort_for_provider( |
| 639 | provider: ProviderKind, |
| 640 | effort: ReasoningEffort, |
| 641 | ) -> ReasoningEffort { |
| 642 | effort.normalize_for_route(provider, "", "") |
| 643 | } |
| 644 | |
| 645 | /// Select the reasoning request that accompanies an Auto-model route. |
| 646 | /// |
| 647 | /// Model routing and reasoning routing are independent. An explicit fixed |
| 648 | /// preference wins over the classifier's suggestion; an absent preference or |
| 649 | /// explicit `Auto` keeps reasoning under per-prompt control. |
| 650 | #[must_use] |
| 651 | pub fn resolve_auto_model_reasoning( |
| 652 | preference: Option<ReasoningEffort>, |
| 653 | routed: Option<ReasoningEffort>, |
| 654 | ) -> (Option<ReasoningEffort>, bool) { |
| 655 | match preference { |
| 656 | Some( |
| 657 | effort @ (ReasoningEffort::Off |
| 658 | | ReasoningEffort::Minimal |
| 659 | | ReasoningEffort::Low |
| 660 | | ReasoningEffort::Medium |
| 661 | | ReasoningEffort::High |
| 662 | | ReasoningEffort::XHigh |
| 663 | | ReasoningEffort::Ultra |
| 664 | | ReasoningEffort::Max), |
| 665 | ) => (Some(effort), false), |
| 666 | None | Some(ReasoningEffort::Auto) => (routed, true), |
| 667 | } |
| 668 | } |
| 669 | |
| 670 | /// Route-aware equivalent of [`normalize_auto_route_effort_for_provider`]. |
| 671 | /// The inventory knows the selected provider/model, and the route resolver |
| 672 | /// supplies the endpoint needed to distinguish Kimi Code's official bare-K3 |
| 673 | /// contract from generic Moonshot. |
| 674 | #[must_use] |
| 675 | pub fn normalize_auto_route_effort_for_configured_route( |
| 676 | config: &Config, |
| 677 | identity: &ProviderIdentity, |
| 678 | model: &str, |
| 679 | effort: ReasoningEffort, |
| 680 | ) -> ReasoningEffort { |
| 681 | crate::route_runtime::resolve_runtime_route_for_identity(config, identity, Some(model)) |
| 682 | .map(|route| { |
| 683 | effort.normalize_for_route_identity( |
| 684 | identity.provider, |
| 685 | identity.key.as_str(), |
| 686 | &route.candidate.endpoint().base_url, |
| 687 | &route.model, |
| 688 | ) |
| 689 | }) |
| 690 | .unwrap_or_else(|_| normalize_auto_route_effort_for_provider(identity.provider, effort)) |
| 691 | } |
| 692 | |
| 693 | fn normalize_auto_route_selection_for_config( |
| 694 | config: &Config, |
| 695 | mut selection: AutoRouteSelection, |
| 696 | ) -> AutoRouteSelection { |
| 697 | selection.reasoning_effort = selection.reasoning_effort.map(|effort| { |
| 698 | normalize_auto_route_effort_for_configured_route( |
| 699 | config, |
| 700 | &selection.provider, |
| 701 | &selection.model, |
| 702 | effort, |
| 703 | ) |
| 704 | }); |
| 705 | selection |
| 706 | } |
| 707 | |
| 708 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 709 | struct InventoryAutoRouteRecommendation { |
| 710 | provider: ProviderIdentity, |
| 711 | model: String, |
| 712 | reasoning_effort: Option<ReasoningEffort>, |
| 713 | } |
| 714 | |
| 715 | /// One provider-backed classifier attempt. A provider-success response always |
| 716 | /// reaches this shape before its content is interpreted, so invalid JSON and |
| 717 | /// provider-declared incomplete output retain their exact routed usage. |
| 718 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 719 | struct InventoryAutoRouteAttempt { |
| 720 | recommendation: Option<InventoryAutoRouteRecommendation>, |
| 721 | routed_usage: Vec<RuntimeUsageRecord>, |
| 722 | routed_usage_drop_records: Vec<RuntimeUsageDropRecord>, |
| 723 | routed_usage_dropped_records: u64, |
| 724 | /// Decision-model evidence, when a decision router answered. |
| 725 | decision: Option<AutoRouteDecisionEvidence>, |
| 726 | /// Why the router produced no usable recommendation. |
| 727 | failure: Option<AutoRouterFailure>, |
| 728 | /// Overrides the fallback reason when the router answered but its answer |
| 729 | /// was not acted on (low confidence). |
| 730 | fallback_reason: Option<AutoRouteHeuristicReason>, |
| 731 | } |
| 732 | |
| 733 | impl InventoryAutoRouteAttempt { |
| 734 | fn failed(failure: AutoRouterFailure) -> Self { |
| 735 | Self { |
| 736 | recommendation: None, |
| 737 | routed_usage: Vec::new(), |
| 738 | routed_usage_drop_records: Vec::new(), |
| 739 | routed_usage_dropped_records: 0, |
| 740 | decision: None, |
| 741 | failure: Some(failure), |
| 742 | fallback_reason: None, |
| 743 | } |
| 744 | } |
| 745 | } |
| 746 | |
| 747 | pub async fn resolve_auto_route_with_inventory( |
| 748 | config: &Config, |
| 749 | latest_request: &str, |
| 750 | recent_context: &str, |
| 751 | selected_model_mode: &str, |
| 752 | selected_thinking_mode: &str, |
| 753 | ) -> Result<AutoRouteSelection> { |
| 754 | resolve_auto_route_with_inventory_for_session( |
| 755 | config, |
| 756 | latest_request, |
| 757 | recent_context, |
| 758 | "agent", |
| 759 | selected_model_mode, |
| 760 | selected_thinking_mode, |
| 761 | ) |
| 762 | .await |
| 763 | } |
| 764 | |
| 765 | pub async fn resolve_auto_route_with_inventory_for_session( |
| 766 | config: &Config, |
| 767 | latest_request: &str, |
| 768 | recent_context: &str, |
| 769 | session_mode: &str, |
| 770 | selected_model_mode: &str, |
| 771 | selected_thinking_mode: &str, |
| 772 | ) -> Result<AutoRouteSelection> { |
| 773 | resolve_auto_route_with_inventory_for_session_and_cache_policy( |
| 774 | config, |
| 775 | latest_request, |
| 776 | recent_context, |
| 777 | session_mode, |
| 778 | selected_model_mode, |
| 779 | selected_thinking_mode, |
| 780 | true, |
| 781 | None, |
| 782 | ) |
| 783 | .await |
| 784 | } |
| 785 | |
| 786 | pub async fn resolve_auto_route_with_inventory_for_session_and_cache_policy( |
| 787 | config: &Config, |
| 788 | latest_request: &str, |
| 789 | recent_context: &str, |
| 790 | session_mode: &str, |
| 791 | selected_model_mode: &str, |
| 792 | selected_thinking_mode: &str, |
| 793 | allow_response_cache: bool, |
| 794 | accounting_source: Option<crate::cost_status::NativeUsageSource>, |
| 795 | ) -> Result<AutoRouteSelection> { |
| 796 | let mut inventory = ModelInventory::from_config(config).map_err(anyhow::Error::msg)?; |
| 797 | if let Some(active) = inventory.active_default() |
| 798 | && active.provider == ProviderKind::Ollama |
| 799 | && active.auth_source == crate::model_inventory::ModelAuthSource::KeylessLocal |
| 800 | && active.context_window_unverified |
| 801 | && config |
| 802 | .context_window_for_provider_config(&active.identity) |
| 803 | .is_none() |
| 804 | { |
| 805 | let _ = tokio::time::timeout( |
| 806 | Duration::from_secs(3), |
| 807 | crate::provider_lake::refresh_local_ollama_catalog(config, &active.identity), |
| 808 | ) |
| 809 | .await; |
| 810 | inventory = ModelInventory::from_config(config).map_err(anyhow::Error::msg)?; |
| 811 | } |
| 812 | if !inventory.router_available { |
| 813 | // Declared-default auto routing when no router is available. A router |
| 814 | // that was declared but cannot run is marked failing on the receipt. |
| 815 | return Ok(normalize_auto_route_selection_for_config( |
| 816 | config, |
| 817 | auto_route_without_router(config, &inventory), |
| 818 | )); |
| 819 | } |
| 820 | |
| 821 | if cfg!(any(test, feature = "test-support")) { |
| 822 | return Ok(normalize_auto_route_selection_for_config( |
| 823 | config, |
| 824 | auto_route_declared_fallback(config, &inventory), |
| 825 | )); |
| 826 | } |
| 827 | |
| 828 | let session = accounting_source |
| 829 | .as_ref() |
| 830 | .and_then(|source| source.origin()?.session_id()) |
| 831 | .map(|id| crate::client::opencode_conversation_key(id, None)); |
| 832 | let attempt = auto_route_via_router( |
| 833 | config, |
| 834 | &inventory, |
| 835 | latest_request, |
| 836 | recent_context, |
| 837 | session_mode, |
| 838 | selected_model_mode, |
| 839 | selected_thinking_mode, |
| 840 | allow_response_cache, |
| 841 | accounting_source, |
| 842 | ); |
| 843 | let selection = if let Some(session) = session |
| 844 | && crate::client::OPENCODE_CONVERSATION |
| 845 | .try_with(|_| ()) |
| 846 | .is_err() |
| 847 | { |
| 848 | crate::client::OPENCODE_CONVERSATION |
| 849 | .scope(session, attempt) |
| 850 | .await? |
| 851 | } else { |
| 852 | attempt.await? |
| 853 | }; |
| 854 | Ok(normalize_auto_route_selection_for_config(config, selection)) |
| 855 | } |
| 856 | |
| 857 | /// The local fallback when the router is not available, marking a declared |
| 858 | /// but unusable router as failing rather than silently ignoring it. |
| 859 | fn auto_route_without_router(config: &Config, inventory: &ModelInventory) -> AutoRouteSelection { |
| 860 | let mut selection = auto_route_declared_fallback(config, inventory); |
| 861 | if inventory.router_setup_issue.is_some() |
| 862 | && let Some(receipt) = selection.receipt.as_mut() |
| 863 | { |
| 864 | receipt.router_failure = Some(AutoRouterFailure::NotRunnable); |
| 865 | } |
| 866 | selection |
| 867 | } |
| 868 | |
| 869 | /// Ask the configured router (either kind) for this turn's route. Callers |
| 870 | /// have already checked `inventory.router_available`. The `cfg!(any(test, feature = "test-support"))` |
| 871 | /// short-circuit lives in the caller, so tests exercise this directly. |
| 872 | #[allow(clippy::too_many_arguments)] |
| 873 | async fn auto_route_via_router( |
| 874 | config: &Config, |
| 875 | inventory: &ModelInventory, |
| 876 | latest_request: &str, |
| 877 | recent_context: &str, |
| 878 | session_mode: &str, |
| 879 | selected_model_mode: &str, |
| 880 | selected_thinking_mode: &str, |
| 881 | allow_response_cache: bool, |
| 882 | accounting_source: Option<crate::cost_status::NativeUsageSource>, |
| 883 | ) -> Result<AutoRouteSelection> { |
| 884 | let fallback = auto_route_declared_fallback(config, inventory); |
| 885 | let attempt = match inventory.router_kind { |
| 886 | AutoRouterKind::Decision => { |
| 887 | // Options are tiers, not model ids: without a runnable strong/fast |
| 888 | // pair there is nothing to decide, so no request and no spend. |
| 889 | let Some(pair) = runnable_active_pair(inventory) else { |
| 890 | let mut selection = fallback; |
| 891 | if let Some(receipt) = selection.receipt.as_mut() { |
| 892 | receipt.reason = |
| 893 | AutoRouteReason::LocalFallback(AutoRouteHeuristicReason::NoFastSibling); |
| 894 | } |
| 895 | return Ok(selection); |
| 896 | }; |
| 897 | auto_route_decision_recommendation( |
| 898 | config, |
| 899 | inventory, |
| 900 | &pair, |
| 901 | latest_request, |
| 902 | recent_context, |
| 903 | session_mode, |
| 904 | selected_thinking_mode, |
| 905 | accounting_source, |
| 906 | ) |
| 907 | .await |
| 908 | } |
| 909 | AutoRouterKind::Chat => { |
| 910 | auto_route_inventory_recommendation( |
| 911 | config, |
| 912 | inventory, |
| 913 | latest_request, |
| 914 | recent_context, |
| 915 | session_mode, |
| 916 | selected_model_mode, |
| 917 | selected_thinking_mode, |
| 918 | allow_response_cache, |
| 919 | accounting_source, |
| 920 | ) |
| 921 | .await |
| 922 | } |
| 923 | }; |
| 924 | match attempt { |
| 925 | Ok(attempt) => Ok(auto_route_from_classifier_attempt( |
| 926 | fallback, inventory, attempt, |
| 927 | )), |
| 928 | // Only client construction/preflight failures use the local fallback. |
| 929 | Err(_) => { |
| 930 | let mut selection = auto_route_classifier_fallback(fallback, inventory); |
| 931 | if let Some(receipt) = selection.receipt.as_mut() { |
| 932 | receipt.router_failure = Some(AutoRouterFailure::NotRunnable); |
| 933 | } |
| 934 | Ok(selection) |
| 935 | } |
| 936 | } |
| 937 | } |
| 938 | |
| 939 | /// Fixed synthetic request used by `/router` preset test calls. |
| 940 | pub const ROUTER_TEST_REQUEST: &str = "Rename the variable foo to bar in src/lib.rs"; |
| 941 | |
| 942 | /// One `/router` preset test call (#6525): exactly the per-turn routing path, |
| 943 | /// run once against a fixed synthetic request, with its wall-clock latency. |
| 944 | /// Returns `Err` with a non-secret reason whenever no request was sent, so |
| 945 | /// the setup view never reports a test that did not happen. |
| 946 | pub async fn test_auto_router( |
| 947 | config: &Config, |
| 948 | accounting_origin: Option<crate::cost_status::NativeUsageOrigin>, |
| 949 | ) -> std::result::Result<(AutoRouteSelection, u64), String> { |
| 950 | let inventory = ModelInventory::from_config(config)?; |
| 951 | if !inventory.router_available { |
| 952 | return Err(inventory |
| 953 | .router_setup_issue |
| 954 | .map_or("router is not configured", |issue| issue.label()) |
| 955 | .to_string()); |
| 956 | } |
| 957 | // A decision router with no runnable strong/fast pair has nothing to |
| 958 | // decide and sends nothing (see `auto_route_via_router`). |
| 959 | if inventory.router_kind == AutoRouterKind::Decision |
| 960 | && runnable_active_pair(&inventory).is_none() |
| 961 | { |
| 962 | return Err(AutoRouteHeuristicReason::NoFastSibling.label().to_string()); |
| 963 | } |
| 964 | let accounting_source = accounting_origin.map(|origin| { |
| 965 | crate::cost_status::NativeUsageSource::capture_with_origin( |
| 966 | format!("router-test:{}", uuid::Uuid::new_v4()), |
| 967 | crate::cost_status::UsageSpendOwner::Auxiliary, |
| 968 | Some(origin), |
| 969 | ) |
| 970 | }); |
| 971 | let started = Instant::now(); |
| 972 | let selection = auto_route_via_router( |
| 973 | config, |
| 974 | &inventory, |
| 975 | ROUTER_TEST_REQUEST, |
| 976 | "", |
| 977 | "agent", |
| 978 | "auto", |
| 979 | "auto", |
| 980 | false, |
| 981 | accounting_source, |
| 982 | ) |
| 983 | .await |
| 984 | .map_err(|error| error.to_string())?; |
| 985 | let latency_ms = u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX); |
| 986 | // `NotRunnable` is set only when the client could not be built or the |
| 987 | // request failed preflight: nothing reached the network. |
| 988 | if let Some(failure @ AutoRouterFailure::NotRunnable) = selection |
| 989 | .receipt |
| 990 | .as_ref() |
| 991 | .and_then(|receipt| receipt.router_failure) |
| 992 | { |
| 993 | return Err(failure.label()); |
| 994 | } |
| 995 | Ok(( |
| 996 | normalize_auto_route_selection_for_config(config, selection), |
| 997 | latency_ms, |
| 998 | )) |
| 999 | } |
| 1000 | |
| 1001 | pub fn resolve_explicit_route_with_inventory( |
| 1002 | config: &Config, |
| 1003 | requested_model: &str, |
| 1004 | ) -> Option<AutoRouteSelection> { |
| 1005 | let requested_model = requested_model.trim(); |
| 1006 | if requested_model.is_empty() || requested_model.eq_ignore_ascii_case("auto") { |
| 1007 | return None; |
| 1008 | } |
| 1009 | |
| 1010 | let inventory = ModelInventory::from_config(config).ok()?; |
| 1011 | let active_identity = &inventory.active_identity; |
| 1012 | |
| 1013 | if let Some(candidate) = inventory.candidates.iter().find(|candidate| { |
| 1014 | &candidate.identity == active_identity |
| 1015 | && explicit_model_matches_candidate(candidate, requested_model) |
| 1016 | }) { |
| 1017 | return Some(AutoRouteSelection { |
| 1018 | provider: candidate.identity.clone(), |
| 1019 | model: candidate.model.clone(), |
| 1020 | reasoning_effort: config.reasoning_effort().map(|setting| { |
| 1021 | normalize_auto_route_effort_for_configured_route( |
| 1022 | config, |
| 1023 | &candidate.identity, |
| 1024 | &candidate.model, |
| 1025 | ReasoningEffort::from_setting(setting), |
| 1026 | ) |
| 1027 | }), |
| 1028 | source: AutoRouteSource::Heuristic, |
| 1029 | receipt: None, |
| 1030 | routed_usage: Vec::new(), |
| 1031 | routed_usage_drop_records: Vec::new(), |
| 1032 | routed_usage_dropped_records: 0, |
| 1033 | }); |
| 1034 | } |
| 1035 | |
| 1036 | let mut matches = inventory |
| 1037 | .candidates |
| 1038 | .iter() |
| 1039 | .filter(|candidate| explicit_model_matches_candidate(candidate, requested_model)); |
| 1040 | let candidate = matches.next()?; |
| 1041 | if matches.next().is_some() { |
| 1042 | return None; |
| 1043 | } |
| 1044 | |
| 1045 | Some(AutoRouteSelection { |
| 1046 | provider: candidate.identity.clone(), |
| 1047 | model: candidate.model.clone(), |
| 1048 | reasoning_effort: config.reasoning_effort().map(|setting| { |
| 1049 | normalize_auto_route_effort_for_configured_route( |
| 1050 | config, |
| 1051 | &candidate.identity, |
| 1052 | &candidate.model, |
| 1053 | ReasoningEffort::from_setting(setting), |
| 1054 | ) |
| 1055 | }), |
| 1056 | source: AutoRouteSource::Heuristic, |
| 1057 | receipt: None, |
| 1058 | routed_usage: Vec::new(), |
| 1059 | routed_usage_drop_records: Vec::new(), |
| 1060 | routed_usage_dropped_records: 0, |
| 1061 | }) |
| 1062 | } |
| 1063 | |
| 1064 | pub fn explicit_route_candidate_providers( |
| 1065 | config: &Config, |
| 1066 | requested_model: &str, |
| 1067 | ) -> Vec<ProviderIdentity> { |
| 1068 | let requested_model = requested_model.trim(); |
| 1069 | if requested_model.is_empty() || requested_model.eq_ignore_ascii_case("auto") { |
| 1070 | return Vec::new(); |
| 1071 | } |
| 1072 | |
| 1073 | let Ok(inventory) = ModelInventory::from_config(config) else { |
| 1074 | return Vec::new(); |
| 1075 | }; |
| 1076 | let mut providers = Vec::new(); |
| 1077 | for candidate in inventory |
| 1078 | .candidates |
| 1079 | .iter() |
| 1080 | .filter(|candidate| explicit_model_matches_candidate(candidate, requested_model)) |
| 1081 | { |
| 1082 | if !providers.contains(&candidate.identity) { |
| 1083 | providers.push(candidate.identity.clone()); |
| 1084 | } |
| 1085 | } |
| 1086 | providers |
| 1087 | } |
| 1088 | |
| 1089 | fn explicit_model_matches_candidate( |
| 1090 | candidate: &crate::model_inventory::ModelRouteCandidate, |
| 1091 | requested_model: &str, |
| 1092 | ) -> bool { |
| 1093 | candidate.model.eq_ignore_ascii_case(requested_model) |
| 1094 | || codewhale_config::route::resolve_model(candidate.provider, requested_model, None) |
| 1095 | .is_ok_and(|resolved| candidate.model.eq_ignore_ascii_case(&resolved.wire_id)) |
| 1096 | } |
| 1097 | |
| 1098 | /// Declared local fallback for Auto routing when the flash classifier is |
| 1099 | /// unavailable (or fails): the configured default model. |
| 1100 | /// |
| 1101 | /// There is no per-request signal here by design. Until the #6290 rework this |
| 1102 | /// guessed cheap-vs-big from request wording (`COMPLEX_KEYWORDS` plus |
| 1103 | /// char-length thresholds) — host-side semantic determinism that made cost |
| 1104 | /// and quality depend on vocabulary. The only content-blind override is the |
| 1105 | /// explicit `[auto] cost_saving` opt-in, which pins the runnable fast |
| 1106 | /// sibling; providers without one stay on the default. |
| 1107 | fn auto_route_declared_fallback(config: &Config, inventory: &ModelInventory) -> AutoRouteSelection { |
| 1108 | let Some(active) = inventory.active_default() else { |
| 1109 | let model = config.default_model(); |
| 1110 | return AutoRouteSelection { |
| 1111 | provider: inventory.active_identity.clone(), |
| 1112 | receipt: Some(auto_route_receipt( |
| 1113 | inventory, |
| 1114 | &inventory.active_identity, |
| 1115 | &model, |
| 1116 | AutoRouteScope::ResolvedProvider, |
| 1117 | AutoRouteDataPath::LocalHeuristic, |
| 1118 | AutoRouteReason::LocalFallback(AutoRouteHeuristicReason::NoRunnableCandidate), |
| 1119 | )), |
| 1120 | model, |
| 1121 | reasoning_effort: Some(crate::auto_reasoning::select()), |
| 1122 | source: AutoRouteSource::Heuristic, |
| 1123 | routed_usage: Vec::new(), |
| 1124 | routed_usage_drop_records: Vec::new(), |
| 1125 | routed_usage_dropped_records: 0, |
| 1126 | }; |
| 1127 | }; |
| 1128 | let router_candidates = provider_router_candidates(active.provider, &active.model); |
| 1129 | let runnable_fast = router_candidates.cheap.as_deref().filter(|model| { |
| 1130 | inventory |
| 1131 | .candidate(active.identity.key.as_str(), model) |
| 1132 | .is_some_and(|candidate| candidate.readiness.can_attempt()) |
| 1133 | }); |
| 1134 | let (model, reason) = if config.auto_cost_saving() { |
| 1135 | match runnable_fast { |
| 1136 | Some(cheap) => ( |
| 1137 | cheap.to_string(), |
| 1138 | AutoRouteHeuristicReason::CostSavingPolicy, |
| 1139 | ), |
| 1140 | None => ( |
| 1141 | active.model.clone(), |
| 1142 | AutoRouteHeuristicReason::NoFastSibling, |
| 1143 | ), |
| 1144 | } |
| 1145 | } else { |
| 1146 | ( |
| 1147 | active.model.clone(), |
| 1148 | AutoRouteHeuristicReason::DeclaredDefault, |
| 1149 | ) |
| 1150 | }; |
| 1151 | AutoRouteSelection { |
| 1152 | provider: active.identity.clone(), |
| 1153 | receipt: Some(auto_route_receipt( |
| 1154 | inventory, |
| 1155 | &active.identity, |
| 1156 | &model, |
| 1157 | AutoRouteScope::ResolvedProvider, |
| 1158 | AutoRouteDataPath::LocalHeuristic, |
| 1159 | AutoRouteReason::LocalFallback(reason), |
| 1160 | )), |
| 1161 | model, |
| 1162 | reasoning_effort: Some(crate::auto_reasoning::select()), |
| 1163 | source: AutoRouteSource::Heuristic, |
| 1164 | routed_usage: Vec::new(), |
| 1165 | routed_usage_drop_records: Vec::new(), |
| 1166 | routed_usage_dropped_records: 0, |
| 1167 | } |
| 1168 | } |
| 1169 | |
| 1170 | fn auto_route_from_classifier( |
| 1171 | inventory: &ModelInventory, |
| 1172 | recommendation: InventoryAutoRouteRecommendation, |
| 1173 | ) -> AutoRouteSelection { |
| 1174 | let data_path = router_data_path(inventory); |
| 1175 | // Report the scope the classifier actually had, not the widest one it |
| 1176 | // could ever have (#4411). A decision router only ever chooses a tier of |
| 1177 | // the active provider. |
| 1178 | let scope = if inventory.cross_provider_auto && inventory.router_decision_route.is_none() { |
| 1179 | AutoRouteScope::RunnableProviders |
| 1180 | } else { |
| 1181 | AutoRouteScope::ActiveProvider |
| 1182 | }; |
| 1183 | AutoRouteSelection { |
| 1184 | provider: recommendation.provider.clone(), |
| 1185 | receipt: Some(auto_route_receipt( |
| 1186 | inventory, |
| 1187 | &recommendation.provider, |
| 1188 | &recommendation.model, |
| 1189 | scope, |
| 1190 | data_path, |
| 1191 | AutoRouteReason::ClassifierRecommendation, |
| 1192 | )), |
| 1193 | model: recommendation.model, |
| 1194 | reasoning_effort: recommendation.reasoning_effort, |
| 1195 | source: AutoRouteSource::FlashRouter, |
| 1196 | routed_usage: Vec::new(), |
| 1197 | routed_usage_drop_records: Vec::new(), |
| 1198 | routed_usage_dropped_records: 0, |
| 1199 | } |
| 1200 | } |
| 1201 | |
| 1202 | fn auto_route_from_classifier_attempt( |
| 1203 | fallback: AutoRouteSelection, |
| 1204 | inventory: &ModelInventory, |
| 1205 | attempt: InventoryAutoRouteAttempt, |
| 1206 | ) -> AutoRouteSelection { |
| 1207 | let InventoryAutoRouteAttempt { |
| 1208 | recommendation, |
| 1209 | routed_usage, |
| 1210 | routed_usage_drop_records, |
| 1211 | routed_usage_dropped_records, |
| 1212 | decision, |
| 1213 | failure, |
| 1214 | fallback_reason, |
| 1215 | } = attempt; |
| 1216 | let mut selection = recommendation.map_or_else( |
| 1217 | || auto_route_classifier_fallback(fallback, inventory), |
| 1218 | |recommendation| auto_route_from_classifier(inventory, recommendation), |
| 1219 | ); |
| 1220 | if let Some(receipt) = selection.receipt.as_mut() { |
| 1221 | if let (Some(reason), AutoRouteReason::ClassifierFallback(_)) = |
| 1222 | (fallback_reason, receipt.reason) |
| 1223 | { |
| 1224 | receipt.reason = AutoRouteReason::ClassifierFallback(reason); |
| 1225 | } |
| 1226 | receipt.decision = decision; |
| 1227 | receipt.router_failure = failure; |
| 1228 | } |
| 1229 | selection.routed_usage = routed_usage; |
| 1230 | selection.routed_usage_drop_records = routed_usage_drop_records; |
| 1231 | selection.routed_usage_dropped_records = routed_usage_dropped_records; |
| 1232 | selection |
| 1233 | } |
| 1234 | |
| 1235 | fn auto_route_classifier_fallback( |
| 1236 | mut fallback: AutoRouteSelection, |
| 1237 | inventory: &ModelInventory, |
| 1238 | ) -> AutoRouteSelection { |
| 1239 | if let Some(receipt) = fallback.receipt.as_mut() { |
| 1240 | let fallback_reason = match receipt.reason { |
| 1241 | AutoRouteReason::LocalFallback(reason) |
| 1242 | | AutoRouteReason::ClassifierFallback(reason) => reason, |
| 1243 | AutoRouteReason::ClassifierRecommendation => AutoRouteHeuristicReason::DeclaredDefault, |
| 1244 | }; |
| 1245 | receipt.data_path = router_data_path(inventory); |
| 1246 | receipt.reason = AutoRouteReason::ClassifierFallback(fallback_reason); |
| 1247 | } |
| 1248 | fallback |
| 1249 | } |
| 1250 | |
| 1251 | /// The non-secret data path of the configured router. |
| 1252 | fn router_data_path(inventory: &ModelInventory) -> AutoRouteDataPath { |
| 1253 | match inventory.router_decision_route { |
| 1254 | Some(route) => AutoRouteDataPath::Decision { |
| 1255 | route, |
| 1256 | model: inventory.router_model.to_string(), |
| 1257 | }, |
| 1258 | None => AutoRouteDataPath::Classifier { |
| 1259 | provider: inventory.router_identity.as_ref().map_or_else( |
| 1260 | || inventory.router_provider.as_str().into(), |
| 1261 | |identity| identity.key.clone(), |
| 1262 | ), |
| 1263 | provider_kind: inventory.router_provider, |
| 1264 | model: inventory.router_model.to_string(), |
| 1265 | }, |
| 1266 | } |
| 1267 | } |
| 1268 | |
| 1269 | fn auto_route_receipt( |
| 1270 | inventory: &ModelInventory, |
| 1271 | identity: &ProviderIdentity, |
| 1272 | selected_model: &str, |
| 1273 | scope: AutoRouteScope, |
| 1274 | data_path: AutoRouteDataPath, |
| 1275 | reason: AutoRouteReason, |
| 1276 | ) -> AutoRouteReceipt { |
| 1277 | let pair = auto_route_pair(inventory, identity, selected_model); |
| 1278 | let tier = if pair |
| 1279 | .fast |
| 1280 | .as_deref() |
| 1281 | .is_some_and(|fast| fast.eq_ignore_ascii_case(selected_model)) |
| 1282 | { |
| 1283 | AutoRouteTier::Fast |
| 1284 | } else if pair.strong.eq_ignore_ascii_case(selected_model) { |
| 1285 | if pair.fast.is_some() { |
| 1286 | AutoRouteTier::Strong |
| 1287 | } else { |
| 1288 | AutoRouteTier::Only |
| 1289 | } |
| 1290 | } else { |
| 1291 | AutoRouteTier::Selected |
| 1292 | }; |
| 1293 | AutoRouteReceipt { |
| 1294 | tier, |
| 1295 | pair, |
| 1296 | scope, |
| 1297 | data_path, |
| 1298 | reason, |
| 1299 | decision: None, |
| 1300 | router_failure: None, |
| 1301 | } |
| 1302 | } |
| 1303 | |
| 1304 | fn auto_route_pair( |
| 1305 | inventory: &ModelInventory, |
| 1306 | identity: &ProviderIdentity, |
| 1307 | selected_model: &str, |
| 1308 | ) -> AutoRoutePair { |
| 1309 | // A provider can expose several unrelated model families. Derive the pair |
| 1310 | // from a runnable candidate that actually contains the selected model, |
| 1311 | // preferring a cheap-tier match before a strong-tier match. Falling back |
| 1312 | // to the provider default would report a truthful provider with a false |
| 1313 | // model family (for example OpenRouter GLM reported as DeepSeek). |
| 1314 | let matching_pair = inventory |
| 1315 | .candidates |
| 1316 | .iter() |
| 1317 | .filter(|candidate| candidate.identity == *identity && candidate.readiness.can_attempt()) |
| 1318 | .map(|candidate| provider_router_candidates(identity.provider, &candidate.model)) |
| 1319 | .find(|pair| { |
| 1320 | pair.cheap |
| 1321 | .as_deref() |
| 1322 | .is_some_and(|fast| fast.eq_ignore_ascii_case(selected_model)) |
| 1323 | }) |
| 1324 | .or_else(|| { |
| 1325 | inventory |
| 1326 | .candidates |
| 1327 | .iter() |
| 1328 | .filter(|candidate| { |
| 1329 | candidate.identity == *identity && candidate.readiness.can_attempt() |
| 1330 | }) |
| 1331 | .map(|candidate| provider_router_candidates(identity.provider, &candidate.model)) |
| 1332 | .find(|pair| pair.big.eq_ignore_ascii_case(selected_model)) |
| 1333 | }); |
| 1334 | let Some(candidates) = matching_pair else { |
| 1335 | return AutoRoutePair { |
| 1336 | strong: selected_model.to_string(), |
| 1337 | fast: None, |
| 1338 | }; |
| 1339 | }; |
| 1340 | let Some(strong) = inventory |
| 1341 | .candidate(identity.key.as_str(), &candidates.big) |
| 1342 | .filter(|candidate| candidate.readiness.can_attempt()) |
| 1343 | .map(|candidate| candidate.model.clone()) |
| 1344 | else { |
| 1345 | return AutoRoutePair { |
| 1346 | strong: selected_model.to_string(), |
| 1347 | fast: None, |
| 1348 | }; |
| 1349 | }; |
| 1350 | let fast = candidates.cheap.as_deref().and_then(|model| { |
| 1351 | inventory |
| 1352 | .candidate(identity.key.as_str(), model) |
| 1353 | .filter(|candidate| candidate.readiness.can_attempt()) |
| 1354 | .map(|candidate| candidate.model.clone()) |
| 1355 | }); |
| 1356 | AutoRoutePair { strong, fast } |
| 1357 | } |
| 1358 | |
| 1359 | fn auto_route_usage_has_reported_data(usage: &codewhale_models::Usage) -> bool { |
| 1360 | usage.input_tokens > 0 |
| 1361 | || usage.output_tokens > 0 |
| 1362 | || usage.prompt_cache_hit_tokens.is_some() |
| 1363 | || usage.prompt_cache_miss_tokens.is_some() |
| 1364 | || usage.prompt_cache_write_tokens.is_some() |
| 1365 | || usage.reasoning_tokens.is_some() |
| 1366 | || usage.reasoning_replay_tokens.is_some() |
| 1367 | || usage.server_tool_use.is_some() |
| 1368 | } |
| 1369 | |
| 1370 | fn auto_route_attempt_from_response( |
| 1371 | _request_route: EffectiveRouteEnvelope, |
| 1372 | response: &MessageResponse, |
| 1373 | inventory: &ModelInventory, |
| 1374 | record: RuntimeUsageRecord, |
| 1375 | ) -> InventoryAutoRouteAttempt { |
| 1376 | let routed_usage = vec![record]; |
| 1377 | let recommendation = |
| 1378 | (!codewhale_models::is_incomplete_stop_reason(response.stop_reason.as_deref())) |
| 1379 | .then(|| { |
| 1380 | parse_inventory_auto_route_recommendation( |
| 1381 | &message_response_text(response), |
| 1382 | inventory, |
| 1383 | ) |
| 1384 | }) |
| 1385 | .flatten(); |
| 1386 | InventoryAutoRouteAttempt { |
| 1387 | failure: recommendation |
| 1388 | .is_none() |
| 1389 | .then_some(AutoRouterFailure::InvalidAnswer), |
| 1390 | recommendation, |
| 1391 | routed_usage, |
| 1392 | routed_usage_drop_records: Vec::new(), |
| 1393 | routed_usage_dropped_records: 0, |
| 1394 | decision: None, |
| 1395 | fallback_reason: None, |
| 1396 | } |
| 1397 | } |
| 1398 | |
| 1399 | fn auto_route_attempt_from_provider_response( |
| 1400 | request_route: EffectiveRouteEnvelope, |
| 1401 | response: &MessageResponse, |
| 1402 | inventory: &ModelInventory, |
| 1403 | record: RuntimeUsageRecord, |
| 1404 | ) -> InventoryAutoRouteAttempt { |
| 1405 | auto_route_attempt_from_response(request_route, response, inventory, record) |
| 1406 | } |
| 1407 | |
| 1408 | fn auto_route_attempt_with_dropped_response( |
| 1409 | record: RuntimeUsageRecord, |
| 1410 | failure: AutoRouterFailure, |
| 1411 | ) -> InventoryAutoRouteAttempt { |
| 1412 | InventoryAutoRouteAttempt { |
| 1413 | routed_usage: vec![record], |
| 1414 | ..InventoryAutoRouteAttempt::failed(failure) |
| 1415 | } |
| 1416 | } |
| 1417 | |
| 1418 | /// Prove that the deterministic request seam accepts this classifier request |
| 1419 | /// before capturing a quote or entering any provider permit/network path. |
| 1420 | fn preflight_auto_route_request(client: &CodewhaleClient, request: &MessageRequest) -> Result<()> { |
| 1421 | client.prepare_outbound_request(request.clone(), false)?; |
| 1422 | Ok(()) |
| 1423 | } |
| 1424 | |
| 1425 | #[allow(clippy::too_many_arguments)] |
| 1426 | async fn auto_route_inventory_recommendation( |
| 1427 | config: &Config, |
| 1428 | inventory: &ModelInventory, |
| 1429 | latest_request: &str, |
| 1430 | recent_context: &str, |
| 1431 | session_mode: &str, |
| 1432 | selected_model_mode: &str, |
| 1433 | selected_thinking_mode: &str, |
| 1434 | allow_response_cache: bool, |
| 1435 | accounting_source: Option<crate::cost_status::NativeUsageSource>, |
| 1436 | ) -> Result<InventoryAutoRouteAttempt> { |
| 1437 | let mut router_config = config.clone(); |
| 1438 | // The classifier runs on the inventory's router route: the explicit |
| 1439 | // [auto.router] route when configured, else the DeepSeek flash default. |
| 1440 | let identity = inventory |
| 1441 | .router_identity |
| 1442 | .as_ref() |
| 1443 | .ok_or_else(|| anyhow::anyhow!("router identity was not admitted"))?; |
| 1444 | router_config |
| 1445 | .scope_to_provider_identity(identity) |
| 1446 | .map_err(anyhow::Error::msg)?; |
| 1447 | router_config.default_text_model = Some(inventory.router_model.clone()); |
| 1448 | |
| 1449 | let client = CodewhaleClient::new(&router_config)?; |
| 1450 | let router_system = inventory_auto_router_system_prompt(inventory, config.auto_cost_saving()); |
| 1451 | let router_prompt = classifier_prompt( |
| 1452 | &client, |
| 1453 | latest_request, |
| 1454 | recent_context, |
| 1455 | session_mode, |
| 1456 | selected_model_mode, |
| 1457 | selected_thinking_mode, |
| 1458 | ); |
| 1459 | let max_tokens = client.effective_max_output_tokens(&inventory.router_model); |
| 1460 | let request = MessageRequest { |
| 1461 | model: inventory.router_model.to_string(), |
| 1462 | messages: vec![Message { |
| 1463 | role: Role::User, |
| 1464 | content: vec![ContentBlock::Text { |
| 1465 | text: router_prompt, |
| 1466 | cache_control: None, |
| 1467 | }], |
| 1468 | }], |
| 1469 | max_tokens, |
| 1470 | system: Some(SystemPrompt::Text(router_system)), |
| 1471 | tools: None, |
| 1472 | tool_choice: None, |
| 1473 | metadata: None, |
| 1474 | thinking: None, |
| 1475 | reasoning_effort: Some( |
| 1476 | inventory |
| 1477 | .router_thinking |
| 1478 | .clone() |
| 1479 | .unwrap_or_else(|| "off".to_string()), |
| 1480 | ), |
| 1481 | stream: Some(false), |
| 1482 | temperature: None, |
| 1483 | top_p: None, |
| 1484 | safety_check: None, |
| 1485 | title: None, |
| 1486 | }; |
| 1487 | |
| 1488 | // Freeze pricing at the last application seam before the provider future |
| 1489 | // starts. Prompt shaping above may be slow and may overlap a catalog |
| 1490 | // refresh; completion-time mutable catalog state must never reprice this |
| 1491 | // already-admitted classifier request. |
| 1492 | preflight_auto_route_request(&client, &request)?; |
| 1493 | let request_route = |
| 1494 | client.effective_route_envelope(&inventory.router_model, chrono::Utc::now()); |
| 1495 | let accounting_source = accounting_source.unwrap_or_else(|| { |
| 1496 | crate::cost_status::NativeUsageSource::capture( |
| 1497 | format!("auto-router:{}", uuid::Uuid::new_v4()), |
| 1498 | crate::cost_status::UsageSpendOwner::Auxiliary, |
| 1499 | ) |
| 1500 | }); |
| 1501 | let observation = accounting_source.observation(); |
| 1502 | let response = if allow_response_cache { |
| 1503 | tokio::time::timeout( |
| 1504 | Duration::from_secs(inventory.router_timeout_secs), |
| 1505 | crate::llm_client::observe_request_retries( |
| 1506 | Some(observation.clone()), |
| 1507 | client.create_message(request), |
| 1508 | ), |
| 1509 | ) |
| 1510 | .await |
| 1511 | } else { |
| 1512 | tokio::time::timeout( |
| 1513 | Duration::from_secs(inventory.router_timeout_secs), |
| 1514 | client.create_message_without_response_cache(request, observation.clone()), |
| 1515 | ) |
| 1516 | .await |
| 1517 | }; |
| 1518 | let wire = observation.wire_observations.drain(); |
| 1519 | let (response, failure) = match response { |
| 1520 | Ok(Ok(response)) => (Some(response), None), |
| 1521 | Ok(Err(error)) => ( |
| 1522 | None, |
| 1523 | Some(crate::client::system_one::router_failure_from_error(&error)), |
| 1524 | ), |
| 1525 | Err(_) => (None, Some(AutoRouterFailure::Timeout)), |
| 1526 | }; |
| 1527 | if response.is_none() && wire.transmissions.is_empty() { |
| 1528 | return Ok(InventoryAutoRouteAttempt::failed( |
| 1529 | failure.unwrap_or(AutoRouterFailure::Transport), |
| 1530 | )); |
| 1531 | } |
| 1532 | let usage = response |
| 1533 | .as_ref() |
| 1534 | .map(|response| &response.usage) |
| 1535 | .cloned() |
| 1536 | .unwrap_or_default(); |
| 1537 | let complete = response.is_some(); |
| 1538 | let coverage = if wire.last_transmission.is_none() { |
| 1539 | if auto_route_usage_has_reported_data(&usage) { |
| 1540 | if complete { |
| 1541 | crate::llm_client::ProviderUsageCoverage::Reported |
| 1542 | } else { |
| 1543 | crate::llm_client::ProviderUsageCoverage::Incomplete |
| 1544 | } |
| 1545 | } else { |
| 1546 | crate::llm_client::ProviderUsageCoverage::Missing |
| 1547 | } |
| 1548 | } else { |
| 1549 | wire.usage_coverage(auto_route_usage_has_reported_data(&usage), complete) |
| 1550 | }; |
| 1551 | let reason = if response.is_some() { |
| 1552 | crate::cost_status::RuntimeUsageMissingReason::SuccessWithoutUsage |
| 1553 | } else { |
| 1554 | crate::cost_status::RuntimeUsageMissingReason::RequestOutcomeUnknown |
| 1555 | }; |
| 1556 | let record = accounting_source.prepare_record(&request_route, &usage, coverage, reason, &wire); |
| 1557 | if let Some(origin) = accounting_source.origin() { |
| 1558 | crate::cost_status::record_runtime_usage_async(origin.scope(), Some(origin), &record).await; |
| 1559 | } |
| 1560 | match response { |
| 1561 | Some(response) => Ok(auto_route_attempt_from_provider_response( |
| 1562 | request_route, |
| 1563 | &response, |
| 1564 | inventory, |
| 1565 | record, |
| 1566 | )), |
| 1567 | None => Ok(auto_route_attempt_with_dropped_response( |
| 1568 | record, |
| 1569 | failure.unwrap_or(AutoRouterFailure::Transport), |
| 1570 | )), |
| 1571 | } |
| 1572 | } |
| 1573 | |
| 1574 | /// The active provider's runnable strong/fast pair, when both tiers can run. |
| 1575 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 1576 | struct ActiveTierPair { |
| 1577 | provider: ProviderIdentity, |
| 1578 | strong: String, |
| 1579 | fast: String, |
| 1580 | } |
| 1581 | |
| 1582 | fn runnable_active_pair(inventory: &ModelInventory) -> Option<ActiveTierPair> { |
| 1583 | let active = inventory.active_default()?; |
| 1584 | let candidates = provider_router_candidates(active.provider, &active.model); |
| 1585 | let runnable = |model: &str| { |
| 1586 | inventory |
| 1587 | .candidate(active.identity.key.as_str(), model) |
| 1588 | .filter(|candidate| candidate.readiness.can_attempt()) |
| 1589 | .map(|candidate| candidate.model.clone()) |
| 1590 | }; |
| 1591 | Some(ActiveTierPair { |
| 1592 | provider: active.identity.clone(), |
| 1593 | strong: runnable(&candidates.big)?, |
| 1594 | fast: runnable(candidates.cheap.as_deref()?)?, |
| 1595 | }) |
| 1596 | } |
| 1597 | |
| 1598 | // The decision model reads its criteria literally, so this wording is a |
| 1599 | // product surface: changing it changes routing. Pinned by a snapshot test. |
| 1600 | pub const DECISION_TIER_INSTRUCTIONS: &str = |
| 1601 | "Which model tier should handle the latest request in this coding-agent session?"; |
| 1602 | pub const DECISION_FAST_WHAT: &str = "A fast, cheaper model. Right for questions, explanations, lookups, small single-file edits, formatting, and routine follow-ups."; |
| 1603 | pub const DECISION_FAST_NOT_FOR: &str = "Multi-step agentic work, debugging across files, architecture or design, security review, release work."; |
| 1604 | pub const DECISION_STRONG_WHAT: &str = "The strongest model. Right for multi-step agentic coding, multi-file changes, debugging, architecture or design, security review, release work, or anything the fast tier would likely get wrong."; |
| 1605 | pub const DECISION_STRONG_NOT_FOR: &str = "Trivial questions or one-line edits."; |
| 1606 | pub const DECISION_THINKING_INSTRUCTIONS: &str = |
| 1607 | "How much reasoning should the chosen model spend on the latest request?"; |
| 1608 | pub const DECISION_THINKING_OFF: &str = "A trivial answer with no tools and no reasoning needed."; |
| 1609 | pub const DECISION_THINKING_HIGH: &str = "Ordinary reasoning: a normal coding or explanation task."; |
| 1610 | pub const DECISION_THINKING_MAX: &str = |
| 1611 | "Agentic, multi-file, debugging, architecture, security, release, or uncertain work."; |
| 1612 | |
| 1613 | const DECISION_TIER_OPTIONS: [&str; 2] = ["fast", "strong"]; |
| 1614 | const DECISION_THINKING_OPTIONS: [&str; 3] = ["off", "high", "max"]; |
| 1615 | /// Under `[auto] cost_saving`, a `strong` decision needs at least this |
| 1616 | /// probability (basis points) or the turn stays on the fast tier. |
| 1617 | pub const COST_SAVING_STRONG_MIN_BP: u16 = 7_500; |
| 1618 | |
| 1619 | /// The System One request: one `tier` choice and one `thinking` choice over |
| 1620 | /// the same redacted, bounded state, plus the shadow Decision Gate's questions |
| 1621 | /// when `[auto.router] shadow_gate = true`. |
| 1622 | fn decision_request_body( |
| 1623 | client: &CodewhaleClient, |
| 1624 | model: &str, |
| 1625 | latest_request: &str, |
| 1626 | recent_context: &str, |
| 1627 | session_mode: &str, |
| 1628 | selected_thinking_mode: &str, |
| 1629 | shadow_gate: bool, |
| 1630 | ) -> serde_json::Value { |
| 1631 | let recent_context = if recent_context.trim().is_empty() { |
| 1632 | "No prior context." |
| 1633 | } else { |
| 1634 | recent_context |
| 1635 | }; |
| 1636 | let mut body = serde_json::json!({ |
| 1637 | "model": model, |
| 1638 | "state": { |
| 1639 | "session_mode": client.redact_model_bound_text(session_mode), |
| 1640 | "selected_thinking_mode": client.redact_model_bound_text(selected_thinking_mode), |
| 1641 | "recent_context": client.redact_model_bound_text(recent_context), |
| 1642 | "latest_request": client |
| 1643 | .redact_model_bound_text(&truncate_for_auto_router(latest_request, 4_000)), |
| 1644 | }, |
| 1645 | "questions": { |
| 1646 | "tier": { |
| 1647 | "type": "choice", |
| 1648 | "instructions": DECISION_TIER_INSTRUCTIONS, |
| 1649 | "criteria": { |
| 1650 | "fast": { "what": DECISION_FAST_WHAT, "not_for": DECISION_FAST_NOT_FOR }, |
| 1651 | "strong": { "what": DECISION_STRONG_WHAT, "not_for": DECISION_STRONG_NOT_FOR }, |
| 1652 | }, |
| 1653 | }, |
| 1654 | "thinking": { |
| 1655 | "type": "choice", |
| 1656 | "instructions": DECISION_THINKING_INSTRUCTIONS, |
| 1657 | "criteria": { |
| 1658 | "off": DECISION_THINKING_OFF, |
| 1659 | "high": DECISION_THINKING_HIGH, |
| 1660 | "max": DECISION_THINKING_MAX, |
| 1661 | }, |
| 1662 | }, |
| 1663 | }, |
| 1664 | }); |
| 1665 | if shadow_gate |
| 1666 | && let Some(questions) = body |
| 1667 | .get_mut("questions") |
| 1668 | .and_then(serde_json::Value::as_object_mut) |
| 1669 | { |
| 1670 | questions.extend(crate::superfast::gate_questions()); |
| 1671 | } |
| 1672 | body |
| 1673 | } |
| 1674 | |
| 1675 | #[allow(clippy::too_many_arguments)] |
| 1676 | async fn auto_route_decision_recommendation( |
| 1677 | config: &Config, |
| 1678 | inventory: &ModelInventory, |
| 1679 | pair: &ActiveTierPair, |
| 1680 | latest_request: &str, |
| 1681 | recent_context: &str, |
| 1682 | session_mode: &str, |
| 1683 | selected_thinking_mode: &str, |
| 1684 | accounting_source: Option<crate::cost_status::NativeUsageSource>, |
| 1685 | ) -> Result<InventoryAutoRouteAttempt> { |
| 1686 | let accounting_source = accounting_source.unwrap_or_else(|| { |
| 1687 | crate::cost_status::NativeUsageSource::capture( |
| 1688 | format!("auto-router:{}", uuid::Uuid::new_v4()), |
| 1689 | crate::cost_status::UsageSpendOwner::Auxiliary, |
| 1690 | ) |
| 1691 | }); |
| 1692 | let route = inventory |
| 1693 | .router_decision_route |
| 1694 | .ok_or_else(|| anyhow::anyhow!("decision router has no route"))?; |
| 1695 | // Resolve environment/keyring credentials off the async worker. |
| 1696 | let decision_config = config.clone(); |
| 1697 | let base_url = inventory.router_base_url.clone(); |
| 1698 | #[cfg(any(test, feature = "test-support"))] |
| 1699 | let ticket = crate::test_support::env_scope_ticket(); |
| 1700 | let shadow_gate = config.auto_router_shadow_gate(); |
| 1701 | let built = tokio::task::spawn_blocking(move || { |
| 1702 | #[cfg(any(test, feature = "test-support"))] |
| 1703 | let _membership = crate::test_support::join_env_scope(ticket); |
| 1704 | CodewhaleClient::for_decision_route(&decision_config, route, base_url.as_deref()) |
| 1705 | }) |
| 1706 | .await; |
| 1707 | if shadow_gate && !matches!(built, Ok(Ok(_))) { |
| 1708 | crate::superfast::record_shadow_failure(AutoRouterFailure::NotRunnable, 0); |
| 1709 | } |
| 1710 | let client = built??; |
| 1711 | let body = decision_request_body( |
| 1712 | &client, |
| 1713 | &inventory.router_model, |
| 1714 | latest_request, |
| 1715 | recent_context, |
| 1716 | session_mode, |
| 1717 | selected_thinking_mode, |
| 1718 | shadow_gate, |
| 1719 | ); |
| 1720 | // Both transports enter the existing usage ledger. TypeSafe carries its |
| 1721 | // own Custom/Unknown identity; no chat price or zero-cost claim is inherited. |
| 1722 | let request_route = |
| 1723 | client.effective_route_envelope(&inventory.router_model, chrono::Utc::now()); |
| 1724 | let observation = accounting_source.observation(); |
| 1725 | let started = Instant::now(); |
| 1726 | let outcome = tokio::time::timeout( |
| 1727 | Duration::from_secs(inventory.router_timeout_secs), |
| 1728 | client.system_one_decide(&body, observation.clone()), |
| 1729 | ) |
| 1730 | .await; |
| 1731 | let latency_ms = u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX); |
| 1732 | let wire = observation.wire_observations.drain(); |
| 1733 | let (response, failure) = match outcome { |
| 1734 | Ok(Ok(response)) => (Some(response), None), |
| 1735 | Ok(Err(failure)) => (None, Some(failure)), |
| 1736 | Err(_) => (None, Some(AutoRouterFailure::Timeout)), |
| 1737 | }; |
| 1738 | if shadow_gate { |
| 1739 | match response.as_ref() { |
| 1740 | Some(response) => { |
| 1741 | crate::superfast::record_shadow_response( |
| 1742 | response, |
| 1743 | latency_ms, |
| 1744 | &request_route, |
| 1745 | &accounting_source, |
| 1746 | ) |
| 1747 | .await; |
| 1748 | } |
| 1749 | None => { |
| 1750 | crate::superfast::record_shadow_failure( |
| 1751 | failure.unwrap_or(AutoRouterFailure::Transport), |
| 1752 | latency_ms, |
| 1753 | ); |
| 1754 | } |
| 1755 | } |
| 1756 | } |
| 1757 | if response.is_none() && wire.transmissions.is_empty() { |
| 1758 | return Ok(InventoryAutoRouteAttempt::failed( |
| 1759 | failure.unwrap_or(AutoRouterFailure::Transport), |
| 1760 | )); |
| 1761 | } |
| 1762 | let usage = Usage { |
| 1763 | input_tokens: response |
| 1764 | .as_ref() |
| 1765 | .and_then(|response| response.usage.as_ref()) |
| 1766 | .map_or(0, |usage| usage.input_tokens), |
| 1767 | output_tokens: response |
| 1768 | .as_ref() |
| 1769 | .and_then(|response| response.usage.as_ref()) |
| 1770 | .map_or(0, |usage| usage.output_tokens), |
| 1771 | ..Default::default() |
| 1772 | }; |
| 1773 | let complete = response |
| 1774 | .as_ref() |
| 1775 | .and_then(|response| response.usage.as_ref()) |
| 1776 | .is_some_and(|usage| usage.complete); |
| 1777 | let coverage = if wire.last_transmission.is_none() { |
| 1778 | if auto_route_usage_has_reported_data(&usage) { |
| 1779 | if complete { |
| 1780 | crate::llm_client::ProviderUsageCoverage::Reported |
| 1781 | } else { |
| 1782 | crate::llm_client::ProviderUsageCoverage::Incomplete |
| 1783 | } |
| 1784 | } else { |
| 1785 | crate::llm_client::ProviderUsageCoverage::Missing |
| 1786 | } |
| 1787 | } else { |
| 1788 | wire.usage_coverage(auto_route_usage_has_reported_data(&usage), complete) |
| 1789 | }; |
| 1790 | let reason = if response.is_some() { |
| 1791 | crate::cost_status::RuntimeUsageMissingReason::SuccessWithoutUsage |
| 1792 | } else { |
| 1793 | crate::cost_status::RuntimeUsageMissingReason::RequestOutcomeUnknown |
| 1794 | }; |
| 1795 | let record = accounting_source.prepare_record(&request_route, &usage, coverage, reason, &wire); |
| 1796 | if let Some(origin) = accounting_source.origin() { |
| 1797 | crate::cost_status::record_runtime_usage_async(origin.scope(), Some(origin), &record).await; |
| 1798 | } |
| 1799 | Ok(match response { |
| 1800 | Some(response) => decision_attempt_from_response( |
| 1801 | config.auto_cost_saving(), |
| 1802 | inventory, |
| 1803 | pair, |
| 1804 | Some(record), |
| 1805 | &response, |
| 1806 | latency_ms, |
| 1807 | ), |
| 1808 | None => auto_route_attempt_with_dropped_response( |
| 1809 | record, |
| 1810 | failure.unwrap_or(AutoRouterFailure::Transport), |
| 1811 | ), |
| 1812 | }) |
| 1813 | } |
| 1814 | |
| 1815 | /// A validated `choice` answer. |
| 1816 | pub struct ValidChoice { |
| 1817 | pub choice: String, |
| 1818 | pub probabilities_bp: BTreeMap<String, u16>, |
| 1819 | pub confidence_bp: u16, |
| 1820 | pub abstained: bool, |
| 1821 | } |
| 1822 | |
| 1823 | /// Validate one `choice` answer against the offered options. Any violation |
| 1824 | /// rejects the whole answer; nothing is repaired. |
| 1825 | pub fn validated_choice(answer: Option<&SystemOneAnswer>, options: &[&str]) -> Option<ValidChoice> { |
| 1826 | let answer = answer?; |
| 1827 | if answer.kind != "choice" { |
| 1828 | return None; |
| 1829 | } |
| 1830 | let choice = answer.choice.as_deref()?; |
| 1831 | if !options.contains(&choice) || answer.probabilities.len() != options.len() { |
| 1832 | return None; |
| 1833 | } |
| 1834 | let mut sum = 0.0; |
| 1835 | let mut probabilities_bp = BTreeMap::new(); |
| 1836 | for option in options { |
| 1837 | let value = (*answer.probabilities.get(*option)?)?; |
| 1838 | if !value.is_finite() || !(0.0..=1.0).contains(&value) { |
| 1839 | return None; |
| 1840 | } |
| 1841 | sum += value; |
| 1842 | probabilities_bp.insert((*option).to_string(), probability_bp(value)); |
| 1843 | } |
| 1844 | if (sum - 1.0).abs() > 0.02 { |
| 1845 | return None; |
| 1846 | } |
| 1847 | let selected = (*answer.probabilities.get(choice)?)?; |
| 1848 | if answer |
| 1849 | .probabilities |
| 1850 | .values() |
| 1851 | .any(|probability| probability.is_some_and(|v| v > selected)) |
| 1852 | { |
| 1853 | return None; |
| 1854 | } |
| 1855 | let confidence = answer.confidence?; |
| 1856 | if !confidence.is_finite() || !(0.0..=1.0).contains(&confidence) { |
| 1857 | return None; |
| 1858 | } |
| 1859 | Some(ValidChoice { |
| 1860 | choice: choice.to_string(), |
| 1861 | probabilities_bp, |
| 1862 | confidence_bp: probability_bp(confidence), |
| 1863 | abstained: answer.abstained, |
| 1864 | }) |
| 1865 | } |
| 1866 | |
| 1867 | /// One decision response settled through the existing routed-usage ledger. |
| 1868 | /// Malformed policy answers still carry provider usage; missing/all-zero usage |
| 1869 | /// remains an explicit coverage gap. The source identity is route-bound. |
| 1870 | pub fn decision_usage_batch( |
| 1871 | request_route: &EffectiveRouteEnvelope, |
| 1872 | response: &SystemOneResponse, |
| 1873 | source: &crate::cost_status::NativeUsageSource, |
| 1874 | wire: &crate::llm_client::OutboundWireObservationBatch, |
| 1875 | ) -> crate::cost_status::RuntimeUsageBatch { |
| 1876 | let usage = Usage { |
| 1877 | input_tokens: response |
| 1878 | .usage |
| 1879 | .as_ref() |
| 1880 | .map_or(0, |usage| usage.input_tokens), |
| 1881 | output_tokens: response |
| 1882 | .usage |
| 1883 | .as_ref() |
| 1884 | .map_or(0, |usage| usage.output_tokens), |
| 1885 | ..Default::default() |
| 1886 | }; |
| 1887 | let complete = response.usage.as_ref().is_some_and(|usage| usage.complete); |
| 1888 | let coverage = if wire.last_transmission.is_none() { |
| 1889 | if auto_route_usage_has_reported_data(&usage) { |
| 1890 | if complete { |
| 1891 | crate::llm_client::ProviderUsageCoverage::Reported |
| 1892 | } else { |
| 1893 | crate::llm_client::ProviderUsageCoverage::Incomplete |
| 1894 | } |
| 1895 | } else { |
| 1896 | crate::llm_client::ProviderUsageCoverage::Missing |
| 1897 | } |
| 1898 | } else { |
| 1899 | wire.usage_coverage(auto_route_usage_has_reported_data(&usage), complete) |
| 1900 | }; |
| 1901 | let record = source.prepare_record( |
| 1902 | request_route, |
| 1903 | &usage, |
| 1904 | coverage, |
| 1905 | crate::cost_status::RuntimeUsageMissingReason::SuccessWithoutUsage, |
| 1906 | wire, |
| 1907 | ); |
| 1908 | crate::cost_status::RuntimeUsageBatch { |
| 1909 | records: vec![record], |
| 1910 | ..Default::default() |
| 1911 | } |
| 1912 | } |
| 1913 | |
| 1914 | /// Turn a decoded System One response into a routing attempt. All policy is |
| 1915 | /// here, in code: the decision model does no arithmetic. |
| 1916 | fn decision_attempt_from_response( |
| 1917 | cost_saving: bool, |
| 1918 | inventory: &ModelInventory, |
| 1919 | pair: &ActiveTierPair, |
| 1920 | usage_record: Option<RuntimeUsageRecord>, |
| 1921 | response: &SystemOneResponse, |
| 1922 | latency_ms: u64, |
| 1923 | ) -> InventoryAutoRouteAttempt { |
| 1924 | let mut attempt = InventoryAutoRouteAttempt { |
| 1925 | recommendation: None, |
| 1926 | routed_usage: Vec::new(), |
| 1927 | routed_usage_drop_records: Vec::new(), |
| 1928 | routed_usage_dropped_records: 0, |
| 1929 | decision: None, |
| 1930 | failure: None, |
| 1931 | fallback_reason: None, |
| 1932 | }; |
| 1933 | if let Some(record) = usage_record { |
| 1934 | attempt.routed_usage.push(record); |
| 1935 | } |
| 1936 | |
| 1937 | // Rejected answers still incurred spend. Keep bounded diagnostic evidence |
| 1938 | // before any policy return; valid tier evidence below replaces this shell. |
| 1939 | attempt.decision = Some(AutoRouteDecisionEvidence { |
| 1940 | choice: "invalid".to_string(), |
| 1941 | probabilities_bp: Default::default(), |
| 1942 | confidence_bp: 0, |
| 1943 | min_confidence_bp: inventory.router_min_confidence_bp, |
| 1944 | abstained_questions: response.abstained_questions(&["tier", "thinking"]), |
| 1945 | cost_saving_kept_fast: false, |
| 1946 | thinking: None, |
| 1947 | provider_reported_cost_usd: response |
| 1948 | .usage |
| 1949 | .as_ref() |
| 1950 | .and_then(|usage| usage.reported_cost()), |
| 1951 | latency_ms, |
| 1952 | response_model: response |
| 1953 | .model |
| 1954 | .as_deref() |
| 1955 | .map(|model| model.chars().take(128).collect()), |
| 1956 | }); |
| 1957 | if response.answers_validated == Some(false) { |
| 1958 | attempt.failure = Some(AutoRouterFailure::InvalidAnswer); |
| 1959 | return attempt; |
| 1960 | } |
| 1961 | let Some(tier) = validated_choice(response.answers.get("tier"), &DECISION_TIER_OPTIONS) else { |
| 1962 | attempt.failure = Some(AutoRouterFailure::InvalidAnswer); |
| 1963 | return attempt; |
| 1964 | }; |
| 1965 | let min_confidence_bp = inventory.router_min_confidence_bp; |
| 1966 | // An invalid or unsure `thinking` answer drops only the effort. |
| 1967 | let thinking = validated_choice(response.answers.get("thinking"), &DECISION_THINKING_OPTIONS) |
| 1968 | .filter(|thinking| !thinking.abstained && thinking.confidence_bp >= min_confidence_bp) |
| 1969 | .map(|thinking| thinking.choice); |
| 1970 | let strong_bp = tier.probabilities_bp.get("strong").copied().unwrap_or(0); |
| 1971 | let cost_saving_kept_fast = |
| 1972 | cost_saving && tier.choice == "strong" && strong_bp < COST_SAVING_STRONG_MIN_BP; |
| 1973 | let acted = !tier.abstained && tier.confidence_bp >= min_confidence_bp; |
| 1974 | attempt.decision = Some(AutoRouteDecisionEvidence { |
| 1975 | choice: tier.choice.clone(), |
| 1976 | probabilities_bp: tier.probabilities_bp, |
| 1977 | confidence_bp: tier.confidence_bp, |
| 1978 | min_confidence_bp, |
| 1979 | abstained_questions: response.abstained_questions(&["tier", "thinking"]), |
| 1980 | cost_saving_kept_fast: acted && cost_saving_kept_fast, |
| 1981 | thinking: thinking.clone().filter(|_| acted), |
| 1982 | provider_reported_cost_usd: response |
| 1983 | .usage |
| 1984 | .as_ref() |
| 1985 | .and_then(|usage| usage.reported_cost()), |
| 1986 | latency_ms, |
| 1987 | response_model: response |
| 1988 | .model |
| 1989 | .as_deref() |
| 1990 | .map(|model| model.chars().take(128).collect()), |
| 1991 | }); |
| 1992 | if !acted { |
| 1993 | attempt.fallback_reason = Some(AutoRouteHeuristicReason::LowConfidence); |
| 1994 | return attempt; |
| 1995 | } |
| 1996 | let model = if tier.choice == "strong" && !cost_saving_kept_fast { |
| 1997 | pair.strong.clone() |
| 1998 | } else { |
| 1999 | pair.fast.clone() |
| 2000 | }; |
| 2001 | attempt.recommendation = Some(InventoryAutoRouteRecommendation { |
| 2002 | provider: pair.provider.clone(), |
| 2003 | model, |
| 2004 | reasoning_effort: thinking |
| 2005 | .as_deref() |
| 2006 | .and_then(parse_auto_route_reasoning_effort), |
| 2007 | }); |
| 2008 | attempt |
| 2009 | } |
| 2010 | |
| 2011 | fn inventory_auto_router_system_prompt(inventory: &ModelInventory, cost_saving: bool) -> String { |
| 2012 | let mut prompt = if inventory.cross_provider_auto { |
| 2013 | String::new() |
| 2014 | } else { |
| 2015 | // The inventory JSON below is already scoped to the active provider |
| 2016 | // (#4411); say so, so the classifier does not try to name one it was |
| 2017 | // never shown. |
| 2018 | format!( |
| 2019 | "Auto routing is scoped to the active provider `{}`. Every model in the inventory \ |
| 2020 | below belongs to it; never select another provider.\n\n", |
| 2021 | inventory.active_identity.key.as_str() |
| 2022 | ) |
| 2023 | }; |
| 2024 | prompt.push_str(&format!( |
| 2025 | "You are the codewhale model-routing classifier. Return only compact JSON: \ |
| 2026 | {{\"provider\":\"<provider>\",\"model\":\"<model>\",\"thinking\":\"off|high|max\"}}.\n\ |
| 2027 | Choose only provider/model pairs present in the inventory JSON. Use off only for trivial no-tool answers, \ |
| 2028 | high for ordinary reasoning, and max for agentic, coding, multi-file, release, architecture, debugging, \ |
| 2029 | security, tool-heavy, or uncertain work.\n\nInventory JSON:\n{}", |
| 2030 | inventory.router_context_json() |
| 2031 | )); |
| 2032 | |
| 2033 | if cost_saving { |
| 2034 | if let Some(ActiveTierPair { |
| 2035 | provider, |
| 2036 | strong, |
| 2037 | fast, |
| 2038 | }) = runnable_active_pair(inventory) |
| 2039 | { |
| 2040 | prompt.push_str(&format!( |
| 2041 | "\n\nCost-saving mode is ON. For the active provider `{}`, `{fast}` is the fast tier \ |
| 2042 | and `{strong}` is the strong tier. Prefer `{fast}` for ambiguous, routine, or single-step work. \ |
| 2043 | Select `{strong}` only when the request is unmistakably agentic, multi-step, architecture/design, \ |
| 2044 | security review, debugging, or otherwise clearly beyond the fast tier. Keep the selected model paired \ |
| 2045 | with provider `{}`.", |
| 2046 | provider.key.as_str(), |
| 2047 | provider.key.as_str() |
| 2048 | )); |
| 2049 | } else { |
| 2050 | prompt.push_str( |
| 2051 | "\n\nCost-saving mode is ON, but the active provider has no known runnable fast sibling. \ |
| 2052 | Do not invent a model or cross-provider downgrade solely to save cost.", |
| 2053 | ); |
| 2054 | } |
| 2055 | } |
| 2056 | |
| 2057 | prompt |
| 2058 | } |
| 2059 | |
| 2060 | fn parse_inventory_auto_route_recommendation( |
| 2061 | raw: &str, |
| 2062 | inventory: &ModelInventory, |
| 2063 | ) -> Option<InventoryAutoRouteRecommendation> { |
| 2064 | let json = extract_first_json_object(raw)?; |
| 2065 | let value: serde_json::Value = serde_json::from_str(json).ok()?; |
| 2066 | let name = value.get("provider").and_then(serde_json::Value::as_str)?; |
| 2067 | let model = value.get("model").and_then(serde_json::Value::as_str)?; |
| 2068 | // Match only identities offered in this captured inventory. A name cannot |
| 2069 | // create a route, borrow a brand's authority, or broaden the Auto scope. |
| 2070 | let mut matches = inventory.candidates.iter().filter(|candidate| { |
| 2071 | let offered = candidate.identity.key.as_str() == name |
| 2072 | || candidate.identity.compatibility().is_some_and(|row| { |
| 2073 | row.tui_wire_tag == name |
| 2074 | || row |
| 2075 | .selector_aliases |
| 2076 | .iter() |
| 2077 | .any(|alias| alias.eq_ignore_ascii_case(name)) |
| 2078 | }); |
| 2079 | offered |
| 2080 | && inventory.auto_scope_allows(candidate.identity.key.as_str()) |
| 2081 | && candidate.readiness.can_attempt() |
| 2082 | && (candidate.model == model |
| 2083 | || (!candidate.user_declared && candidate.model.eq_ignore_ascii_case(model))) |
| 2084 | }); |
| 2085 | let candidate = matches.next()?; |
| 2086 | if matches.next().is_some() { |
| 2087 | return None; |
| 2088 | } |
| 2089 | let reasoning_effort = value |
| 2090 | .get("thinking") |
| 2091 | .or_else(|| value.get("reasoning_effort")) |
| 2092 | .or_else(|| value.get("effort")) |
| 2093 | .and_then(serde_json::Value::as_str) |
| 2094 | .and_then(parse_auto_route_reasoning_effort); |
| 2095 | Some(InventoryAutoRouteRecommendation { |
| 2096 | provider: candidate.identity.clone(), |
| 2097 | model: candidate.model.clone(), |
| 2098 | reasoning_effort, |
| 2099 | }) |
| 2100 | } |
| 2101 | |
| 2102 | fn auto_route_prompt( |
| 2103 | latest_request: &str, |
| 2104 | recent_context: &str, |
| 2105 | session_mode: &str, |
| 2106 | selected_model_mode: &str, |
| 2107 | selected_thinking_mode: &str, |
| 2108 | ) -> String { |
| 2109 | format!( |
| 2110 | "Session mode: {}\nSelected model mode: {}\nSelected thinking mode: {}\n\nRecent context:\n{}\n\nLatest user request:\n{}\n\nReturn JSON only.", |
| 2111 | session_mode, |
| 2112 | selected_model_mode, |
| 2113 | selected_thinking_mode, |
| 2114 | if recent_context.trim().is_empty() { |
| 2115 | "No prior context." |
| 2116 | } else { |
| 2117 | recent_context |
| 2118 | }, |
| 2119 | truncate_for_auto_router(latest_request, 4_000) |
| 2120 | ) |
| 2121 | } |
| 2122 | |
| 2123 | fn classifier_prompt( |
| 2124 | client: &CodewhaleClient, |
| 2125 | latest_request: &str, |
| 2126 | recent_context: &str, |
| 2127 | session_mode: &str, |
| 2128 | selected_model_mode: &str, |
| 2129 | selected_thinking_mode: &str, |
| 2130 | ) -> String { |
| 2131 | client.redact_model_bound_text(&auto_route_prompt( |
| 2132 | latest_request, |
| 2133 | recent_context, |
| 2134 | session_mode, |
| 2135 | selected_model_mode, |
| 2136 | selected_thinking_mode, |
| 2137 | )) |
| 2138 | } |
| 2139 | |
| 2140 | fn message_response_text(response: &MessageResponse) -> String { |
| 2141 | let mut out = String::new(); |
| 2142 | for block in &response.content { |
| 2143 | match block { |
| 2144 | ContentBlock::Text { text, .. } | ContentBlock::ToolResult { content: text, .. } => { |
| 2145 | append_router_text(&mut out, text); |
| 2146 | } |
| 2147 | ContentBlock::Thinking { thinking, .. } => { |
| 2148 | append_router_text(&mut out, thinking); |
| 2149 | } |
| 2150 | ContentBlock::ToolUse { name, .. } => { |
| 2151 | append_router_text(&mut out, &format!("[tool call: {name}]")); |
| 2152 | } |
| 2153 | _ => {} |
| 2154 | } |
| 2155 | } |
| 2156 | out |
| 2157 | } |
| 2158 | |
| 2159 | fn append_router_text(out: &mut String, text: &str) { |
| 2160 | if !out.is_empty() { |
| 2161 | out.push('\n'); |
| 2162 | } |
| 2163 | out.push_str(text); |
| 2164 | } |
| 2165 | |
| 2166 | pub fn truncate_for_auto_router(text: &str, max_chars: usize) -> String { |
| 2167 | let mut chars = text.chars(); |
| 2168 | let truncated: String = chars.by_ref().take(max_chars).collect(); |
| 2169 | if chars.next().is_some() { |
| 2170 | format!("{truncated}...") |
| 2171 | } else { |
| 2172 | truncated |
| 2173 | } |
| 2174 | } |
| 2175 | |
| 2176 | #[cfg(test)] |
| 2177 | mod tests { |
| 2178 | use super::*; |
| 2179 | |
| 2180 | struct ProviderCatalogReset; |
| 2181 | |
| 2182 | impl Drop for ProviderCatalogReset { |
| 2183 | fn drop(&mut self) { |
| 2184 | crate::provider_catalog_live::reset_cache_for_test(); |
| 2185 | crate::provider_lake::clear_live_snapshot(); |
| 2186 | } |
| 2187 | } |
| 2188 | |
| 2189 | fn priced_openrouter_delta( |
| 2190 | model: &str, |
| 2191 | fingerprint: &str, |
| 2192 | fetched_at: u64, |
| 2193 | input: f64, |
| 2194 | output: f64, |
| 2195 | ) -> codewhale_config::catalog::ProviderCatalogDelta { |
| 2196 | use codewhale_config::catalog::{CatalogOffering, CatalogSource, ProviderCatalogDelta}; |
| 2197 | |
| 2198 | ProviderCatalogDelta { |
| 2199 | provider: ProviderKind::Openrouter.as_str().to_string(), |
| 2200 | base_url_fingerprint: fingerprint.to_string(), |
| 2201 | fetched_at, |
| 2202 | offerings: vec![CatalogOffering { |
| 2203 | provider: ProviderKind::Openrouter.as_str().to_string(), |
| 2204 | wire_model_id: model.to_string(), |
| 2205 | endpoint_key: "chat".to_string(), |
| 2206 | source: CatalogSource::Live { |
| 2207 | base_url_fingerprint: fingerprint.to_string(), |
| 2208 | fetched_at, |
| 2209 | }, |
| 2210 | cost: Some(codewhale_config::models_dev::ModelsDevCost { |
| 2211 | input: Some(input), |
| 2212 | output: Some(output), |
| 2213 | cache_read: Some(input / 2.0), |
| 2214 | cache_write: None, |
| 2215 | ..Default::default() |
| 2216 | }), |
| 2217 | ..CatalogOffering::default() |
| 2218 | }], |
| 2219 | } |
| 2220 | } |
| 2221 | |
| 2222 | fn classifier_response( |
| 2223 | id: &str, |
| 2224 | text: &str, |
| 2225 | stop_reason: &str, |
| 2226 | usage: codewhale_models::Usage, |
| 2227 | ) -> MessageResponse { |
| 2228 | MessageResponse { |
| 2229 | tool_projection_warning: None, |
| 2230 | id: id.to_string(), |
| 2231 | r#type: "message".to_string(), |
| 2232 | role: "assistant".to_string(), |
| 2233 | content: vec![ContentBlock::Text { |
| 2234 | text: text.to_string(), |
| 2235 | cache_control: None, |
| 2236 | }], |
| 2237 | model: "router-response-alias-must-not-price".to_string(), |
| 2238 | stop_reason: Some(stop_reason.to_string()), |
| 2239 | stop_sequence: None, |
| 2240 | container: None, |
| 2241 | usage, |
| 2242 | title: None, |
| 2243 | stop_details: None, |
| 2244 | refusal: None, |
| 2245 | } |
| 2246 | } |
| 2247 | |
| 2248 | #[test] |
| 2249 | fn classifier_semantic_fallbacks_keep_exact_quotes_and_replay_once() { |
| 2250 | let _env_lock = crate::test_support::lock_test_env(); |
| 2251 | let _live = crate::provider_lake::lock_live_snapshot(); |
| 2252 | let home = tempfile::tempdir().expect("test home"); |
| 2253 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", home.path()); |
| 2254 | let _reset = ProviderCatalogReset; |
| 2255 | crate::provider_catalog_live::reset_cache_for_test(); |
| 2256 | crate::provider_lake::clear_live_snapshot(); |
| 2257 | |
| 2258 | let model = "synthetic/openrouter-auto-classifier"; |
| 2259 | let config = { |
| 2260 | let __cw_config_init_0_0 = Some("openrouter".to_string()); |
| 2261 | let __cw_config_init_0_1 = Some(codewhale_runtime::config::ProvidersConfig { |
| 2262 | openrouter: codewhale_runtime::config::ProviderConfig { |
| 2263 | api_key: Some("test-openrouter-key".to_string()), |
| 2264 | base_url: Some( |
| 2265 | codewhale_config::descriptors::defaults::DEFAULT_OPENROUTER_BASE_URL |
| 2266 | .to_string(), |
| 2267 | ), |
| 2268 | model: Some(model.to_string()), |
| 2269 | ..Default::default() |
| 2270 | }, |
| 2271 | ..Default::default() |
| 2272 | }); |
| 2273 | let __cw_config_init_0_2 = Some(codewhale_runtime::config::AutoConfig { |
| 2274 | cost_saving: None, |
| 2275 | cross_provider: None, |
| 2276 | router: Some(codewhale_runtime::config::AutoRouterConfig { |
| 2277 | provider: Some("openrouter".to_string()), |
| 2278 | model: Some(model.to_string()), |
| 2279 | thinking: Some("off".to_string()), |
| 2280 | timeout_secs: None, |
| 2281 | ..Default::default() |
| 2282 | }), |
| 2283 | }); |
| 2284 | let mut __cw_config_init_0_value: Config = Default::default(); |
| 2285 | __cw_config_init_0_value.provider = __cw_config_init_0_0; |
| 2286 | __cw_config_init_0_value.providers = __cw_config_init_0_1; |
| 2287 | __cw_config_init_0_value.auto = __cw_config_init_0_2; |
| 2288 | __cw_config_init_0_value |
| 2289 | }; |
| 2290 | let inventory = ModelInventory::from_config(&config).unwrap(); |
| 2291 | assert!( |
| 2292 | inventory |
| 2293 | .candidate(ProviderKind::Openrouter.as_str(), model) |
| 2294 | .is_some() |
| 2295 | ); |
| 2296 | let client = CodewhaleClient::new(&config).expect("OpenRouter classifier client"); |
| 2297 | let fingerprint = codewhale_config::catalog::base_url_fingerprint( |
| 2298 | codewhale_config::descriptors::defaults::DEFAULT_OPENROUTER_BASE_URL, |
| 2299 | ); |
| 2300 | let first_at = chrono::Utc::now(); |
| 2301 | let fetched_at = u64::try_from(first_at.timestamp()).expect("nonnegative timestamp"); |
| 2302 | |
| 2303 | crate::provider_catalog_live::record_success(priced_openrouter_delta( |
| 2304 | model, |
| 2305 | &fingerprint, |
| 2306 | fetched_at, |
| 2307 | 1.0, |
| 2308 | 4.0, |
| 2309 | )); |
| 2310 | let first_route = client.effective_route_envelope(model, first_at); |
| 2311 | let valid = { |
| 2312 | let native = crate::cost_status::NativeUsageSource::capture( |
| 2313 | format!( |
| 2314 | "auto-router:{}", |
| 2315 | crate::cost_status::usage_source_fingerprint(&uuid::Uuid::new_v4().to_string()) |
| 2316 | ), |
| 2317 | crate::cost_status::UsageSpendOwner::Auxiliary, |
| 2318 | ); |
| 2319 | let route = first_route; |
| 2320 | let response = classifier_response( |
| 2321 | "same-provider-response-id", |
| 2322 | &format!(r#"{{"provider":"openrouter","model":"{model}","thinking":"off"}}"#), |
| 2323 | "stop", |
| 2324 | codewhale_models::Usage { |
| 2325 | input_tokens: 10, |
| 2326 | output_tokens: 2, |
| 2327 | prompt_cache_hit_tokens: Some(3), |
| 2328 | ..Default::default() |
| 2329 | }, |
| 2330 | ); |
| 2331 | let record = native.reported(&route, &response.usage); |
| 2332 | auto_route_attempt_from_response(route, &response, &inventory, record) |
| 2333 | }; |
| 2334 | |
| 2335 | // Replace the live row in the same Unix second. The first routed |
| 2336 | // record must keep its old immutable revision and the new attempt must |
| 2337 | // freeze a distinct one at its own dispatch boundary. |
| 2338 | crate::provider_catalog_live::record_success(priced_openrouter_delta( |
| 2339 | model, |
| 2340 | &fingerprint, |
| 2341 | fetched_at, |
| 2342 | 9.0, |
| 2343 | 19.0, |
| 2344 | )); |
| 2345 | let second_at = first_at + chrono::Duration::nanoseconds(1); |
| 2346 | let invalid = { |
| 2347 | let native = crate::cost_status::NativeUsageSource::capture( |
| 2348 | format!( |
| 2349 | "auto-router:{}", |
| 2350 | crate::cost_status::usage_source_fingerprint(&uuid::Uuid::new_v4().to_string()) |
| 2351 | ), |
| 2352 | crate::cost_status::UsageSpendOwner::Auxiliary, |
| 2353 | ); |
| 2354 | let route = client.effective_route_envelope(model, second_at); |
| 2355 | let response = classifier_response( |
| 2356 | "same-provider-response-id", |
| 2357 | "not valid route json", |
| 2358 | "stop", |
| 2359 | codewhale_models::Usage { |
| 2360 | input_tokens: 11, |
| 2361 | output_tokens: 3, |
| 2362 | ..Default::default() |
| 2363 | }, |
| 2364 | ); |
| 2365 | let record = native.reported(&route, &response.usage); |
| 2366 | auto_route_attempt_from_response(route, &response, &inventory, record) |
| 2367 | }; |
| 2368 | let incomplete = { |
| 2369 | let native = crate::cost_status::NativeUsageSource::capture( |
| 2370 | format!( |
| 2371 | "auto-router:{}", |
| 2372 | crate::cost_status::usage_source_fingerprint(&uuid::Uuid::new_v4().to_string()) |
| 2373 | ), |
| 2374 | crate::cost_status::UsageSpendOwner::Auxiliary, |
| 2375 | ); |
| 2376 | let route = client |
| 2377 | .effective_route_envelope(model, second_at + chrono::Duration::nanoseconds(1)); |
| 2378 | let response = classifier_response( |
| 2379 | "same-provider-response-id", |
| 2380 | &format!(r#"{{"provider":"openrouter","model":"{model}"}}"#), |
| 2381 | "length", |
| 2382 | codewhale_models::Usage { |
| 2383 | input_tokens: 12, |
| 2384 | output_tokens: 4, |
| 2385 | ..Default::default() |
| 2386 | }, |
| 2387 | ); |
| 2388 | let record = native.reported(&route, &response.usage); |
| 2389 | auto_route_attempt_from_response(route, &response, &inventory, record) |
| 2390 | }; |
| 2391 | let missing_usage_route = |
| 2392 | client.effective_route_envelope(model, second_at + chrono::Duration::nanoseconds(2)); |
| 2393 | let missing_usage = { |
| 2394 | let native = crate::cost_status::NativeUsageSource::capture( |
| 2395 | format!( |
| 2396 | "auto-router:{}", |
| 2397 | crate::cost_status::usage_source_fingerprint(&uuid::Uuid::new_v4().to_string()) |
| 2398 | ), |
| 2399 | crate::cost_status::UsageSpendOwner::Auxiliary, |
| 2400 | ); |
| 2401 | let route = missing_usage_route.clone(); |
| 2402 | let response = classifier_response( |
| 2403 | "missing-usage-response-id", |
| 2404 | "not valid route json", |
| 2405 | "stop", |
| 2406 | codewhale_models::Usage::default(), |
| 2407 | ); |
| 2408 | let record = native.reported(&route, &response.usage); |
| 2409 | auto_route_attempt_from_provider_response(route, &response, &inventory, record) |
| 2410 | }; |
| 2411 | assert_eq!(missing_usage.routed_usage.len(), 1); |
| 2412 | assert_eq!(missing_usage.routed_usage_dropped_records, 0); |
| 2413 | assert!(missing_usage.routed_usage_drop_records.is_empty()); |
| 2414 | assert_eq!( |
| 2415 | missing_usage.routed_usage[0].usage.route, |
| 2416 | missing_usage_route.sanitized_for_persistence() |
| 2417 | ); |
| 2418 | assert_eq!( |
| 2419 | missing_usage.routed_usage[0] |
| 2420 | .settlement |
| 2421 | .as_ref() |
| 2422 | .unwrap() |
| 2423 | .coverage, |
| 2424 | crate::llm_client::ProviderUsageCoverage::Missing |
| 2425 | ); |
| 2426 | assert!( |
| 2427 | missing_usage.routed_usage[0] |
| 2428 | .source_id |
| 2429 | .starts_with("auto-router:") |
| 2430 | ); |
| 2431 | assert!( |
| 2432 | !missing_usage.routed_usage[0] |
| 2433 | .source_id |
| 2434 | .contains("missing-usage-response-id") |
| 2435 | ); |
| 2436 | |
| 2437 | let transport = { |
| 2438 | let native = crate::cost_status::NativeUsageSource::capture( |
| 2439 | format!("auto-router:{}", uuid::Uuid::new_v4()), |
| 2440 | crate::cost_status::UsageSpendOwner::Auxiliary, |
| 2441 | ); |
| 2442 | let route = client |
| 2443 | .effective_route_envelope(model, second_at + chrono::Duration::nanoseconds(3)); |
| 2444 | let record = native.prepare( |
| 2445 | &route, |
| 2446 | &codewhale_models::Usage::default(), |
| 2447 | crate::llm_client::ProviderUsageCoverage::Missing, |
| 2448 | crate::cost_status::RuntimeUsageMissingReason::RequestOutcomeUnknown, |
| 2449 | ); |
| 2450 | auto_route_attempt_with_dropped_response(record, AutoRouterFailure::Transport) |
| 2451 | }; |
| 2452 | assert_eq!(transport.routed_usage_dropped_records, 0); |
| 2453 | assert!(transport.routed_usage_drop_records.is_empty()); |
| 2454 | assert_eq!(transport.routed_usage.len(), 1); |
| 2455 | assert_eq!( |
| 2456 | transport.routed_usage[0] |
| 2457 | .settlement |
| 2458 | .as_ref() |
| 2459 | .unwrap() |
| 2460 | .coverage, |
| 2461 | crate::llm_client::ProviderUsageCoverage::Missing |
| 2462 | ); |
| 2463 | |
| 2464 | let fallback = auto_route_declared_fallback(&config, &inventory); |
| 2465 | let valid = auto_route_from_classifier_attempt(fallback.clone(), &inventory, valid); |
| 2466 | let invalid = auto_route_from_classifier_attempt(fallback.clone(), &inventory, invalid); |
| 2467 | let incomplete = auto_route_from_classifier_attempt(fallback, &inventory, incomplete); |
| 2468 | assert_eq!(valid.source, AutoRouteSource::FlashRouter); |
| 2469 | for fallback in [&invalid, &incomplete] { |
| 2470 | assert_eq!(fallback.source, AutoRouteSource::Heuristic); |
| 2471 | assert!(matches!( |
| 2472 | fallback.receipt.as_ref().map(|receipt| receipt.reason), |
| 2473 | Some(AutoRouteReason::ClassifierFallback(_)) |
| 2474 | )); |
| 2475 | assert_eq!(fallback.routed_usage.len(), 1); |
| 2476 | assert_eq!(fallback.routed_usage_dropped_records, 0); |
| 2477 | } |
| 2478 | assert_eq!(valid.routed_usage.len(), 1); |
| 2479 | assert_eq!(valid.routed_usage[0].usage.usage.input_tokens, 10); |
| 2480 | assert_eq!( |
| 2481 | valid.routed_usage[0].usage.usage.prompt_cache_hit_tokens, |
| 2482 | Some(3) |
| 2483 | ); |
| 2484 | |
| 2485 | let first_quote = valid.routed_usage[0] |
| 2486 | .usage |
| 2487 | .route |
| 2488 | .provider_live_pricing |
| 2489 | .as_ref() |
| 2490 | .expect("first exact quote"); |
| 2491 | let second_quote = invalid.routed_usage[0] |
| 2492 | .usage |
| 2493 | .route |
| 2494 | .provider_live_pricing |
| 2495 | .as_ref() |
| 2496 | .expect("replacement exact quote"); |
| 2497 | assert_ne!(first_quote.catalog_revision, second_quote.catalog_revision); |
| 2498 | assert_eq!(first_quote.input_per_million.as_deref(), Some("1")); |
| 2499 | assert_eq!(second_quote.input_per_million.as_deref(), Some("9")); |
| 2500 | |
| 2501 | let records = valid |
| 2502 | .routed_usage |
| 2503 | .iter() |
| 2504 | .chain(&invalid.routed_usage) |
| 2505 | .chain(&incomplete.routed_usage) |
| 2506 | .cloned() |
| 2507 | .collect::<Vec<_>>(); |
| 2508 | assert_eq!(records.len(), 3); |
| 2509 | assert!(records.iter().all(|record| { |
| 2510 | record.source_id.starts_with("auto-router:") |
| 2511 | && record.source_id.len() == "auto-router:".len() + 64 |
| 2512 | && !record.source_id.contains("same-provider-response-id") |
| 2513 | })); |
| 2514 | |
| 2515 | // Exercise the canonical sink exactly as selection consumers do: |
| 2516 | // replaying any record cannot add parent-route spend or a second |
| 2517 | // routed segment, while distinct dispatches remain distinct. |
| 2518 | let _cost_scope = crate::cost_status::test_scope(); |
| 2519 | let directory = tempfile::tempdir().unwrap(); |
| 2520 | let manager = |
| 2521 | crate::session_manager::SessionManager::new(directory.path().to_path_buf()).unwrap(); |
| 2522 | for record in &records { |
| 2523 | for _ in 0..2 { |
| 2524 | crate::usage_persistence::report_runtime_usage_record_for_origin_with_manager( |
| 2525 | crate::cost_status::scope_token(), |
| 2526 | "router-cost-fixture", |
| 2527 | "router-turn", |
| 2528 | record, |
| 2529 | &manager, |
| 2530 | ) |
| 2531 | .unwrap(); |
| 2532 | } |
| 2533 | } |
| 2534 | let pending = crate::cost_status::drain(); |
| 2535 | assert_eq!(pending.source_records.len(), records.len()); |
| 2536 | let mut cost = crate::session_manager::SessionCostSnapshot::default(); |
| 2537 | for record in &pending.source_records { |
| 2538 | cost.project_usage_record(record).unwrap(); |
| 2539 | } |
| 2540 | assert_eq!(cost.usage_source_fingerprints.len(), records.len()); |
| 2541 | assert_eq!(cost.priced_turns, records.len() as u32); |
| 2542 | assert_eq!(cost.unpriced_turns, 0); |
| 2543 | } |
| 2544 | |
| 2545 | #[test] |
| 2546 | fn auto_model_reasoning_keeps_model_and_thinking_choices_independent() { |
| 2547 | assert_eq!( |
| 2548 | resolve_auto_model_reasoning(Some(ReasoningEffort::Low), Some(ReasoningEffort::Max)), |
| 2549 | (Some(ReasoningEffort::Low), false) |
| 2550 | ); |
| 2551 | assert_eq!( |
| 2552 | resolve_auto_model_reasoning(Some(ReasoningEffort::Auto), Some(ReasoningEffort::Max)), |
| 2553 | (Some(ReasoningEffort::Max), true) |
| 2554 | ); |
| 2555 | assert_eq!( |
| 2556 | resolve_auto_model_reasoning(None, Some(ReasoningEffort::High)), |
| 2557 | (Some(ReasoningEffort::High), true) |
| 2558 | ); |
| 2559 | } |
| 2560 | |
| 2561 | #[test] |
| 2562 | fn auto_route_prompt_uses_current_session_mode() { |
| 2563 | let prompt = auto_route_prompt( |
| 2564 | "Please explain the change before editing files.", |
| 2565 | "No prior context.", |
| 2566 | "plan", |
| 2567 | "auto", |
| 2568 | "auto", |
| 2569 | ); |
| 2570 | |
| 2571 | assert!( |
| 2572 | prompt.starts_with("Session mode: plan\n"), |
| 2573 | "auto-route prompt should reflect the active session mode, got: {prompt}" |
| 2574 | ); |
| 2575 | } |
| 2576 | |
| 2577 | #[test] |
| 2578 | fn classifier_prompt_redacts_secret_after_tool_result_flattening() { |
| 2579 | let secret = "cw-router-secret-should-never-leave-process"; |
| 2580 | let config = |
| 2581 | <Config as Default>::default().with_legacy_root(Some(secret.to_string()), None); |
| 2582 | let client = CodewhaleClient::new(&config).expect("classifier client"); |
| 2583 | // `recent_auto_router_context` converts ToolResult blocks into ordinary |
| 2584 | // text before this boundary. Exercise that exact flattened shape. |
| 2585 | let recent_context = format!("assistant: [tool result] token={secret}"); |
| 2586 | |
| 2587 | let prompt = classifier_prompt( |
| 2588 | &client, |
| 2589 | "continue the investigation", |
| 2590 | &recent_context, |
| 2591 | "agent", |
| 2592 | "auto", |
| 2593 | "auto", |
| 2594 | ); |
| 2595 | |
| 2596 | assert!( |
| 2597 | !prompt.contains(secret), |
| 2598 | "flattened tool-result secret leaked" |
| 2599 | ); |
| 2600 | assert!( |
| 2601 | prompt.contains(codewhale_config::persistence::REDACTED), |
| 2602 | "secret should be visibly redacted" |
| 2603 | ); |
| 2604 | assert!(prompt.contains("continue the investigation")); |
| 2605 | } |
| 2606 | |
| 2607 | #[test] |
| 2608 | fn inventory_auto_router_prompt_names_cost_saving_zai_pair() { |
| 2609 | let _env_lock = crate::test_support::lock_test_env(); |
| 2610 | let _deepseek = crate::test_support::EnvVarGuard::remove("DEEPSEEK_API_KEY"); |
| 2611 | let _zai = crate::test_support::EnvVarGuard::set("ZAI_API_KEY", "zai-key"); |
| 2612 | let config = { |
| 2613 | let __cw_config_init_2_0 = Some("zai".to_string()); |
| 2614 | let mut __cw_config_init_2_value: Config = Default::default(); |
| 2615 | __cw_config_init_2_value.provider = __cw_config_init_2_0; |
| 2616 | __cw_config_init_2_value |
| 2617 | }; |
| 2618 | let inventory = ModelInventory::from_config(&config).unwrap(); |
| 2619 | |
| 2620 | let balanced = inventory_auto_router_system_prompt(&inventory, false); |
| 2621 | let cost_saving = inventory_auto_router_system_prompt(&inventory, true); |
| 2622 | |
| 2623 | assert!(!balanced.contains("Cost-saving mode is ON")); |
| 2624 | assert!( |
| 2625 | cost_saving.contains( |
| 2626 | "For the active provider `zai`, `GLM-5.3-Flash` is the fast tier and `GLM-5.3` is the strong tier" |
| 2627 | ), |
| 2628 | "cost-saving classifier policy must name the provider-safe pair: {cost_saving}" |
| 2629 | ); |
| 2630 | assert!( |
| 2631 | cost_saving.contains("Keep the selected model paired with provider `zai`"), |
| 2632 | "cost-saving policy must preserve provider/model validation: {cost_saving}" |
| 2633 | ); |
| 2634 | } |
| 2635 | |
| 2636 | #[test] |
| 2637 | fn auto_route_effort_normalization_is_provider_aware() { |
| 2638 | // Slice 4, D2: the Auto path delegates to the canonical route |
| 2639 | // normalizer with an unresolved route. Two providers where the deleted |
| 2640 | // local copy disagreed with the authority are pinned explicitly. |
| 2641 | assert_eq!( |
| 2642 | normalize_auto_route_effort_for_provider(ProviderKind::Deepseek, ReasoningEffort::Low), |
| 2643 | ReasoningEffort::Low, |
| 2644 | "first-party DeepSeek documents low|high|max, so the canonical normalizer keeps low" |
| 2645 | ); |
| 2646 | assert_eq!( |
| 2647 | normalize_auto_route_effort_for_provider( |
| 2648 | ProviderKind::Deepseek, |
| 2649 | ReasoningEffort::Medium |
| 2650 | ), |
| 2651 | ReasoningEffort::High |
| 2652 | ); |
| 2653 | assert_eq!( |
| 2654 | normalize_auto_route_effort_for_provider( |
| 2655 | ProviderKind::OllamaCloud, |
| 2656 | ReasoningEffort::Minimal |
| 2657 | ), |
| 2658 | ReasoningEffort::Low, |
| 2659 | "OllamaCloud folds the Codewhale-only `minimal` spelling onto low" |
| 2660 | ); |
| 2661 | assert_eq!( |
| 2662 | normalize_auto_route_effort_for_provider( |
| 2663 | ProviderKind::OllamaCloud, |
| 2664 | ReasoningEffort::Ultra |
| 2665 | ), |
| 2666 | ReasoningEffort::Max |
| 2667 | ); |
| 2668 | // A provider with no exact-route rule keeps the historic collapse. |
| 2669 | assert_eq!( |
| 2670 | normalize_auto_route_effort_for_provider(ProviderKind::Moonshot, ReasoningEffort::Low), |
| 2671 | ReasoningEffort::High |
| 2672 | ); |
| 2673 | assert_eq!( |
| 2674 | normalize_auto_route_effort_for_provider(ProviderKind::Moonshot, ReasoningEffort::Auto), |
| 2675 | ReasoningEffort::Auto |
| 2676 | ); |
| 2677 | assert_eq!( |
| 2678 | normalize_auto_route_effort_for_provider(ProviderKind::Moonshot, ReasoningEffort::Max), |
| 2679 | ReasoningEffort::Max |
| 2680 | ); |
| 2681 | // Codex keeps its provider-level mapping (off -> low, auto -> medium). |
| 2682 | assert_eq!( |
| 2683 | normalize_auto_route_effort_for_provider( |
| 2684 | ProviderKind::OpenaiCodex, |
| 2685 | ReasoningEffort::Low |
| 2686 | ), |
| 2687 | ReasoningEffort::Low |
| 2688 | ); |
| 2689 | assert_eq!( |
| 2690 | normalize_auto_route_effort_for_provider( |
| 2691 | ProviderKind::OpenaiCodex, |
| 2692 | ReasoningEffort::Medium |
| 2693 | ), |
| 2694 | ReasoningEffort::Medium |
| 2695 | ); |
| 2696 | assert_eq!( |
| 2697 | normalize_auto_route_effort_for_provider( |
| 2698 | ProviderKind::OpenaiCodex, |
| 2699 | ReasoningEffort::Off |
| 2700 | ), |
| 2701 | ReasoningEffort::Low |
| 2702 | ); |
| 2703 | } |
| 2704 | |
| 2705 | #[test] |
| 2706 | fn configured_route_effort_normalizer_keeps_kimi_code_low_medium_local() { |
| 2707 | let mut config = { |
| 2708 | let __cw_config_init_3_0 = Some("moonshot".to_string()); |
| 2709 | let __cw_config_init_3_1 = Some(codewhale_runtime::config::ProvidersConfig { |
| 2710 | moonshot: codewhale_runtime::config::ProviderConfig { |
| 2711 | base_url: Some( |
| 2712 | codewhale_config::descriptors::defaults::DEFAULT_KIMI_CODE_BASE_URL |
| 2713 | .to_string(), |
| 2714 | ), |
| 2715 | model: Some("k3".to_string()), |
| 2716 | ..Default::default() |
| 2717 | }, |
| 2718 | ..Default::default() |
| 2719 | }); |
| 2720 | let mut __cw_config_init_3_value: Config = Default::default(); |
| 2721 | __cw_config_init_3_value.provider = __cw_config_init_3_0; |
| 2722 | __cw_config_init_3_value.providers = __cw_config_init_3_1; |
| 2723 | __cw_config_init_3_value |
| 2724 | }; |
| 2725 | assert_eq!( |
| 2726 | normalize_auto_route_effort_for_configured_route( |
| 2727 | &config, |
| 2728 | &(config).test_identity_for_kind(ProviderKind::Moonshot), |
| 2729 | "k3", |
| 2730 | ReasoningEffort::Low, |
| 2731 | ), |
| 2732 | ReasoningEffort::Low |
| 2733 | ); |
| 2734 | assert_eq!( |
| 2735 | normalize_auto_route_effort_for_configured_route( |
| 2736 | &config, |
| 2737 | &(config).test_identity_for_kind(ProviderKind::Moonshot), |
| 2738 | "k3", |
| 2739 | ReasoningEffort::Medium, |
| 2740 | ), |
| 2741 | ReasoningEffort::Medium |
| 2742 | ); |
| 2743 | |
| 2744 | config |
| 2745 | .providers |
| 2746 | .as_mut() |
| 2747 | .expect("providers") |
| 2748 | .moonshot |
| 2749 | .base_url = |
| 2750 | Some(codewhale_config::descriptors::defaults::DEFAULT_MOONSHOT_BASE_URL.to_string()); |
| 2751 | assert_eq!( |
| 2752 | normalize_auto_route_effort_for_configured_route( |
| 2753 | &config, |
| 2754 | &(config).test_identity_for_kind(ProviderKind::Moonshot), |
| 2755 | "k3", |
| 2756 | ReasoningEffort::Low, |
| 2757 | ), |
| 2758 | ReasoningEffort::High |
| 2759 | ); |
| 2760 | } |
| 2761 | |
| 2762 | #[test] |
| 2763 | fn inventory_auto_route_recommendation_requires_runnable_pair() { |
| 2764 | let _env_lock = crate::test_support::lock_test_env(); |
| 2765 | let _deepseek = crate::test_support::EnvVarGuard::set("DEEPSEEK_API_KEY", "ds-key"); |
| 2766 | let _zai = crate::test_support::EnvVarGuard::set("ZAI_API_KEY", "zai-key"); |
| 2767 | let config = { |
| 2768 | let __cw_config_init_4_0 = Some("zai".to_string()); |
| 2769 | let __cw_config_init_4_1 = |
| 2770 | Some(codewhale_config::descriptors::defaults::DEFAULT_TEXT_MODEL.to_string()); |
| 2771 | let mut __cw_config_init_4_value: Config = Default::default(); |
| 2772 | __cw_config_init_4_value.provider = __cw_config_init_4_0; |
| 2773 | __cw_config_init_4_value.default_text_model = __cw_config_init_4_1; |
| 2774 | __cw_config_init_4_value |
| 2775 | }; |
| 2776 | let inventory = ModelInventory::from_config(&config).unwrap(); |
| 2777 | |
| 2778 | let route = parse_inventory_auto_route_recommendation( |
| 2779 | r#"{"provider":"zai","model":"GLM-5.2","thinking":"max"}"#, |
| 2780 | &inventory, |
| 2781 | ) |
| 2782 | .expect("valid inventory route should parse"); |
| 2783 | assert_eq!(route.provider.provider, ProviderKind::Zai); |
| 2784 | assert_eq!( |
| 2785 | route.model, |
| 2786 | codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_2_MODEL |
| 2787 | ); |
| 2788 | assert_eq!(route.reasoning_effort, Some(ReasoningEffort::Max)); |
| 2789 | |
| 2790 | assert!( |
| 2791 | parse_inventory_auto_route_recommendation( |
| 2792 | r#"{"provider":"zai","model":"deepseek-v4-pro","thinking":"max"}"#, |
| 2793 | &inventory, |
| 2794 | ) |
| 2795 | .is_none(), |
| 2796 | "router must not pair a DeepSeek model with the Z.ai provider" |
| 2797 | ); |
| 2798 | |
| 2799 | let wrapped = parse_inventory_auto_route_recommendation( |
| 2800 | r#"route: {"provider":"zai","model":"GLM-5-Turbo","reasoning_effort":"medium"}"#, |
| 2801 | &inventory, |
| 2802 | ) |
| 2803 | .expect("wrapped inventory route should parse"); |
| 2804 | assert_eq!(wrapped.provider.provider, ProviderKind::Zai); |
| 2805 | assert_eq!( |
| 2806 | wrapped.model, |
| 2807 | codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_TURBO_MODEL |
| 2808 | ); |
| 2809 | // Parsing is strict and literal; the historic Medium->High coercion |
| 2810 | // is applied downstream by normalize_auto_route_selection_for_config |
| 2811 | // so route-specific contracts (Kimi Code K3) can keep Medium. |
| 2812 | assert_eq!(wrapped.reasoning_effort, Some(ReasoningEffort::Medium)); |
| 2813 | } |
| 2814 | |
| 2815 | #[test] |
| 2816 | fn inventory_auto_route_recommendation_rejects_unready_candidate() { |
| 2817 | let _env_lock = crate::test_support::lock_test_env(); |
| 2818 | let _zai = crate::test_support::EnvVarGuard::set("ZAI_API_KEY", "zai-key"); |
| 2819 | let config = { |
| 2820 | let __cw_config_init_5_0 = Some("zai".to_string()); |
| 2821 | let mut __cw_config_init_5_value: Config = Default::default(); |
| 2822 | __cw_config_init_5_value.provider = __cw_config_init_5_0; |
| 2823 | __cw_config_init_5_value |
| 2824 | }; |
| 2825 | let mut inventory = ModelInventory::from_config(&config).unwrap(); |
| 2826 | let candidate = inventory |
| 2827 | .candidates |
| 2828 | .iter_mut() |
| 2829 | .find(|candidate| { |
| 2830 | candidate.provider == ProviderKind::Zai |
| 2831 | && candidate.model |
| 2832 | == codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_2_MODEL |
| 2833 | }) |
| 2834 | .expect("Z.ai strong candidate"); |
| 2835 | candidate.readiness = crate::provider_readiness::ResolvedProviderReadiness::InvalidRoute; |
| 2836 | |
| 2837 | assert!( |
| 2838 | parse_inventory_auto_route_recommendation( |
| 2839 | r#"{"provider":"zai","model":"GLM-5.2","thinking":"max"}"#, |
| 2840 | &inventory, |
| 2841 | ) |
| 2842 | .is_none(), |
| 2843 | "classifier output must not revive an unsupported route" |
| 2844 | ); |
| 2845 | } |
| 2846 | |
| 2847 | #[test] |
| 2848 | fn inventory_auto_route_recommendation_accepts_wanjie_v4_ids() { |
| 2849 | let _env_lock = crate::test_support::lock_test_env(); |
| 2850 | let _deepseek = crate::test_support::EnvVarGuard::set("DEEPSEEK_API_KEY", "ds-key"); |
| 2851 | let _wanjie = crate::test_support::EnvVarGuard::set("WANJIE_ARK_API_KEY", "wanjie-key"); |
| 2852 | let config = { |
| 2853 | let __cw_config_init_6_0 = Some("wanjie-ark".to_string()); |
| 2854 | let mut __cw_config_init_6_value: Config = Default::default(); |
| 2855 | __cw_config_init_6_value.provider = __cw_config_init_6_0; |
| 2856 | __cw_config_init_6_value |
| 2857 | }; |
| 2858 | let inventory = ModelInventory::from_config(&config).unwrap(); |
| 2859 | |
| 2860 | let route = parse_inventory_auto_route_recommendation( |
| 2861 | r#"{"provider":"wanjie-ark","model":"deepseek-v4-pro","thinking":"max"}"#, |
| 2862 | &inventory, |
| 2863 | ) |
| 2864 | .expect("Wanjie V4 Pro inventory route should parse"); |
| 2865 | assert_eq!(route.provider.provider, ProviderKind::WanjieArk); |
| 2866 | assert_eq!(route.model, "deepseek-v4-pro"); |
| 2867 | assert_eq!(route.reasoning_effort, Some(ReasoningEffort::Max)); |
| 2868 | |
| 2869 | let route = parse_inventory_auto_route_recommendation( |
| 2870 | r#"{"provider":"wanjie-ark","model":"deepseek-v4-flash","thinking":"off"}"#, |
| 2871 | &inventory, |
| 2872 | ) |
| 2873 | .expect("Wanjie V4 Flash inventory route should parse"); |
| 2874 | assert_eq!(route.provider.provider, ProviderKind::WanjieArk); |
| 2875 | assert_eq!(route.model, "deepseek-v4-flash"); |
| 2876 | assert_eq!(route.reasoning_effort, Some(ReasoningEffort::Off)); |
| 2877 | } |
| 2878 | |
| 2879 | #[test] |
| 2880 | fn explicit_route_to_nonactive_provider_uses_that_providers_effort() { |
| 2881 | // Active provider is DeepSeek (whose effort floor is low/medium), but the |
| 2882 | // explicit model `GLM-5.2` only routes to Z.ai. The resolved effort must |
| 2883 | // be normalized for Z.ai — not left at DeepSeek's raw `low` setting. |
| 2884 | let _env_lock = crate::test_support::lock_test_env(); |
| 2885 | let _deepseek = crate::test_support::EnvVarGuard::set("DEEPSEEK_API_KEY", "ds-key"); |
| 2886 | let _zai = crate::test_support::EnvVarGuard::set("ZAI_API_KEY", "zai-key"); |
| 2887 | let config = { |
| 2888 | let __cw_config_init_7_0 = Some("deepseek".to_string()); |
| 2889 | let __cw_config_init_7_1 = Some("low".to_string()); |
| 2890 | let mut __cw_config_init_7_value: Config = Default::default(); |
| 2891 | __cw_config_init_7_value.provider = __cw_config_init_7_0; |
| 2892 | __cw_config_init_7_value.reasoning_effort = __cw_config_init_7_1; |
| 2893 | __cw_config_init_7_value |
| 2894 | }; |
| 2895 | |
| 2896 | let route = resolve_explicit_route_with_inventory(&config, "GLM-5.2") |
| 2897 | .expect("explicit GLM route should resolve to its provider"); |
| 2898 | |
| 2899 | assert_eq!( |
| 2900 | route.provider.provider, |
| 2901 | ProviderKind::Zai, |
| 2902 | "GLM-5.2 must route to Z.ai, not the active DeepSeek provider" |
| 2903 | ); |
| 2904 | assert_eq!( |
| 2905 | route.reasoning_effort, |
| 2906 | Some(ReasoningEffort::High), |
| 2907 | "low must be normalized up to high for the Z.ai route, not passed through" |
| 2908 | ); |
| 2909 | |
| 2910 | // GLM-5.3 is the default and a first-class route: same provider |
| 2911 | // ownership, same effort normalization, and it resolves to its own id. |
| 2912 | let route_53 = resolve_explicit_route_with_inventory(&config, "GLM-5.3") |
| 2913 | .expect("explicit GLM-5.3 route should resolve to its provider"); |
| 2914 | assert_eq!( |
| 2915 | route_53.provider.provider, |
| 2916 | ProviderKind::Zai, |
| 2917 | "GLM-5.3 must route to Z.ai, not the active DeepSeek provider" |
| 2918 | ); |
| 2919 | assert_eq!( |
| 2920 | route_53.model, |
| 2921 | codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_3_MODEL, |
| 2922 | "GLM-5.3 must resolve to its own id" |
| 2923 | ); |
| 2924 | // GLM-5.3 publishes its own ladder (low/high/max) instead of 5.2's, so |
| 2925 | // low reaches the wire (#6396). |
| 2926 | assert_eq!(route_53.reasoning_effort, Some(ReasoningEffort::Low)); |
| 2927 | } |
| 2928 | |
| 2929 | #[tokio::test] |
| 2930 | #[allow(clippy::await_holding_lock)] |
| 2931 | async fn inventory_auto_route_resolves_active_authenticated_provider() { |
| 2932 | let _env_lock = crate::test_support::lock_test_env(); |
| 2933 | let _deepseek = crate::test_support::EnvVarGuard::set("DEEPSEEK_API_KEY", "ds-key"); |
| 2934 | let _zai = crate::test_support::EnvVarGuard::set("ZAI_API_KEY", "zai-key"); |
| 2935 | let config = { |
| 2936 | let __cw_config_init_8_0 = Some("zai".to_string()); |
| 2937 | let mut __cw_config_init_8_value: Config = Default::default(); |
| 2938 | __cw_config_init_8_value.provider = __cw_config_init_8_0; |
| 2939 | __cw_config_init_8_value |
| 2940 | }; |
| 2941 | |
| 2942 | // #6290 rework: without the flash classifier there is no |
| 2943 | // per-request signal, so every wording resolves the same declared |
| 2944 | // default — the short chat and the complex ask below must agree. |
| 2945 | for prompt in [ |
| 2946 | "quick status check", |
| 2947 | "please refactor this architecture and audit its security boundaries", |
| 2948 | ] { |
| 2949 | let route = resolve_auto_route_with_inventory(&config, prompt, "", "auto", "auto") |
| 2950 | .await |
| 2951 | .expect("inventory route should resolve with authenticated active provider"); |
| 2952 | |
| 2953 | assert_eq!(route.provider.provider, ProviderKind::Zai); |
| 2954 | assert_eq!( |
| 2955 | route.model, |
| 2956 | codewhale_config::descriptors::defaults::DEFAULT_ZAI_MODEL |
| 2957 | ); |
| 2958 | assert_eq!(route.source, AutoRouteSource::Heuristic); |
| 2959 | let receipt = route.receipt.expect("Auto route receipt"); |
| 2960 | assert_eq!(receipt.tier, AutoRouteTier::Strong); |
| 2961 | assert_eq!(receipt.scope, AutoRouteScope::ResolvedProvider); |
| 2962 | assert_eq!(receipt.data_path, AutoRouteDataPath::LocalHeuristic); |
| 2963 | assert_eq!( |
| 2964 | receipt.reason, |
| 2965 | AutoRouteReason::LocalFallback(AutoRouteHeuristicReason::DeclaredDefault), |
| 2966 | "prompt {prompt:?} must take the declared default, not a content judgment" |
| 2967 | ); |
| 2968 | assert_eq!( |
| 2969 | receipt.pair.strong, |
| 2970 | codewhale_config::descriptors::defaults::DEFAULT_ZAI_MODEL |
| 2971 | ); |
| 2972 | assert_eq!( |
| 2973 | receipt.pair.fast.as_deref(), |
| 2974 | Some(codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_3_FLASH_MODEL) |
| 2975 | ); |
| 2976 | } |
| 2977 | } |
| 2978 | |
| 2979 | #[test] |
| 2980 | fn classifier_receipt_discloses_active_provider_scope_and_data_path() { |
| 2981 | let _env_lock = crate::test_support::lock_test_env(); |
| 2982 | let _deepseek = crate::test_support::EnvVarGuard::set("DEEPSEEK_API_KEY", "ds-key"); |
| 2983 | let _zai = crate::test_support::EnvVarGuard::set("ZAI_API_KEY", "zai-key"); |
| 2984 | let config = { |
| 2985 | let __cw_config_init_9_0 = Some("zai".to_string()); |
| 2986 | let mut __cw_config_init_9_value: Config = Default::default(); |
| 2987 | __cw_config_init_9_value.provider = __cw_config_init_9_0; |
| 2988 | __cw_config_init_9_value |
| 2989 | }; |
| 2990 | let inventory = ModelInventory::from_config(&config).unwrap(); |
| 2991 | let recommendation = parse_inventory_auto_route_recommendation( |
| 2992 | r#"{"provider":"zai","model":"GLM-5-Turbo","thinking":"off"}"#, |
| 2993 | &inventory, |
| 2994 | ) |
| 2995 | .expect("runnable classifier recommendation"); |
| 2996 | |
| 2997 | let route = auto_route_from_classifier(&inventory, recommendation); |
| 2998 | |
| 2999 | assert_eq!(route.provider.provider, ProviderKind::Zai); |
| 3000 | assert_eq!( |
| 3001 | route.model, |
| 3002 | codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_TURBO_MODEL |
| 3003 | ); |
| 3004 | assert_eq!(route.source, AutoRouteSource::FlashRouter); |
| 3005 | let receipt = route.receipt.expect("classifier receipt"); |
| 3006 | assert_eq!(receipt.tier, AutoRouteTier::Fast); |
| 3007 | // #4411: the classifier only saw Z.ai routes, so the receipt says so |
| 3008 | // instead of claiming the wider runnable-providers scope. |
| 3009 | assert_eq!(receipt.scope, AutoRouteScope::ActiveProvider); |
| 3010 | assert_eq!( |
| 3011 | receipt.data_path, |
| 3012 | AutoRouteDataPath::Classifier { |
| 3013 | provider: "deepseek".into(), |
| 3014 | provider_kind: ProviderKind::Deepseek, |
| 3015 | model: "deepseek-flash".to_string(), |
| 3016 | } |
| 3017 | ); |
| 3018 | assert_eq!(receipt.reason, AutoRouteReason::ClassifierRecommendation); |
| 3019 | } |
| 3020 | |
| 3021 | #[test] |
| 3022 | fn classifier_recommendation_for_another_provider_is_refused_by_default() { |
| 3023 | // #4411: the payload never named DeepSeek, but a classifier can still |
| 3024 | // emit one. The recommendation must not become a route unless the |
| 3025 | // persisted cross-provider opt-in is set. |
| 3026 | let _env_lock = crate::test_support::lock_test_env(); |
| 3027 | let _deepseek = crate::test_support::EnvVarGuard::set("DEEPSEEK_API_KEY", "ds-key"); |
| 3028 | let _zai = crate::test_support::EnvVarGuard::set("ZAI_API_KEY", "zai-key"); |
| 3029 | let scoped = { |
| 3030 | let __cw_config_init_10_0 = Some("zai".to_string()); |
| 3031 | let mut __cw_config_init_10_value: Config = Default::default(); |
| 3032 | __cw_config_init_10_value.provider = __cw_config_init_10_0; |
| 3033 | __cw_config_init_10_value |
| 3034 | }; |
| 3035 | let scoped_inventory = ModelInventory::from_config(&scoped).unwrap(); |
| 3036 | let raw = r#"{"provider":"deepseek","model":"deepseek-v4-flash","thinking":"off"}"#; |
| 3037 | |
| 3038 | assert!( |
| 3039 | parse_inventory_auto_route_recommendation(raw, &scoped_inventory).is_none(), |
| 3040 | "cross-provider classifier output must be refused by default" |
| 3041 | ); |
| 3042 | // The same inventory still accepts an in-scope active-provider route. |
| 3043 | assert!( |
| 3044 | parse_inventory_auto_route_recommendation( |
| 3045 | r#"{"provider":"zai","model":"GLM-5.2","thinking":"max"}"#, |
| 3046 | &scoped_inventory, |
| 3047 | ) |
| 3048 | .is_some() |
| 3049 | ); |
| 3050 | |
| 3051 | let opted_in = { |
| 3052 | let __cw_config_init_11_0 = Some(codewhale_runtime::config::AutoConfig { |
| 3053 | cost_saving: None, |
| 3054 | cross_provider: Some(true), |
| 3055 | router: None, |
| 3056 | }); |
| 3057 | let mut __cw_config_init_11_value: Config = scoped.clone(); |
| 3058 | __cw_config_init_11_value.auto = __cw_config_init_11_0; |
| 3059 | __cw_config_init_11_value |
| 3060 | }; |
| 3061 | let opted_in_route = parse_inventory_auto_route_recommendation( |
| 3062 | raw, |
| 3063 | &ModelInventory::from_config(&opted_in).unwrap(), |
| 3064 | ) |
| 3065 | .expect("opt-in admits the cross-provider recommendation"); |
| 3066 | assert_eq!(opted_in_route.provider.provider, ProviderKind::Deepseek); |
| 3067 | } |
| 3068 | |
| 3069 | #[test] |
| 3070 | fn classifier_prompt_declares_active_provider_scope_by_default() { |
| 3071 | let _env_lock = crate::test_support::lock_test_env(); |
| 3072 | let _deepseek = crate::test_support::EnvVarGuard::set("DEEPSEEK_API_KEY", "ds-key"); |
| 3073 | let _zai = crate::test_support::EnvVarGuard::set("ZAI_API_KEY", "zai-key"); |
| 3074 | let config = { |
| 3075 | let __cw_config_init_12_0 = Some("zai".to_string()); |
| 3076 | let mut __cw_config_init_12_value: Config = Default::default(); |
| 3077 | __cw_config_init_12_value.provider = __cw_config_init_12_0; |
| 3078 | __cw_config_init_12_value |
| 3079 | }; |
| 3080 | |
| 3081 | let prompt = inventory_auto_router_system_prompt( |
| 3082 | &ModelInventory::from_config(&config).unwrap(), |
| 3083 | false, |
| 3084 | ); |
| 3085 | |
| 3086 | assert!( |
| 3087 | prompt.contains("Auto routing is scoped to the active provider `zai`"), |
| 3088 | "{prompt}" |
| 3089 | ); |
| 3090 | assert!(!prompt.contains("deepseek"), "{prompt}"); |
| 3091 | } |
| 3092 | |
| 3093 | #[tokio::test] |
| 3094 | #[allow(clippy::await_holding_lock)] |
| 3095 | async fn active_provider_declared_default_survives_scoping() { |
| 3096 | // #4411: scoping keeps Auto on the active provider. #6290 rework: |
| 3097 | // without the flash classifier there is no per-request tier signal, |
| 3098 | // so both wordings resolve the same declared default on Zai. |
| 3099 | let _env_lock = crate::test_support::lock_test_env(); |
| 3100 | let _deepseek = crate::test_support::EnvVarGuard::remove("DEEPSEEK_API_KEY"); |
| 3101 | let _zai = crate::test_support::EnvVarGuard::set("ZAI_API_KEY", "zai-key"); |
| 3102 | let config = { |
| 3103 | let __cw_config_init_13_0 = Some("zai".to_string()); |
| 3104 | let mut __cw_config_init_13_value: Config = Default::default(); |
| 3105 | __cw_config_init_13_value.provider = __cw_config_init_13_0; |
| 3106 | __cw_config_init_13_value |
| 3107 | }; |
| 3108 | |
| 3109 | for prompt in [ |
| 3110 | "refactor the routing module and audit its security boundaries", |
| 3111 | "hi", |
| 3112 | ] { |
| 3113 | let route = resolve_auto_route_with_inventory(&config, prompt, "", "auto", "auto") |
| 3114 | .await |
| 3115 | .expect("scoped Auto route"); |
| 3116 | assert_eq!(route.provider.provider, ProviderKind::Zai); |
| 3117 | assert_eq!( |
| 3118 | route.model, |
| 3119 | codewhale_config::descriptors::defaults::DEFAULT_ZAI_MODEL |
| 3120 | ); |
| 3121 | let receipt = route.receipt.expect("scoped receipt"); |
| 3122 | assert_eq!(receipt.tier, AutoRouteTier::Strong); |
| 3123 | assert_eq!(receipt.scope, AutoRouteScope::ResolvedProvider); |
| 3124 | assert_eq!( |
| 3125 | receipt.reason, |
| 3126 | AutoRouteReason::LocalFallback(AutoRouteHeuristicReason::DeclaredDefault), |
| 3127 | "prompt {prompt:?}" |
| 3128 | ); |
| 3129 | } |
| 3130 | } |
| 3131 | |
| 3132 | #[test] |
| 3133 | fn config_auto_cross_provider_defaults_to_false() { |
| 3134 | assert!(!Config::default().auto_cross_provider()); |
| 3135 | let opted_in = { |
| 3136 | let __cw_config_init_14_0 = Some(codewhale_runtime::config::AutoConfig { |
| 3137 | cost_saving: None, |
| 3138 | cross_provider: Some(true), |
| 3139 | router: None, |
| 3140 | }); |
| 3141 | let mut __cw_config_init_14_value: Config = Default::default(); |
| 3142 | __cw_config_init_14_value.auto = __cw_config_init_14_0; |
| 3143 | __cw_config_init_14_value |
| 3144 | }; |
| 3145 | assert!(opted_in.auto_cross_provider()); |
| 3146 | } |
| 3147 | |
| 3148 | #[test] |
| 3149 | fn classifier_receipt_never_reports_openrouter_default_for_another_family() { |
| 3150 | let _env_lock = crate::test_support::lock_test_env(); |
| 3151 | let _openrouter = |
| 3152 | crate::test_support::EnvVarGuard::set("OPENROUTER_API_KEY", "openrouter-key"); |
| 3153 | let config = { |
| 3154 | let __cw_config_init_15_0 = Some("openrouter".to_string()); |
| 3155 | let mut __cw_config_init_15_value: Config = Default::default(); |
| 3156 | __cw_config_init_15_value.provider = __cw_config_init_15_0; |
| 3157 | __cw_config_init_15_value |
| 3158 | }; |
| 3159 | let inventory = ModelInventory::from_config(&config).unwrap(); |
| 3160 | let recommendation = parse_inventory_auto_route_recommendation( |
| 3161 | r#"{"provider":"openrouter","model":"z-ai/glm-5.2","thinking":"max"}"#, |
| 3162 | &inventory, |
| 3163 | ) |
| 3164 | .expect("runnable non-default OpenRouter family"); |
| 3165 | |
| 3166 | let route = auto_route_from_classifier(&inventory, recommendation); |
| 3167 | let receipt = route.receipt.expect("classifier receipt"); |
| 3168 | |
| 3169 | assert_eq!( |
| 3170 | route.model, |
| 3171 | codewhale_config::catalog::reviewed::constants::OPENROUTER_GLM_5_2_MODEL |
| 3172 | ); |
| 3173 | assert_eq!( |
| 3174 | receipt.pair.strong, |
| 3175 | codewhale_config::catalog::reviewed::constants::OPENROUTER_GLM_5_2_MODEL |
| 3176 | ); |
| 3177 | assert_ne!( |
| 3178 | receipt.pair.fast.as_deref(), |
| 3179 | Some(codewhale_config::descriptors::defaults::DEFAULT_OPENROUTER_FLASH_MODEL), |
| 3180 | "a GLM selection must not be described as the DeepSeek default pair" |
| 3181 | ); |
| 3182 | assert!(matches!( |
| 3183 | receipt.tier, |
| 3184 | AutoRouteTier::Strong | AutoRouteTier::Only |
| 3185 | )); |
| 3186 | } |
| 3187 | |
| 3188 | #[test] |
| 3189 | fn classifier_fallback_preserves_attempted_data_path_without_error_text() { |
| 3190 | let _env_lock = crate::test_support::lock_test_env(); |
| 3191 | let _deepseek = crate::test_support::EnvVarGuard::set("DEEPSEEK_API_KEY", "ds-key"); |
| 3192 | let _zai = crate::test_support::EnvVarGuard::set("ZAI_API_KEY", "zai-key"); |
| 3193 | let config = { |
| 3194 | let __cw_config_init_16_0 = Some("zai".to_string()); |
| 3195 | let mut __cw_config_init_16_value: Config = Default::default(); |
| 3196 | __cw_config_init_16_value.provider = __cw_config_init_16_0; |
| 3197 | __cw_config_init_16_value |
| 3198 | }; |
| 3199 | let inventory = ModelInventory::from_config(&config).unwrap(); |
| 3200 | let fallback = auto_route_declared_fallback(&config, &inventory); |
| 3201 | |
| 3202 | let route = auto_route_classifier_fallback(fallback, &inventory); |
| 3203 | |
| 3204 | assert_eq!(route.source, AutoRouteSource::Heuristic); |
| 3205 | let receipt = route.receipt.expect("fallback receipt"); |
| 3206 | assert_eq!(receipt.scope, AutoRouteScope::ResolvedProvider); |
| 3207 | assert!(matches!( |
| 3208 | receipt.data_path, |
| 3209 | AutoRouteDataPath::Classifier { |
| 3210 | ref provider, |
| 3211 | ref model, |
| 3212 | .. |
| 3213 | } if provider.as_str() == "deepseek" && model == "deepseek-flash" |
| 3214 | )); |
| 3215 | assert_eq!( |
| 3216 | receipt.reason, |
| 3217 | AutoRouteReason::ClassifierFallback(AutoRouteHeuristicReason::DeclaredDefault) |
| 3218 | ); |
| 3219 | assert!(!receipt.reason.label().contains("secret-provider-error")); |
| 3220 | } |
| 3221 | |
| 3222 | #[test] |
| 3223 | fn pre_rework_receipt_shape_still_deserializes() { |
| 3224 | // Sessions saved before the #6290 rework persist |
| 3225 | // `local_heuristic` + content-derived reasons. They must keep |
| 3226 | // loading: the wrapper arrives via serde alias, the legacy reasons |
| 3227 | // are retained variants. |
| 3228 | let reason: AutoRouteReason = |
| 3229 | serde_json::from_str(r#"{"local_heuristic":"complex_request"}"#) |
| 3230 | .expect("pre-rework receipt reason deserializes"); |
| 3231 | assert_eq!( |
| 3232 | reason, |
| 3233 | AutoRouteReason::LocalFallback(AutoRouteHeuristicReason::ComplexRequest) |
| 3234 | ); |
| 3235 | let receipt: AutoRouteReceipt = serde_json::from_str( |
| 3236 | r#"{"tier":"fast","pair":{"strong":"GLM-5.3","fast":"GLM-5.3-Flash"},"scope":"resolved_provider","data_path":"local_heuristic","reason":{"local_heuristic":"short_request"}}"#, |
| 3237 | ) |
| 3238 | .expect("pre-rework receipt deserializes"); |
| 3239 | assert_eq!(receipt.reason.label(), "local fallback: short request"); |
| 3240 | } |
| 3241 | |
| 3242 | #[tokio::test] |
| 3243 | #[allow(clippy::await_holding_lock)] |
| 3244 | async fn inventory_auto_route_never_falls_back_across_providers_by_default() { |
| 3245 | // #4411: the active provider has no usable credential, but another |
| 3246 | // provider does. Auto must stay on the active provider and report a |
| 3247 | // no-runnable-candidate fallback instead of silently spending the |
| 3248 | // other provider's key. |
| 3249 | let _env_lock = crate::test_support::lock_test_env(); |
| 3250 | let _deepseek = crate::test_support::EnvVarGuard::set("DEEPSEEK_API_KEY", "ds-key"); |
| 3251 | let _zai = crate::test_support::EnvVarGuard::remove("ZAI_API_KEY"); |
| 3252 | let config = { |
| 3253 | let __cw_config_init_17_0 = Some("zai".to_string()); |
| 3254 | let mut __cw_config_init_17_value: Config = Default::default(); |
| 3255 | __cw_config_init_17_value.provider = __cw_config_init_17_0; |
| 3256 | __cw_config_init_17_value |
| 3257 | }; |
| 3258 | |
| 3259 | let route = |
| 3260 | resolve_auto_route_with_inventory(&config, "quick status check", "", "auto", "auto") |
| 3261 | .await |
| 3262 | .expect("inventory route should resolve without leaving the active provider"); |
| 3263 | |
| 3264 | assert_eq!(route.provider.provider, ProviderKind::Zai); |
| 3265 | assert_ne!(route.provider.provider, ProviderKind::Deepseek); |
| 3266 | assert_eq!(route.source, AutoRouteSource::Heuristic); |
| 3267 | let receipt = route.receipt.expect("Auto route receipt"); |
| 3268 | assert_eq!(receipt.scope, AutoRouteScope::ResolvedProvider); |
| 3269 | assert_eq!( |
| 3270 | receipt.reason, |
| 3271 | AutoRouteReason::LocalFallback(AutoRouteHeuristicReason::NoRunnableCandidate) |
| 3272 | ); |
| 3273 | } |
| 3274 | |
| 3275 | #[tokio::test] |
| 3276 | #[allow(clippy::await_holding_lock)] |
| 3277 | async fn inventory_auto_route_crosses_providers_only_under_persisted_opt_in() { |
| 3278 | // The same configuration as above, plus the persisted |
| 3279 | // `[auto] cross_provider = true` opt-in (#4411). |
| 3280 | let _env_lock = crate::test_support::lock_test_env(); |
| 3281 | let _deepseek = crate::test_support::EnvVarGuard::set("DEEPSEEK_API_KEY", "ds-key"); |
| 3282 | let _zai = crate::test_support::EnvVarGuard::remove("ZAI_API_KEY"); |
| 3283 | let config = { |
| 3284 | let __cw_config_init_18_0 = Some("zai".to_string()); |
| 3285 | let __cw_config_init_18_1 = Some(codewhale_runtime::config::AutoConfig { |
| 3286 | cost_saving: None, |
| 3287 | cross_provider: Some(true), |
| 3288 | router: None, |
| 3289 | }); |
| 3290 | let mut __cw_config_init_18_value: Config = Default::default(); |
| 3291 | __cw_config_init_18_value.provider = __cw_config_init_18_0; |
| 3292 | __cw_config_init_18_value.auto = __cw_config_init_18_1; |
| 3293 | __cw_config_init_18_value |
| 3294 | }; |
| 3295 | |
| 3296 | let route = |
| 3297 | resolve_auto_route_with_inventory(&config, "quick status check", "", "auto", "auto") |
| 3298 | .await |
| 3299 | .expect("opted-in route should fall back to an authenticated provider"); |
| 3300 | |
| 3301 | assert_eq!(route.provider.provider, ProviderKind::Deepseek); |
| 3302 | assert_eq!(route.model, "deepseek-flash"); |
| 3303 | assert_eq!(route.source, AutoRouteSource::Heuristic); |
| 3304 | } |
| 3305 | |
| 3306 | #[tokio::test] |
| 3307 | #[allow(clippy::await_holding_lock)] |
| 3308 | async fn inventory_auto_route_cost_saving_pins_fast_sibling() { |
| 3309 | let _env_lock = crate::test_support::lock_test_env(); |
| 3310 | let _deepseek = crate::test_support::EnvVarGuard::remove("DEEPSEEK_API_KEY"); |
| 3311 | let _zai = crate::test_support::EnvVarGuard::set("ZAI_API_KEY", "zai-key"); |
| 3312 | let balanced = { |
| 3313 | let __cw_config_init_19_0 = Some("zai".to_string()); |
| 3314 | let mut __cw_config_init_19_value: Config = Default::default(); |
| 3315 | __cw_config_init_19_value.provider = __cw_config_init_19_0; |
| 3316 | __cw_config_init_19_value |
| 3317 | }; |
| 3318 | let cost_saving = { |
| 3319 | let __cw_config_init_20_0 = Some(codewhale_runtime::config::AutoConfig { |
| 3320 | cost_saving: Some(true), |
| 3321 | cross_provider: None, |
| 3322 | router: None, |
| 3323 | }); |
| 3324 | let mut __cw_config_init_20_value: Config = balanced.clone(); |
| 3325 | __cw_config_init_20_value.auto = __cw_config_init_20_0; |
| 3326 | __cw_config_init_20_value |
| 3327 | }; |
| 3328 | |
| 3329 | let balanced_route = resolve_auto_route_with_inventory( |
| 3330 | &balanced, |
| 3331 | "Please implement a binary search", |
| 3332 | "", |
| 3333 | "auto", |
| 3334 | "auto", |
| 3335 | ) |
| 3336 | .await |
| 3337 | .expect("balanced Auto route should resolve"); |
| 3338 | let cost_saving_route = resolve_auto_route_with_inventory( |
| 3339 | &cost_saving, |
| 3340 | "Please implement a binary search", |
| 3341 | "", |
| 3342 | "auto", |
| 3343 | "auto", |
| 3344 | ) |
| 3345 | .await |
| 3346 | .expect("cost-saving Auto route should resolve"); |
| 3347 | |
| 3348 | assert_eq!(balanced_route.provider.provider, ProviderKind::Zai); |
| 3349 | assert_eq!( |
| 3350 | balanced_route.model, |
| 3351 | codewhale_config::descriptors::defaults::DEFAULT_ZAI_MODEL |
| 3352 | ); |
| 3353 | assert_eq!(cost_saving_route.provider.provider, ProviderKind::Zai); |
| 3354 | assert_eq!( |
| 3355 | cost_saving_route.model, |
| 3356 | codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_3_FLASH_MODEL |
| 3357 | ); |
| 3358 | assert_eq!(cost_saving_route.source, AutoRouteSource::Heuristic); |
| 3359 | assert_eq!( |
| 3360 | balanced_route |
| 3361 | .receipt |
| 3362 | .as_ref() |
| 3363 | .map(|receipt| (receipt.tier, receipt.reason)), |
| 3364 | Some(( |
| 3365 | AutoRouteTier::Strong, |
| 3366 | AutoRouteReason::LocalFallback(AutoRouteHeuristicReason::DeclaredDefault), |
| 3367 | )) |
| 3368 | ); |
| 3369 | assert_eq!( |
| 3370 | cost_saving_route |
| 3371 | .receipt |
| 3372 | .as_ref() |
| 3373 | .map(|receipt| (receipt.tier, receipt.reason)), |
| 3374 | Some(( |
| 3375 | AutoRouteTier::Fast, |
| 3376 | AutoRouteReason::LocalFallback(AutoRouteHeuristicReason::CostSavingPolicy), |
| 3377 | )) |
| 3378 | ); |
| 3379 | |
| 3380 | let cost_saving_glm54 = { |
| 3381 | let __cw_config_init_23_0 = Some(codewhale_runtime::config::AutoConfig { |
| 3382 | cost_saving: Some(true), |
| 3383 | cross_provider: None, |
| 3384 | router: None, |
| 3385 | }); |
| 3386 | let mut __cw_config_init_23_value: Config = Default::default(); |
| 3387 | __cw_config_init_23_value.provider = Some("zai".to_string()); |
| 3388 | __cw_config_init_23_value.default_text_model = |
| 3389 | Some(codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_4_MODEL.to_string()); |
| 3390 | __cw_config_init_23_value.auto = __cw_config_init_23_0; |
| 3391 | __cw_config_init_23_value |
| 3392 | }; |
| 3393 | let glm54_route = resolve_auto_route_with_inventory( |
| 3394 | &cost_saving_glm54, |
| 3395 | "Please implement a binary search", |
| 3396 | "", |
| 3397 | "auto", |
| 3398 | "auto", |
| 3399 | ) |
| 3400 | .await |
| 3401 | .expect("cost-saving GLM-5.4 route should resolve"); |
| 3402 | assert_eq!(glm54_route.provider.provider, ProviderKind::Zai); |
| 3403 | assert_eq!( |
| 3404 | glm54_route.model, |
| 3405 | codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_4_MODEL |
| 3406 | ); |
| 3407 | assert_eq!( |
| 3408 | glm54_route |
| 3409 | .receipt |
| 3410 | .as_ref() |
| 3411 | .map(|receipt| (receipt.tier, receipt.reason)), |
| 3412 | Some(( |
| 3413 | AutoRouteTier::Only, |
| 3414 | AutoRouteReason::LocalFallback(AutoRouteHeuristicReason::NoFastSibling), |
| 3415 | )) |
| 3416 | ); |
| 3417 | } |
| 3418 | |
| 3419 | #[tokio::test] |
| 3420 | #[allow(clippy::await_holding_lock)] |
| 3421 | async fn inventory_auto_route_uses_wanjie_v4_pair_without_deepseek_router() { |
| 3422 | let _env_lock = crate::test_support::lock_test_env(); |
| 3423 | let _deepseek = crate::test_support::EnvVarGuard::remove("DEEPSEEK_API_KEY"); |
| 3424 | let _wanjie = crate::test_support::EnvVarGuard::set("WANJIE_ARK_API_KEY", "wanjie-key"); |
| 3425 | let config = { |
| 3426 | let __cw_config_init_21_0 = Some("wanjie-ark".to_string()); |
| 3427 | let __cw_config_init_21_1 = Some("auto".to_string()); |
| 3428 | let mut __cw_config_init_21_value: Config = Default::default(); |
| 3429 | __cw_config_init_21_value.provider = __cw_config_init_21_0; |
| 3430 | __cw_config_init_21_value.default_text_model = __cw_config_init_21_1; |
| 3431 | __cw_config_init_21_value |
| 3432 | }; |
| 3433 | |
| 3434 | // #6290 rework: no classifier, no content signal — both wordings |
| 3435 | // take the declared Wanjie default. |
| 3436 | for prompt in ["quick status check", "please refactor this architecture"] { |
| 3437 | let route = resolve_auto_route_with_inventory(&config, prompt, "", "auto", "auto") |
| 3438 | .await |
| 3439 | .expect("declared-default Wanjie route should resolve"); |
| 3440 | assert_eq!(route.provider.provider, ProviderKind::WanjieArk); |
| 3441 | assert_eq!(route.model, "deepseek-reasoner"); |
| 3442 | assert_eq!(route.source, AutoRouteSource::Heuristic); |
| 3443 | } |
| 3444 | } |
| 3445 | |
| 3446 | #[tokio::test] |
| 3447 | #[allow(clippy::await_holding_lock)] |
| 3448 | async fn inventory_auto_route_uses_volcengine_v4_pair_without_deepseek_router() { |
| 3449 | let _env_lock = crate::test_support::lock_test_env(); |
| 3450 | let _deepseek = crate::test_support::EnvVarGuard::remove("DEEPSEEK_API_KEY"); |
| 3451 | let _volcengine = |
| 3452 | crate::test_support::EnvVarGuard::set("VOLCENGINE_API_KEY", "volcengine-key"); |
| 3453 | let config = { |
| 3454 | let __cw_config_init_22_0 = Some("volcengine".to_string()); |
| 3455 | let __cw_config_init_22_1 = Some("auto".to_string()); |
| 3456 | let mut __cw_config_init_22_value: Config = Default::default(); |
| 3457 | __cw_config_init_22_value.provider = __cw_config_init_22_0; |
| 3458 | __cw_config_init_22_value.default_text_model = __cw_config_init_22_1; |
| 3459 | __cw_config_init_22_value |
| 3460 | }; |
| 3461 | |
| 3462 | // #6290 rework: no classifier, no content signal — both wordings |
| 3463 | // take the declared Volcengine default. |
| 3464 | for prompt in ["quick status check", "please refactor this architecture"] { |
| 3465 | let route = resolve_auto_route_with_inventory(&config, prompt, "", "auto", "auto") |
| 3466 | .await |
| 3467 | .expect("declared-default Volcengine route should resolve"); |
| 3468 | assert_eq!(route.provider.provider, ProviderKind::Volcengine); |
| 3469 | assert_eq!(route.model, "DeepSeek-V4-Pro"); |
| 3470 | assert_eq!(route.source, AutoRouteSource::Heuristic); |
| 3471 | } |
| 3472 | } |
| 3473 | |
| 3474 | #[test] |
| 3475 | fn provider_router_candidates_cover_known_provider_classes() { |
| 3476 | use codewhale_config::ProviderKind; |
| 3477 | |
| 3478 | let deepseek = provider_router_candidates(ProviderKind::Deepseek, "deepseek-v4-pro"); |
| 3479 | assert_eq!(deepseek.big, "deepseek-v4-pro"); |
| 3480 | assert_eq!(deepseek.cheap.as_deref(), Some("deepseek-flash")); |
| 3481 | |
| 3482 | let openrouter = |
| 3483 | provider_router_candidates(ProviderKind::Openrouter, "deepseek/deepseek-v4-pro"); |
| 3484 | assert_eq!(openrouter.big, "deepseek/deepseek-v4-pro"); |
| 3485 | assert_eq!( |
| 3486 | openrouter.cheap.as_deref(), |
| 3487 | Some("deepseek/deepseek-v4-flash") |
| 3488 | ); |
| 3489 | |
| 3490 | let wanjie = provider_router_candidates(ProviderKind::WanjieArk, "deepseek-reasoner"); |
| 3491 | assert_eq!(wanjie.big, "deepseek-v4-pro"); |
| 3492 | assert_eq!(wanjie.cheap.as_deref(), Some("deepseek-v4-flash")); |
| 3493 | |
| 3494 | let volcengine = provider_router_candidates(ProviderKind::Volcengine, "DeepSeek-V4-Pro"); |
| 3495 | assert_eq!(volcengine.big, "DeepSeek-V4-Pro"); |
| 3496 | assert_eq!(volcengine.cheap.as_deref(), Some("DeepSeek-V4-Flash")); |
| 3497 | |
| 3498 | let zai = provider_router_candidates(ProviderKind::Zai, "GLM-5.2"); |
| 3499 | assert_eq!(zai.big, "GLM-5.2"); |
| 3500 | // GLM-5.2 faster/explore children route to GLM-5-Turbo (same-family fast |
| 3501 | // sibling), not back down to GLM-5.1. |
| 3502 | assert_eq!(zai.cheap.as_deref(), Some("GLM-5-Turbo")); |
| 3503 | |
| 3504 | let openrouter_glm = provider_router_candidates(ProviderKind::Openrouter, "z-ai/glm-5.2"); |
| 3505 | assert_eq!(openrouter_glm.big, "z-ai/glm-5.2"); |
| 3506 | assert_eq!(openrouter_glm.cheap.as_deref(), Some("z-ai/glm-5-turbo")); |
| 3507 | |
| 3508 | // GLM-5.3's fast sibling is Flash; GLM-5.2 still uses Turbo. |
| 3509 | let zai_53 = provider_router_candidates(ProviderKind::Zai, "GLM-5.3"); |
| 3510 | assert_eq!(zai_53.big, "GLM-5.3"); |
| 3511 | assert_eq!(zai_53.cheap.as_deref(), Some("GLM-5.3-Flash")); |
| 3512 | |
| 3513 | let openrouter_glm_53 = |
| 3514 | provider_router_candidates(ProviderKind::Openrouter, "z-ai/glm-5.3"); |
| 3515 | assert_eq!(openrouter_glm_53.big, "z-ai/glm-5.3"); |
| 3516 | assert_eq!( |
| 3517 | openrouter_glm_53.cheap.as_deref(), |
| 3518 | Some("z-ai/glm-5.3-flash") |
| 3519 | ); |
| 3520 | |
| 3521 | let zai_flash = provider_router_candidates(ProviderKind::Zai, "GLM-5.3-Flash"); |
| 3522 | assert_eq!(zai_flash.big, "GLM-5.3-Flash"); |
| 3523 | assert_eq!(zai_flash.cheap, None); |
| 3524 | |
| 3525 | // GLM-5.1 has no cheaper tier; faster children stay on the parent. |
| 3526 | let zai_51 = provider_router_candidates(ProviderKind::Zai, "GLM-5.1"); |
| 3527 | assert_eq!(zai_51.big, "GLM-5.1"); |
| 3528 | assert_eq!(zai_51.cheap, None); |
| 3529 | |
| 3530 | // GLM-5-Turbo is itself the cheap tier; no further downgrade. |
| 3531 | let zai_turbo = provider_router_candidates(ProviderKind::Zai, "GLM-5-Turbo"); |
| 3532 | assert_eq!(zai_turbo.big, "GLM-5-Turbo"); |
| 3533 | assert_eq!(zai_turbo.cheap, None); |
| 3534 | |
| 3535 | // Providers without a known cheap tier: big = session model, no cheap. |
| 3536 | let ollama = provider_router_candidates(ProviderKind::Ollama, "qwen3:32b"); |
| 3537 | assert_eq!(ollama.big, "qwen3:32b"); |
| 3538 | assert_eq!(ollama.cheap, None); |
| 3539 | |
| 3540 | let moonshot = provider_router_candidates(ProviderKind::Moonshot, "kimi-k2.6"); |
| 3541 | assert_eq!(moonshot.big, "kimi-k2.6"); |
| 3542 | assert_eq!(moonshot.cheap, None); |
| 3543 | } |
| 3544 | |
| 3545 | #[test] |
| 3546 | fn provider_router_candidates_cover_catalog_fast_siblings() { |
| 3547 | use codewhale_config::ProviderKind; |
| 3548 | |
| 3549 | let cases = [ |
| 3550 | (ProviderKind::OpenaiCodex, "gpt-5.6-sol", "gpt-5.6-luna"), |
| 3551 | ( |
| 3552 | ProviderKind::Anthropic, |
| 3553 | "claude-sonnet-4-6", |
| 3554 | "claude-haiku-4-5", |
| 3555 | ), |
| 3556 | (ProviderKind::XiaomiMimo, "mimo-v2.6-pro", "mimo-v2.6-flash"), |
| 3557 | ( |
| 3558 | ProviderKind::Arcee, |
| 3559 | "trinity-large-thinking", |
| 3560 | "trinity-mini", |
| 3561 | ), |
| 3562 | (ProviderKind::Moonshot, "kimi-k2.7-code", "kimi-k2.6"), |
| 3563 | ( |
| 3564 | ProviderKind::Minimax, |
| 3565 | "MiniMax-M2.7", |
| 3566 | "MiniMax-M2.7-highspeed", |
| 3567 | ), |
| 3568 | (ProviderKind::OpencodeGo, "kimi-k3", "kimi-k2.7-code"), |
| 3569 | ( |
| 3570 | ProviderKind::Openrouter, |
| 3571 | "qwen/qwen3.6-max-preview", |
| 3572 | "qwen/qwen3.6-flash", |
| 3573 | ), |
| 3574 | ( |
| 3575 | ProviderKind::Openrouter, |
| 3576 | "anthropic/claude-sonnet-4-6", |
| 3577 | "anthropic/claude-haiku-4-5", |
| 3578 | ), |
| 3579 | ]; |
| 3580 | |
| 3581 | for (provider, strong, fast) in cases { |
| 3582 | let candidates = provider_router_candidates(provider, strong); |
| 3583 | assert_eq!(candidates.big, strong); |
| 3584 | assert_eq!(candidates.cheap.as_deref(), Some(fast)); |
| 3585 | assert_eq!( |
| 3586 | provider_router_candidates(provider, fast).cheap, |
| 3587 | None, |
| 3588 | "already-fast model must not downgrade again: {provider:?}/{fast}" |
| 3589 | ); |
| 3590 | } |
| 3591 | |
| 3592 | for (provider, model) in [ |
| 3593 | (ProviderKind::Ollama, "qwen3:32b"), |
| 3594 | (ProviderKind::Custom, "gpt-5.6-sol"), |
| 3595 | (ProviderKind::OpenaiCodex, "gpt-5.6-luna"), |
| 3596 | ] { |
| 3597 | assert_eq!(provider_router_candidates(provider, model).cheap, None); |
| 3598 | } |
| 3599 | } |
| 3600 | |
| 3601 | #[tokio::test] |
| 3602 | #[allow(clippy::await_holding_lock)] |
| 3603 | async fn declared_fallback_without_cheap_tier_stays_on_default_model() { |
| 3604 | // #3018 AC: Ollama + auto must never fabricate a DeepSeek id. The |
| 3605 | // declared fallback returns the configured default verbatim, so no |
| 3606 | // sibling id can be invented regardless of request wording. |
| 3607 | let _env_lock = crate::test_support::lock_test_env(); |
| 3608 | let config = { |
| 3609 | let __cw_config_init_23_0 = Some("ollama".to_string()); |
| 3610 | let mut __cw_config_init_23_value: Config = Default::default(); |
| 3611 | __cw_config_init_23_value.provider = __cw_config_init_23_0; |
| 3612 | __cw_config_init_23_value |
| 3613 | }; |
| 3614 | for prompt in ["hi", "please refactor the auth module for security"] { |
| 3615 | let route = resolve_auto_route_with_inventory(&config, prompt, "", "auto", "auto") |
| 3616 | .await |
| 3617 | .expect("ollama Auto route should resolve"); |
| 3618 | assert_eq!(route.provider.provider, ProviderKind::Ollama); |
| 3619 | assert_eq!(route.model, config.default_model()); |
| 3620 | assert!( |
| 3621 | !route.model.to_ascii_lowercase().contains("deepseek"), |
| 3622 | "no DeepSeek id may be fabricated: {}", |
| 3623 | route.model |
| 3624 | ); |
| 3625 | } |
| 3626 | } |
| 3627 | |
| 3628 | #[test] |
| 3629 | fn config_auto_cost_saving_defaults_to_false() { |
| 3630 | let cfg = Config::default(); |
| 3631 | assert!(!cfg.auto_cost_saving()); |
| 3632 | } |
| 3633 | |
| 3634 | #[test] |
| 3635 | fn config_auto_cost_saving_reads_table() { |
| 3636 | let cfg = { |
| 3637 | let __cw_config_init_24_0 = Some(codewhale_runtime::config::AutoConfig { |
| 3638 | cost_saving: Some(true), |
| 3639 | cross_provider: None, |
| 3640 | router: None, |
| 3641 | }); |
| 3642 | let mut __cw_config_init_24_value: Config = Default::default(); |
| 3643 | __cw_config_init_24_value.auto = __cw_config_init_24_0; |
| 3644 | __cw_config_init_24_value |
| 3645 | }; |
| 3646 | assert!(cfg.auto_cost_saving()); |
| 3647 | } |
| 3648 | } |
| 3649 | |
| 3650 | #[cfg(test)] |
| 3651 | mod decision_router_tests { |
| 3652 | //! `[auto.router] kind = "decision"` (#6525) against wiremock. The |
| 3653 | //! resolver's `cfg!(any(test, feature = "test-support"))` short-circuit stays; these call the router path |
| 3654 | //! (`auto_route_via_router`) and its pure policy directly. |
| 3655 | |
| 3656 | use super::*; |
| 3657 | use wiremock::matchers::{header, method, path}; |
| 3658 | use wiremock::{Mock, MockServer, Request, ResponseTemplate}; |
| 3659 | |
| 3660 | const MARKER: &str = "PROVIDER-BODY-MARKER-must-not-leak"; |
| 3661 | |
| 3662 | /// Fields drop in declaration order: restore the environment before the |
| 3663 | /// lock is released, or another test observes our overrides. |
| 3664 | struct Env { |
| 3665 | _guards: Vec<crate::test_support::EnvVarGuard>, |
| 3666 | _home: tempfile::TempDir, |
| 3667 | _lock: crate::test_support::TestEnvLock, |
| 3668 | } |
| 3669 | |
| 3670 | fn hermetic_env() -> Env { |
| 3671 | let lock = crate::test_support::lock_test_env(); |
| 3672 | let home = tempfile::tempdir().expect("test home"); |
| 3673 | let guards = vec![ |
| 3674 | crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", home.path()), |
| 3675 | crate::test_support::EnvVarGuard::remove("OPENROUTER_API_KEY"), |
| 3676 | crate::test_support::EnvVarGuard::remove("TYPESAFE_API_KEY"), |
| 3677 | ]; |
| 3678 | Env { |
| 3679 | _guards: guards, |
| 3680 | _home: home, |
| 3681 | _lock: lock, |
| 3682 | } |
| 3683 | } |
| 3684 | |
| 3685 | /// Active DeepSeek (pro/flash pair runnable) with an OpenRouter decision |
| 3686 | /// router pointed at `openrouter_base`. |
| 3687 | fn decision_config(openrouter_base: &str, cost_saving: bool, timeout_secs: u64) -> Config { |
| 3688 | { |
| 3689 | let __cw_config_init_25_0 = Some("deepseek".to_string()); |
| 3690 | let __cw_config_init_25_1 = Some("deepseek-v4-pro".to_string()); |
| 3691 | let __cw_config_init_25_2 = Some(codewhale_runtime::config::ProvidersConfig { |
| 3692 | deepseek: codewhale_runtime::config::ProviderConfig { |
| 3693 | api_key: Some("ds-test-key".to_string()), |
| 3694 | ..Default::default() |
| 3695 | }, |
| 3696 | openrouter: codewhale_runtime::config::ProviderConfig { |
| 3697 | api_key: Some("or-test-key".to_string()), |
| 3698 | base_url: Some(openrouter_base.to_string()), |
| 3699 | ..Default::default() |
| 3700 | }, |
| 3701 | ..Default::default() |
| 3702 | }); |
| 3703 | let __cw_config_init_25_3 = Some(codewhale_runtime::config::AutoConfig { |
| 3704 | cost_saving: Some(cost_saving), |
| 3705 | cross_provider: None, |
| 3706 | router: Some(codewhale_runtime::config::AutoRouterConfig { |
| 3707 | kind: Some("decision".to_string()), |
| 3708 | provider: Some("openrouter".to_string()), |
| 3709 | model: Some("typesafe/jev-1.13".to_string()), |
| 3710 | timeout_secs: Some(timeout_secs), |
| 3711 | ..Default::default() |
| 3712 | }), |
| 3713 | }); |
| 3714 | let mut __cw_config_init_25_value: Config = Default::default(); |
| 3715 | __cw_config_init_25_value.provider = __cw_config_init_25_0; |
| 3716 | __cw_config_init_25_value.default_text_model = __cw_config_init_25_1; |
| 3717 | __cw_config_init_25_value.providers = __cw_config_init_25_2; |
| 3718 | __cw_config_init_25_value.auto = __cw_config_init_25_3; |
| 3719 | __cw_config_init_25_value |
| 3720 | } |
| 3721 | } |
| 3722 | |
| 3723 | const TYPESAFE_TEST_KEY: &str = "tsbarekey0123456789"; |
| 3724 | |
| 3725 | fn answer_body(strong: f64, confidence: f64) -> serde_json::Value { |
| 3726 | serde_json::json!({ |
| 3727 | "id": "gen-dec-1", |
| 3728 | "model": "typesafe/jev-1.13-20260917", |
| 3729 | "provider": "TypeSafe", |
| 3730 | "answers": { |
| 3731 | "tier": { |
| 3732 | "type": "choice", |
| 3733 | "choice": if strong >= 0.5 { "strong" } else { "fast" }, |
| 3734 | "probabilities": { "fast": 1.0 - strong, "strong": strong }, |
| 3735 | "confidence": confidence, |
| 3736 | }, |
| 3737 | "thinking": { |
| 3738 | "type": "choice", |
| 3739 | "choice": "max", |
| 3740 | "probabilities": { "off": 0.02, "high": 0.21, "max": 0.77 }, |
| 3741 | "confidence": 0.66, |
| 3742 | }, |
| 3743 | }, |
| 3744 | "usage": { "cost": 0.000019992, "input_tokens": 476, "output_tokens": 70 }, |
| 3745 | }) |
| 3746 | } |
| 3747 | |
| 3748 | async fn route(config: &Config, latest: &str, context: &str) -> AutoRouteSelection { |
| 3749 | let inventory = ModelInventory::from_config(config).unwrap(); |
| 3750 | assert!( |
| 3751 | inventory.router_available, |
| 3752 | "decision router must be available" |
| 3753 | ); |
| 3754 | auto_route_via_router( |
| 3755 | config, &inventory, latest, context, "agent", "auto", "auto", false, None, |
| 3756 | ) |
| 3757 | .await |
| 3758 | .expect("fixture classifier accounting must settle") |
| 3759 | } |
| 3760 | |
| 3761 | fn receipt(selection: &AutoRouteSelection) -> &AutoRouteReceipt { |
| 3762 | selection.receipt.as_ref().expect("auto receipt") |
| 3763 | } |
| 3764 | |
| 3765 | #[tokio::test] |
| 3766 | async fn decision_request_has_pinned_shape_and_redacted_state() { |
| 3767 | let _env = hermetic_env(); |
| 3768 | let server = MockServer::start().await; |
| 3769 | Mock::given(method("POST")) |
| 3770 | .and(path("/api/alpha/decisions")) |
| 3771 | .and(header("authorization", "Bearer or-test-key")) |
| 3772 | .respond_with(ResponseTemplate::new(200).set_body_json(answer_body(0.82, 0.64))) |
| 3773 | .expect(1) |
| 3774 | .mount(&server) |
| 3775 | .await; |
| 3776 | let mut config = decision_config(&format!("{}/api/v1", server.uri()), false, 2); |
| 3777 | // A configured credential that a tool result echoed back. |
| 3778 | let secret = "cw-router-secret-should-never-leave-process"; |
| 3779 | config |
| 3780 | .providers |
| 3781 | .as_mut() |
| 3782 | .expect("providers") |
| 3783 | .deepseek |
| 3784 | .api_key = Some(secret.to_string()); |
| 3785 | let selection = route( |
| 3786 | &config, |
| 3787 | "Refactor the parser across files", |
| 3788 | &format!("assistant: [tool result] token={secret}"), |
| 3789 | ) |
| 3790 | .await; |
| 3791 | assert_eq!(selection.model, "deepseek-v4-pro"); |
| 3792 | |
| 3793 | let requests: Vec<Request> = server.received_requests().await.expect("recorded"); |
| 3794 | assert_eq!(requests.len(), 1); |
| 3795 | let raw = String::from_utf8(requests[0].body.clone()).expect("utf8 body"); |
| 3796 | assert!( |
| 3797 | !raw.contains(secret), |
| 3798 | "secret leaked into the decision state" |
| 3799 | ); |
| 3800 | let body: serde_json::Value = serde_json::from_str(&raw).expect("json body"); |
| 3801 | assert_eq!(body["model"], "typesafe/jev-1.13"); |
| 3802 | let state_keys: Vec<&str> = body["state"] |
| 3803 | .as_object() |
| 3804 | .expect("state object") |
| 3805 | .keys() |
| 3806 | .map(String::as_str) |
| 3807 | .collect(); |
| 3808 | assert_eq!( |
| 3809 | state_keys, |
| 3810 | [ |
| 3811 | "session_mode", |
| 3812 | "selected_thinking_mode", |
| 3813 | "recent_context", |
| 3814 | "latest_request" |
| 3815 | ] |
| 3816 | ); |
| 3817 | // The criteria are a product surface: pin the exact wording. |
| 3818 | assert_eq!( |
| 3819 | body["questions"], |
| 3820 | serde_json::json!({ |
| 3821 | "tier": { |
| 3822 | "type": "choice", |
| 3823 | "instructions": "Which model tier should handle the latest request in this coding-agent session?", |
| 3824 | "criteria": { |
| 3825 | "fast": { |
| 3826 | "what": "A fast, cheaper model. Right for questions, explanations, lookups, small single-file edits, formatting, and routine follow-ups.", |
| 3827 | "not_for": "Multi-step agentic work, debugging across files, architecture or design, security review, release work." |
| 3828 | }, |
| 3829 | "strong": { |
| 3830 | "what": "The strongest model. Right for multi-step agentic coding, multi-file changes, debugging, architecture or design, security review, release work, or anything the fast tier would likely get wrong.", |
| 3831 | "not_for": "Trivial questions or one-line edits." |
| 3832 | } |
| 3833 | } |
| 3834 | }, |
| 3835 | "thinking": { |
| 3836 | "type": "choice", |
| 3837 | "instructions": "How much reasoning should the chosen model spend on the latest request?", |
| 3838 | "criteria": { |
| 3839 | "off": "A trivial answer with no tools and no reasoning needed.", |
| 3840 | "high": "Ordinary reasoning: a normal coding or explanation task.", |
| 3841 | "max": "Agentic, multi-file, debugging, architecture, security, release, or uncertain work." |
| 3842 | } |
| 3843 | } |
| 3844 | }) |
| 3845 | ); |
| 3846 | } |
| 3847 | |
| 3848 | #[tokio::test] |
| 3849 | async fn shadow_gate_questions_ride_the_one_router_request() { |
| 3850 | let _env = hermetic_env(); |
| 3851 | let server = MockServer::start().await; |
| 3852 | let mut answers = answer_body(0.82, 0.64); |
| 3853 | answers["answers"]["needs_tool"] = serde_json::json!({ "type": "noul", "noul": 0.93 }); |
| 3854 | answers["answers"]["answerable_from_context"] = |
| 3855 | serde_json::json!({ "type": "noul", "noul": 0.1 }); |
| 3856 | answers["answers"]["intent"] = serde_json::json!({ |
| 3857 | "type": "choice", |
| 3858 | "choice": "code_change", |
| 3859 | "probabilities": { |
| 3860 | "code_change": 0.9, "code_question": 0.04, "command": 0.03, |
| 3861 | "chat": 0.02, "other": 0.01 |
| 3862 | }, |
| 3863 | "confidence": 0.8, |
| 3864 | }); |
| 3865 | Mock::given(method("POST")) |
| 3866 | .and(path("/api/alpha/decisions")) |
| 3867 | .respond_with(ResponseTemplate::new(200).set_body_json(answers)) |
| 3868 | .expect(1) |
| 3869 | .mount(&server) |
| 3870 | .await; |
| 3871 | let mut config = decision_config(&format!("{}/api/v1", server.uri()), false, 2); |
| 3872 | config |
| 3873 | .auto |
| 3874 | .as_mut() |
| 3875 | .and_then(|auto| auto.router.as_mut()) |
| 3876 | .expect("router table") |
| 3877 | .shadow_gate = Some(true); |
| 3878 | assert!(config.auto_router_shadow_gate()); |
| 3879 | |
| 3880 | let decisions = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); |
| 3881 | let decision_sink = decisions.clone(); |
| 3882 | let origin = crate::cost_status::NativeUsageOrigin::captured_runtime_with_sinks( |
| 3883 | crate::cost_status::scope_token(), |
| 3884 | "shadow-gate-owner".to_string(), |
| 3885 | std::sync::Arc::new(|_record: crate::cost_status::RuntimeUsageRecord| true), |
| 3886 | None, |
| 3887 | Some(std::sync::Arc::new( |
| 3888 | move |receipt: crate::cost_status::RuntimeDecisionReceipt| { |
| 3889 | decision_sink.lock().expect("decision sink").push(receipt); |
| 3890 | true |
| 3891 | }, |
| 3892 | )), |
| 3893 | ); |
| 3894 | let source = crate::cost_status::NativeUsageSource::capture_with_origin( |
| 3895 | "auto-router:shadow-gate-test", |
| 3896 | crate::cost_status::UsageSpendOwner::Auxiliary, |
| 3897 | Some(origin), |
| 3898 | ); |
| 3899 | let inventory = ModelInventory::from_config(&config).unwrap(); |
| 3900 | let selection = auto_route_via_router( |
| 3901 | &config, |
| 3902 | &inventory, |
| 3903 | "Refactor the parser across files", |
| 3904 | "", |
| 3905 | "agent", |
| 3906 | "auto", |
| 3907 | "auto", |
| 3908 | false, |
| 3909 | Some(source), |
| 3910 | ) |
| 3911 | .await |
| 3912 | .expect("router answers"); |
| 3913 | assert_eq!( |
| 3914 | selection.model, "deepseek-v4-pro", |
| 3915 | "the gate never changes the route" |
| 3916 | ); |
| 3917 | |
| 3918 | let requests: Vec<Request> = server.received_requests().await.expect("recorded"); |
| 3919 | assert_eq!(requests.len(), 1, "one call carries both question sets"); |
| 3920 | let body: serde_json::Value = serde_json::from_slice(&requests[0].body).expect("json body"); |
| 3921 | let questions: Vec<&str> = body["questions"] |
| 3922 | .as_object() |
| 3923 | .expect("questions") |
| 3924 | .keys() |
| 3925 | .map(String::as_str) |
| 3926 | .collect(); |
| 3927 | assert_eq!( |
| 3928 | questions, |
| 3929 | [ |
| 3930 | "tier", |
| 3931 | "thinking", |
| 3932 | "needs_tool", |
| 3933 | "answerable_from_context", |
| 3934 | "intent" |
| 3935 | ] |
| 3936 | ); |
| 3937 | let receipts = decisions.lock().expect("decision receipts"); |
| 3938 | assert_eq!(receipts.len(), 1); |
| 3939 | assert!(receipts[0].shadow && receipts[0].valid_answers); |
| 3940 | assert_eq!(receipts[0].evidence.choice, "code_change"); |
| 3941 | } |
| 3942 | |
| 3943 | #[test] |
| 3944 | fn shadow_gate_is_a_decision_router_option_only() { |
| 3945 | let _env = hermetic_env(); |
| 3946 | let mut config = decision_config("https://openrouter.invalid/api/v1", false, 2); |
| 3947 | assert!(!config.auto_router_shadow_gate(), "off unless written down"); |
| 3948 | let router = config |
| 3949 | .auto |
| 3950 | .as_mut() |
| 3951 | .and_then(|auto| auto.router.as_mut()) |
| 3952 | .expect("router table"); |
| 3953 | router.shadow_gate = Some(true); |
| 3954 | router.kind = Some("chat".to_string()); |
| 3955 | router.provider = Some("deepseek".to_string()); |
| 3956 | router.model = Some("deepseek-v4-flash".to_string()); |
| 3957 | assert!(!config.auto_router_shadow_gate()); |
| 3958 | let inventory = ModelInventory::from_config(&config).unwrap(); |
| 3959 | assert!(!inventory.router_available); |
| 3960 | assert_eq!( |
| 3961 | inventory.router_setup_issue, |
| 3962 | Some(crate::model_inventory::AutoRouterSetupIssue::ShadowGateNeedsDecision) |
| 3963 | ); |
| 3964 | } |
| 3965 | |
| 3966 | #[tokio::test] |
| 3967 | async fn confident_strong_decision_routes_strong_with_evidence_and_usage() { |
| 3968 | let _env = hermetic_env(); |
| 3969 | let server = MockServer::start().await; |
| 3970 | Mock::given(method("POST")) |
| 3971 | .and(path("/api/alpha/decisions")) |
| 3972 | .respond_with(ResponseTemplate::new(200).set_body_json(answer_body(0.82, 0.64))) |
| 3973 | .mount(&server) |
| 3974 | .await; |
| 3975 | let config = decision_config(&format!("{}/api/v1", server.uri()), false, 2); |
| 3976 | let selection = route(&config, "Debug the release pipeline", "").await; |
| 3977 | |
| 3978 | assert_eq!(selection.provider.provider, ProviderKind::Deepseek); |
| 3979 | assert_eq!(selection.model, "deepseek-v4-pro"); |
| 3980 | assert_eq!(selection.source, AutoRouteSource::FlashRouter); |
| 3981 | assert_eq!(selection.reasoning_effort, Some(ReasoningEffort::Max)); |
| 3982 | let receipt = receipt(&selection); |
| 3983 | assert_eq!(receipt.reason, AutoRouteReason::ClassifierRecommendation); |
| 3984 | assert_eq!(receipt.tier, AutoRouteTier::Strong); |
| 3985 | assert_eq!(receipt.scope, AutoRouteScope::ActiveProvider); |
| 3986 | assert_eq!( |
| 3987 | receipt.data_path, |
| 3988 | AutoRouteDataPath::Decision { |
| 3989 | route: DecisionRouterRoute::Openrouter, |
| 3990 | model: "typesafe/jev-1.13".to_string(), |
| 3991 | } |
| 3992 | ); |
| 3993 | assert_eq!(receipt.router_failure, None); |
| 3994 | let decision = receipt.decision.as_ref().expect("decision evidence"); |
| 3995 | assert_eq!(decision.choice, "strong"); |
| 3996 | assert_eq!( |
| 3997 | decision.probabilities_bp, |
| 3998 | BTreeMap::from([("fast".to_string(), 1800), ("strong".to_string(), 8200)]) |
| 3999 | ); |
| 4000 | assert_eq!(decision.confidence_bp, 6400); |
| 4001 | assert_eq!(decision.min_confidence_bp, 5000); |
| 4002 | assert_eq!(decision.thinking.as_deref(), Some("max")); |
| 4003 | assert_eq!( |
| 4004 | decision.provider_reported_cost_usd.as_deref(), |
| 4005 | Some("0.000019992") |
| 4006 | ); |
| 4007 | assert_eq!( |
| 4008 | decision.response_model.as_deref(), |
| 4009 | Some("typesafe/jev-1.13-20260917") |
| 4010 | ); |
| 4011 | assert_eq!(selection.routed_usage.len(), 1); |
| 4012 | assert_eq!(selection.routed_usage[0].usage.usage.input_tokens, 476); |
| 4013 | assert_eq!(selection.routed_usage[0].usage.usage.output_tokens, 70); |
| 4014 | assert!( |
| 4015 | selection.routed_usage[0] |
| 4016 | .source_id |
| 4017 | .starts_with("auto-router:") |
| 4018 | ); |
| 4019 | } |
| 4020 | |
| 4021 | #[tokio::test] |
| 4022 | async fn low_confidence_takes_the_declared_fallback_and_keeps_usage() { |
| 4023 | let _env = hermetic_env(); |
| 4024 | let server = MockServer::start().await; |
| 4025 | Mock::given(method("POST")) |
| 4026 | .and(path("/api/alpha/decisions")) |
| 4027 | .respond_with(ResponseTemplate::new(200).set_body_json(answer_body(0.35, 0.3))) |
| 4028 | .mount(&server) |
| 4029 | .await; |
| 4030 | let config = decision_config(&format!("{}/api/v1", server.uri()), false, 2); |
| 4031 | let selection = route(&config, "What does this function do?", "").await; |
| 4032 | |
| 4033 | assert_eq!(selection.model, "deepseek-v4-pro", "declared default"); |
| 4034 | assert_eq!(selection.source, AutoRouteSource::Heuristic); |
| 4035 | let receipt = receipt(&selection); |
| 4036 | assert_eq!( |
| 4037 | receipt.reason, |
| 4038 | AutoRouteReason::ClassifierFallback(AutoRouteHeuristicReason::LowConfidence) |
| 4039 | ); |
| 4040 | assert_eq!(receipt.router_failure, None); |
| 4041 | let decision = receipt.decision.as_ref().expect("evidence is kept"); |
| 4042 | assert_eq!(decision.choice, "fast"); |
| 4043 | assert_eq!(decision.confidence_bp, 3000); |
| 4044 | assert_eq!( |
| 4045 | decision.thinking, None, |
| 4046 | "an unacted decision applies no effort" |
| 4047 | ); |
| 4048 | assert_eq!(selection.routed_usage.len(), 1, "usage is still recorded"); |
| 4049 | } |
| 4050 | |
| 4051 | #[tokio::test] |
| 4052 | async fn http_errors_fail_the_router_loudly_without_leaking_bodies() { |
| 4053 | for status in [401_u16, 402, 429, 500] { |
| 4054 | let _env = hermetic_env(); |
| 4055 | let server = MockServer::start().await; |
| 4056 | Mock::given(method("POST")) |
| 4057 | .and(path("/api/alpha/decisions")) |
| 4058 | .respond_with( |
| 4059 | ResponseTemplate::new(status) |
| 4060 | .set_body_string(format!(r#"{{"error":{{"message":"{MARKER}"}}}}"#)), |
| 4061 | ) |
| 4062 | .expect(1) |
| 4063 | .mount(&server) |
| 4064 | .await; |
| 4065 | let mut config = decision_config(&format!("{}/api/v1", server.uri()), false, 2); |
| 4066 | config.retry = Some(toml::from_str("enabled = false").unwrap()); |
| 4067 | let selection = route(&config, "Explain the diff", "").await; |
| 4068 | |
| 4069 | assert_eq!(selection.model, "deepseek-v4-pro", "status {status}"); |
| 4070 | let receipt = receipt(&selection); |
| 4071 | assert!( |
| 4072 | matches!(receipt.reason, AutoRouteReason::ClassifierFallback(_)), |
| 4073 | "status {status}" |
| 4074 | ); |
| 4075 | assert_eq!( |
| 4076 | receipt.router_failure, |
| 4077 | Some(AutoRouterFailure::Http { status }), |
| 4078 | "status {status}" |
| 4079 | ); |
| 4080 | let json = serde_json::to_string(receipt).expect("receipt json"); |
| 4081 | assert!(!json.contains(MARKER), "status {status}: body leaked"); |
| 4082 | assert!(!receipt.router_failure.unwrap().label().contains(MARKER)); |
| 4083 | assert_eq!(selection.routed_usage.len(), 1); |
| 4084 | assert_eq!(selection.routed_usage_dropped_records, 0, "status {status}"); |
| 4085 | assert!(selection.routed_usage_drop_records.is_empty()); |
| 4086 | assert_eq!( |
| 4087 | selection.routed_usage[0] |
| 4088 | .settlement |
| 4089 | .as_ref() |
| 4090 | .unwrap() |
| 4091 | .coverage, |
| 4092 | if matches!(status, 402 | 500) { |
| 4093 | crate::llm_client::ProviderUsageCoverage::Missing |
| 4094 | } else { |
| 4095 | crate::llm_client::ProviderUsageCoverage::Rejected |
| 4096 | }, |
| 4097 | "status {status}" |
| 4098 | ); |
| 4099 | } |
| 4100 | } |
| 4101 | |
| 4102 | #[tokio::test] |
| 4103 | async fn dispatched_timeout_falls_back_and_marks_usage_missing() { |
| 4104 | let _env = hermetic_env(); |
| 4105 | let server = MockServer::start().await; |
| 4106 | Mock::given(method("POST")) |
| 4107 | .and(path("/api/alpha/decisions")) |
| 4108 | .respond_with( |
| 4109 | ResponseTemplate::new(200) |
| 4110 | .set_body_json(answer_body(0.9, 0.8)) |
| 4111 | .set_delay(Duration::from_millis(1_600)), |
| 4112 | ) |
| 4113 | .mount(&server) |
| 4114 | .await; |
| 4115 | let config = decision_config(&format!("{}/api/v1", server.uri()), false, 1); |
| 4116 | let selection = route(&config, "Explain the diff", "").await; |
| 4117 | |
| 4118 | let receipt = receipt(&selection); |
| 4119 | assert_eq!(receipt.router_failure, Some(AutoRouterFailure::Timeout)); |
| 4120 | assert!(matches!( |
| 4121 | receipt.reason, |
| 4122 | AutoRouteReason::ClassifierFallback(_) |
| 4123 | )); |
| 4124 | assert_eq!(selection.routed_usage.len(), 1); |
| 4125 | assert!(selection.routed_usage_drop_records.is_empty()); |
| 4126 | assert_eq!(selection.routed_usage_dropped_records, 0); |
| 4127 | assert_eq!( |
| 4128 | selection.routed_usage[0] |
| 4129 | .settlement |
| 4130 | .as_ref() |
| 4131 | .unwrap() |
| 4132 | .coverage, |
| 4133 | crate::llm_client::ProviderUsageCoverage::Missing |
| 4134 | ); |
| 4135 | assert_eq!( |
| 4136 | selection.routed_usage[0] |
| 4137 | .settlement |
| 4138 | .as_ref() |
| 4139 | .unwrap() |
| 4140 | .physical_requests |
| 4141 | .len(), |
| 4142 | 1 |
| 4143 | ); |
| 4144 | } |
| 4145 | |
| 4146 | #[tokio::test] |
| 4147 | async fn no_fast_strong_pair_means_no_request() { |
| 4148 | let _env = hermetic_env(); |
| 4149 | let server = MockServer::start().await; |
| 4150 | Mock::given(method("POST")) |
| 4151 | .respond_with(ResponseTemplate::new(200).set_body_json(answer_body(0.9, 0.8))) |
| 4152 | .expect(0) |
| 4153 | .mount(&server) |
| 4154 | .await; |
| 4155 | let mut config = decision_config(&format!("{}/api/v1", server.uri()), false, 2); |
| 4156 | // A single-tier active provider: nothing for the decision to choose. |
| 4157 | config.provider = Some("openrouter".to_string()); |
| 4158 | config.default_text_model = Some("synthetic/single-tier-model".to_string()); |
| 4159 | let selection = route(&config, "Refactor everything", "").await; |
| 4160 | |
| 4161 | let receipt = receipt(&selection); |
| 4162 | assert_eq!( |
| 4163 | receipt.reason, |
| 4164 | AutoRouteReason::LocalFallback(AutoRouteHeuristicReason::NoFastSibling) |
| 4165 | ); |
| 4166 | assert_eq!(receipt.data_path, AutoRouteDataPath::LocalHeuristic); |
| 4167 | assert!(selection.routed_usage.is_empty()); |
| 4168 | |
| 4169 | // The setup test must say no call was made, not report a result. |
| 4170 | let reason = test_auto_router(&config, None) |
| 4171 | .await |
| 4172 | .expect_err("no test call without a strong/fast pair"); |
| 4173 | assert_eq!(reason, AutoRouteHeuristicReason::NoFastSibling.label()); |
| 4174 | } |
| 4175 | |
| 4176 | #[tokio::test] |
| 4177 | async fn typesafe_direct_uses_its_own_endpoint_and_key() { |
| 4178 | let _env = hermetic_env(); |
| 4179 | let server = MockServer::start().await; |
| 4180 | Mock::given(method("POST")) |
| 4181 | .and(path("/v1/systemone")) |
| 4182 | .and(header( |
| 4183 | "authorization", |
| 4184 | format!("Bearer {TYPESAFE_TEST_KEY}").as_str(), |
| 4185 | )) |
| 4186 | .respond_with(ResponseTemplate::new(200).set_body_json(answer_body(0.2, 0.6))) |
| 4187 | .expect(1) |
| 4188 | .mount(&server) |
| 4189 | .await; |
| 4190 | let mut config = decision_config("https://openrouter.invalid/api/v1", false, 2); |
| 4191 | let providers = config.providers.as_mut().expect("providers"); |
| 4192 | providers.openrouter.api_key = None; |
| 4193 | // From the environment: not part of any `[providers.*]` table, so |
| 4194 | // only the TypeSafe-specific redaction covers it. |
| 4195 | let _key = crate::test_support::EnvVarGuard::set("TYPESAFE_API_KEY", TYPESAFE_TEST_KEY); |
| 4196 | let router = config |
| 4197 | .auto |
| 4198 | .as_mut() |
| 4199 | .and_then(|auto| auto.router.as_mut()) |
| 4200 | .expect("router"); |
| 4201 | router.provider = Some("typesafe".to_string()); |
| 4202 | router.model = Some("jev-latest".to_string()); |
| 4203 | router.base_url = Some(format!("{}/v1", server.uri())); |
| 4204 | |
| 4205 | // The TypeSafe key is no chat provider's key; a bare echo of it in |
| 4206 | // context must still be redacted from the decision body. |
| 4207 | let selection = route( |
| 4208 | &config, |
| 4209 | "Rename a variable", |
| 4210 | &format!("assistant: [tool result] {TYPESAFE_TEST_KEY}"), |
| 4211 | ) |
| 4212 | .await; |
| 4213 | let requests: Vec<Request> = server.received_requests().await.expect("recorded"); |
| 4214 | let raw = String::from_utf8(requests[0].body.clone()).expect("utf8 body"); |
| 4215 | assert!(!raw.contains(TYPESAFE_TEST_KEY), "TypeSafe key leaked"); |
| 4216 | |
| 4217 | assert_eq!(selection.model, "deepseek-flash"); |
| 4218 | let receipt = receipt(&selection); |
| 4219 | assert_eq!(receipt.reason, AutoRouteReason::ClassifierRecommendation); |
| 4220 | assert_eq!( |
| 4221 | receipt.data_path, |
| 4222 | AutoRouteDataPath::Decision { |
| 4223 | route: DecisionRouterRoute::Typesafe, |
| 4224 | model: "jev-latest".to_string(), |
| 4225 | } |
| 4226 | ); |
| 4227 | assert!(receipt.decision.is_some()); |
| 4228 | // A decision endpoint never inherits the active DeepSeek billing identity. |
| 4229 | assert_eq!(selection.routed_usage.len(), 1); |
| 4230 | let usage = &selection.routed_usage[0]; |
| 4231 | assert_eq!(usage.usage.route.provider, ProviderKind::Custom); |
| 4232 | assert_eq!(usage.usage.route.provider_identity, "typesafe"); |
| 4233 | assert_eq!( |
| 4234 | usage.usage.route.billing_mode, |
| 4235 | crate::cost_status::RouteBillingMode::Unknown |
| 4236 | ); |
| 4237 | assert_eq!(usage.usage.usage.input_tokens, 476); |
| 4238 | assert_eq!(usage.usage.usage.output_tokens, 70); |
| 4239 | assert!(selection.routed_usage_drop_records.is_empty()); |
| 4240 | } |
| 4241 | |
| 4242 | #[test] |
| 4243 | fn declared_router_without_a_key_is_shown_as_failing() { |
| 4244 | let _env = hermetic_env(); |
| 4245 | let mut config = decision_config("https://openrouter.invalid/api/v1", false, 2); |
| 4246 | config |
| 4247 | .providers |
| 4248 | .as_mut() |
| 4249 | .expect("providers") |
| 4250 | .openrouter |
| 4251 | .api_key = None; |
| 4252 | let inventory = ModelInventory::from_config(&config).unwrap(); |
| 4253 | assert!(!inventory.router_available); |
| 4254 | let selection = auto_route_without_router(&config, &inventory); |
| 4255 | assert_eq!( |
| 4256 | receipt(&selection).router_failure, |
| 4257 | Some(AutoRouterFailure::NotRunnable) |
| 4258 | ); |
| 4259 | } |
| 4260 | |
| 4261 | fn parsed(json: serde_json::Value) -> SystemOneResponse { |
| 4262 | serde_json::from_str(&json.to_string()).expect("system one response") |
| 4263 | } |
| 4264 | |
| 4265 | fn pair() -> ActiveTierPair { |
| 4266 | ActiveTierPair { |
| 4267 | provider: Config::default().test_identity_for_kind(ProviderKind::Deepseek), |
| 4268 | strong: "deepseek-v4-pro".to_string(), |
| 4269 | fast: "deepseek-v4-flash".to_string(), |
| 4270 | } |
| 4271 | } |
| 4272 | |
| 4273 | fn policy(cost_saving: bool, response: &SystemOneResponse) -> InventoryAutoRouteAttempt { |
| 4274 | let _env = hermetic_env(); |
| 4275 | let config = decision_config("https://openrouter.invalid/api/v1", cost_saving, 2); |
| 4276 | let inventory = ModelInventory::from_config(&config).unwrap(); |
| 4277 | decision_attempt_from_response(cost_saving, &inventory, &pair(), None, response, 120) |
| 4278 | } |
| 4279 | |
| 4280 | #[test] |
| 4281 | fn cost_saving_needs_a_clear_strong_probability() { |
| 4282 | let unsure = policy(true, &parsed(answer_body(0.70, 0.9))); |
| 4283 | let recommendation = unsure.recommendation.expect("acted"); |
| 4284 | assert_eq!(recommendation.model, "deepseek-v4-flash"); |
| 4285 | assert!(unsure.decision.expect("evidence").cost_saving_kept_fast); |
| 4286 | |
| 4287 | let clear = policy(true, &parsed(answer_body(0.80, 0.9))); |
| 4288 | assert_eq!( |
| 4289 | clear.recommendation.expect("acted").model, |
| 4290 | "deepseek-v4-pro" |
| 4291 | ); |
| 4292 | assert!(!clear.decision.expect("evidence").cost_saving_kept_fast); |
| 4293 | |
| 4294 | let balanced = policy(false, &parsed(answer_body(0.70, 0.9))); |
| 4295 | assert_eq!( |
| 4296 | balanced.recommendation.expect("acted").model, |
| 4297 | "deepseek-v4-pro" |
| 4298 | ); |
| 4299 | } |
| 4300 | |
| 4301 | #[test] |
| 4302 | fn explicit_abstention_survives_decode_and_never_authorizes_auto_at_floor_zero() { |
| 4303 | let _env = hermetic_env(); |
| 4304 | let mut config = decision_config("https://openrouter.invalid/api/v1", false, 2); |
| 4305 | config |
| 4306 | .auto |
| 4307 | .as_mut() |
| 4308 | .unwrap() |
| 4309 | .router |
| 4310 | .as_mut() |
| 4311 | .unwrap() |
| 4312 | .min_confidence = Some(0.0); |
| 4313 | let inventory = ModelInventory::from_config(&config).unwrap(); |
| 4314 | let attempt = |body: serde_json::Value| { |
| 4315 | decision_attempt_from_response(false, &inventory, &pair(), None, &parsed(body), 120) |
| 4316 | }; |
| 4317 | let mut body = answer_body(0.1, 0.9); |
| 4318 | body["answers"]["thinking"]["abstained"] = true.into(); |
| 4319 | let effort_abstained = attempt(body.clone()); |
| 4320 | let recommendation = effort_abstained |
| 4321 | .recommendation |
| 4322 | .expect("valid tier survives effort abstention"); |
| 4323 | assert_eq!(recommendation.model, "deepseek-v4-flash"); |
| 4324 | assert_eq!(recommendation.reasoning_effort, None); |
| 4325 | assert_eq!( |
| 4326 | effort_abstained.decision.unwrap().abstained_questions, |
| 4327 | vec!["thinking"] |
| 4328 | ); |
| 4329 | body["answers"]["tier"]["abstained"] = true.into(); |
| 4330 | let tier_abstained = attempt(body); |
| 4331 | assert!(tier_abstained.recommendation.is_none()); |
| 4332 | assert_eq!( |
| 4333 | tier_abstained.fallback_reason, |
| 4334 | Some(AutoRouteHeuristicReason::LowConfidence) |
| 4335 | ); |
| 4336 | assert_eq!(tier_abstained.failure, None); |
| 4337 | let decision = tier_abstained.decision.unwrap(); |
| 4338 | assert_eq!(decision.abstained_questions, vec!["tier", "thinking"]); |
| 4339 | assert_eq!(decision.choice, "fast"); |
| 4340 | assert_eq!( |
| 4341 | decision.provider_reported_cost_usd.as_deref(), |
| 4342 | Some("0.000019992") |
| 4343 | ); |
| 4344 | } |
| 4345 | |
| 4346 | #[test] |
| 4347 | fn non_boolean_abstention_is_refused_not_ignored() { |
| 4348 | let mut body = answer_body(0.1, 0.9); |
| 4349 | body["answers"]["tier"]["abstained"] = "yes".into(); |
| 4350 | let attempt = policy(false, &parsed(body)); |
| 4351 | assert!(attempt.recommendation.is_none()); |
| 4352 | assert_eq!(attempt.failure, Some(AutoRouterFailure::InvalidAnswer)); |
| 4353 | } |
| 4354 | |
| 4355 | #[test] |
| 4356 | fn invalid_answers_are_rejected_not_repaired() { |
| 4357 | let mut outside = answer_body(0.8, 0.6); |
| 4358 | outside["answers"]["tier"]["choice"] = "medium".into(); |
| 4359 | let mut bad_sum = answer_body(0.8, 0.6); |
| 4360 | bad_sum["answers"]["tier"]["probabilities"]["fast"] = 0.5.into(); |
| 4361 | let mut missing = answer_body(0.8, 0.6); |
| 4362 | missing["answers"] |
| 4363 | .as_object_mut() |
| 4364 | .expect("answers") |
| 4365 | .remove("tier"); |
| 4366 | let mut null_probability = answer_body(0.8, 0.6); |
| 4367 | null_probability["answers"]["tier"]["probabilities"]["fast"] = serde_json::Value::Null; |
| 4368 | let mut bad_confidence = answer_body(0.8, 0.6); |
| 4369 | bad_confidence["answers"]["tier"]["confidence"] = 1.5.into(); |
| 4370 | for body in [outside, bad_sum, missing, null_probability, bad_confidence] { |
| 4371 | let attempt = policy(false, &parsed(body.clone())); |
| 4372 | assert_eq!(attempt.recommendation, None, "{body}"); |
| 4373 | assert_eq!( |
| 4374 | attempt |
| 4375 | .decision |
| 4376 | .as_ref() |
| 4377 | .and_then(|r| r.provider_reported_cost_usd.as_deref()), |
| 4378 | parsed(body.clone()) |
| 4379 | .usage |
| 4380 | .as_ref() |
| 4381 | .and_then(|u| u.reported_cost()) |
| 4382 | .as_deref(), |
| 4383 | "rejected policy retains cost" |
| 4384 | ); |
| 4385 | assert_eq!( |
| 4386 | attempt.failure, |
| 4387 | Some(AutoRouterFailure::InvalidAnswer), |
| 4388 | "{body}" |
| 4389 | ); |
| 4390 | } |
| 4391 | |
| 4392 | // An invalid `thinking` answer drops only the effort. |
| 4393 | let mut bad_thinking = answer_body(0.8, 0.6); |
| 4394 | bad_thinking["answers"]["thinking"]["choice"] = "ultra".into(); |
| 4395 | let attempt = policy(false, &parsed(bad_thinking)); |
| 4396 | let recommendation = attempt.recommendation.expect("tier still acted on"); |
| 4397 | assert_eq!(recommendation.model, "deepseek-v4-pro"); |
| 4398 | assert_eq!(recommendation.reasoning_effort, None); |
| 4399 | } |
| 4400 | |
| 4401 | #[tokio::test] |
| 4402 | async fn malformed_decision_envelopes_preserve_cost_without_a_route_hop() { |
| 4403 | let _env = hermetic_env(); |
| 4404 | for (pointer, value, incomplete_usage) in [ |
| 4405 | ("/answers/tier/choice", serde_json::json!(17), false), |
| 4406 | ("/model", serde_json::json!({"invalid":"model"}), false), |
| 4407 | ("/usage/input_tokens", serde_json::json!(u64::MAX), true), |
| 4408 | ] { |
| 4409 | let server = MockServer::start().await; |
| 4410 | let mut body = answer_body(0.9, 0.9); |
| 4411 | *body.pointer_mut(pointer).expect("fixture field") = value; |
| 4412 | Mock::given(method("POST")) |
| 4413 | .and(path("/api/alpha/decisions")) |
| 4414 | .respond_with(ResponseTemplate::new(200).set_body_json(body)) |
| 4415 | .expect(1) |
| 4416 | .mount(&server) |
| 4417 | .await; |
| 4418 | let config = decision_config(&format!("{}/api/v1", server.uri()), false, 2); |
| 4419 | let fallback = |
| 4420 | auto_route_without_router(&config, &ModelInventory::from_config(&config).unwrap()); |
| 4421 | let selection = route(&config, "Explain a variable name", "").await; |
| 4422 | assert_eq!(selection.source, AutoRouteSource::Heuristic); |
| 4423 | assert_eq!(selection.provider, fallback.provider); |
| 4424 | assert_eq!( |
| 4425 | selection.model, fallback.model, |
| 4426 | "malformed policy cannot change the route" |
| 4427 | ); |
| 4428 | let receipt = receipt(&selection); |
| 4429 | assert_eq!( |
| 4430 | receipt.router_failure, |
| 4431 | Some(AutoRouterFailure::InvalidAnswer) |
| 4432 | ); |
| 4433 | assert_eq!( |
| 4434 | receipt |
| 4435 | .decision |
| 4436 | .as_ref() |
| 4437 | .expect("billing evidence") |
| 4438 | .provider_reported_cost_usd |
| 4439 | .as_deref(), |
| 4440 | Some("0.000019992") |
| 4441 | ); |
| 4442 | if incomplete_usage { |
| 4443 | assert_eq!(selection.routed_usage.len(), 1); |
| 4444 | assert_eq!(selection.routed_usage_dropped_records, 0); |
| 4445 | assert!(selection.routed_usage_drop_records.is_empty()); |
| 4446 | assert!(matches!( |
| 4447 | selection.routed_usage[0] |
| 4448 | .settlement |
| 4449 | .as_ref() |
| 4450 | .unwrap() |
| 4451 | .coverage, |
| 4452 | crate::llm_client::ProviderUsageCoverage::Missing |
| 4453 | | crate::llm_client::ProviderUsageCoverage::Incomplete |
| 4454 | )); |
| 4455 | } else { |
| 4456 | assert_eq!(selection.routed_usage.len(), 1); |
| 4457 | assert!(selection.routed_usage_drop_records.is_empty()); |
| 4458 | } |
| 4459 | } |
| 4460 | } |
| 4461 | |
| 4462 | #[test] |
| 4463 | fn camel_case_usage_and_verbatim_cost_parse() { |
| 4464 | let response = parsed(serde_json::json!({ |
| 4465 | "answers": {}, |
| 4466 | "usage": { "inputTokens": 381, "outputTokens": 62, "cost": 0.000016002 }, |
| 4467 | })); |
| 4468 | let usage = response.usage.expect("usage"); |
| 4469 | assert_eq!(usage.input_tokens, 381); |
| 4470 | assert_eq!(usage.output_tokens, 62); |
| 4471 | assert_eq!(usage.reported_cost().as_deref(), Some("0.000016002")); |
| 4472 | } |
| 4473 | |
| 4474 | #[test] |
| 4475 | fn receipts_saved_before_decision_routing_still_load() { |
| 4476 | let json = r#"{"tier":"fast","pair":{"strong":"deepseek-v4-pro","fast":"deepseek-v4-flash"},"scope":"active_provider","data_path":{"classifier":{"provider":"deepseek","model":"deepseek-v4-flash"}},"reason":"classifier_recommendation"}"#; |
| 4477 | let receipt: AutoRouteReceipt = serde_json::from_str(json).expect("legacy receipt"); |
| 4478 | assert_eq!(receipt.decision, None); |
| 4479 | assert_eq!(receipt.router_failure, None); |
| 4480 | // And the new fields stay off the wire when empty. |
| 4481 | assert_eq!(serde_json::to_string(&receipt).expect("json"), json); |
| 4482 | } |
| 4483 | |
| 4484 | #[tokio::test] |
| 4485 | async fn auto_routing_routes_without_an_admitted_usage_origin() { |
| 4486 | let _env = hermetic_env(); |
| 4487 | for use_source in [false, true] { |
| 4488 | let server = MockServer::start().await; |
| 4489 | Mock::given(method("POST")) |
| 4490 | .and(path("/api/alpha/decisions")) |
| 4491 | .respond_with(ResponseTemplate::new(200).set_body_json(answer_body(0.85, 0.90))) |
| 4492 | .expect(1) |
| 4493 | .mount(&server) |
| 4494 | .await; |
| 4495 | let config = decision_config(&format!("{}/api/v1", server.uri()), false, 2); |
| 4496 | let inventory = ModelInventory::from_config(&config).unwrap(); |
| 4497 | let source = use_source.then(|| { |
| 4498 | let s = crate::cost_status::NativeUsageSource::capture( |
| 4499 | "router-no-origin".to_string(), |
| 4500 | crate::cost_status::UsageSpendOwner::Auxiliary, |
| 4501 | ); |
| 4502 | assert!(s.origin().is_none()); |
| 4503 | s |
| 4504 | }); |
| 4505 | let selection = auto_route_via_router( |
| 4506 | &config, |
| 4507 | &inventory, |
| 4508 | "refactor module", |
| 4509 | "", |
| 4510 | "agent", |
| 4511 | "auto", |
| 4512 | "auto", |
| 4513 | false, |
| 4514 | source, |
| 4515 | ) |
| 4516 | .await |
| 4517 | .expect("classifier must route without an admitted usage origin"); |
| 4518 | assert_eq!(selection.source, AutoRouteSource::FlashRouter); |
| 4519 | assert_eq!(selection.model, "deepseek-v4-pro"); |
| 4520 | } |
| 4521 | } |
| 4522 | } |
| 4523 |