Skip to main content

vtcode_core/llm/
lightweight_routing.rs

1use anyhow::{Context, Result};
2use std::str::FromStr;
3
4use crate::config::api_keys::get_api_key_in_workspace_with_mode;
5use crate::config::constants::model_helpers;
6use crate::config::loader::VTCodeConfig;
7use crate::config::models::{ModelId, Provider, model_catalog_entry};
8use crate::config::types::AgentConfig as RuntimeAgentConfig;
9use crate::llm::factory::{ProviderConfig, create_provider_with_config, infer_provider_from_model};
10use crate::llm::provider::LLMProvider;
11use vtcode_config::auth::AuthCredentialsStoreMode;
12
13/// Features that may use a lightweight (cheaper, faster) model instead of the
14/// primary model to reduce cost and latency.
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub enum LightweightFeature {
17    /// Conversation memory summarization.
18    Memory,
19    /// Generating prompt suggestions for the user.
20    PromptSuggestions,
21    /// Refining user-provided prompts before execution.
22    PromptRefinement,
23    /// Reviewing auto-permission decisions.
24    AutoPermissionReview,
25    /// Probing auto-permission suitability.
26    AutoPermissionProbe,
27    /// Summarizing large file reads.
28    LargeReadSummary,
29    /// Summarizing web-fetched content.
30    WebSummary,
31    /// Summarizing git history.
32    GitHistorySummary,
33    /// Running as a subagent delegate.
34    Subagent,
35    /// Diagnosing a failed or non-zero tool execution from bounded evidence.
36    ToolFailureDiagnosis,
37}
38
39/// A resolved provider-and-model pair that identifies a specific LLM endpoint.
40#[derive(Debug, Clone, PartialEq, Eq)]
41pub struct ModelRoute {
42    /// Lowercase provider registry key (e.g. `"openai"`, `"anthropic"`).
43    pub provider_name: String,
44    /// Model identifier string (e.g. `"gpt-5"`, `"claude-4-sonnet"`).
45    pub model: String,
46}
47
48/// Indicates how a lightweight route was resolved.
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50pub enum LightweightRouteSource {
51    /// An explicit per-feature model override was provided.
52    FeatureOverride,
53    /// The shared `[agent.small_model]` config provided a model name.
54    SharedConfigured,
55    /// The shared small-model config is enabled but no model was named, so one
56    /// was selected automatically.
57    SharedAutomatic,
58    /// No lightweight model applies; the main model is used directly.
59    MainModel,
60}
61
62/// Result of resolving which model a lightweight feature should use.
63#[derive(Debug, Clone, PartialEq, Eq)]
64pub struct LightweightRouteResolution {
65    /// The model route that should be used for the feature.
66    pub primary: ModelRoute,
67    /// The original main-model route, if the primary differs from it.
68    pub fallback: Option<ModelRoute>,
69    /// How this resolution was determined.
70    pub source: LightweightRouteSource,
71    /// Non-fatal warning generated during resolution (e.g. a cross-provider override).
72    pub warning: Option<String>,
73}
74
75impl LightweightRouteResolution {
76    /// Return `true` when a model other than the main model was selected.
77    pub fn uses_lightweight_model(&self) -> bool {
78        !matches!(self.source, LightweightRouteSource::MainModel)
79    }
80
81    /// Return a reference to the main-model fallback route, if one exists.
82    pub fn fallback_to_main_model(&self) -> Option<&ModelRoute> {
83        self.fallback.as_ref()
84    }
85}
86
87/// Resolve the best model route for a given lightweight feature.
88///
89/// Checks, in priority order: explicit per-feature override, shared small-model
90/// config, and automatic model selection for the active provider.
91pub fn resolve_lightweight_route(
92    runtime_config: &RuntimeAgentConfig,
93    vt_cfg: Option<&VTCodeConfig>,
94    feature: LightweightFeature,
95    explicit_override_model: Option<&str>,
96) -> LightweightRouteResolution {
97    let main_route = main_model_route(runtime_config);
98    let main_provider = main_route.provider_name.as_str();
99
100    let mut warning = None;
101    if let Some(configured_model) = explicit_override_model.map(str::trim).filter(|value| !value.is_empty()) {
102        if let Some(route) = route_for_candidate(main_provider, configured_model, vt_cfg) {
103            return LightweightRouteResolution {
104                fallback: (route != main_route).then_some(main_route),
105                primary: route,
106                source: LightweightRouteSource::FeatureOverride,
107                warning: None,
108            };
109        }
110
111        warning = Some(format!(
112            "ignored lightweight override model '{configured_model}' because it does not match the active provider '{main_provider}'"
113        ));
114    }
115
116    let Some(vt_cfg) = vt_cfg else {
117        return LightweightRouteResolution {
118            primary: main_route,
119            fallback: None,
120            source: LightweightRouteSource::MainModel,
121            warning,
122        };
123    };
124
125    let shared_cfg = &vt_cfg.agent.small_model;
126    if !shared_cfg.enabled || !feature_uses_shared_model(shared_cfg, feature) {
127        return LightweightRouteResolution {
128            primary: main_route,
129            fallback: None,
130            source: LightweightRouteSource::MainModel,
131            warning,
132        };
133    }
134
135    let configured_model = shared_cfg.model.trim();
136    if !configured_model.is_empty() {
137        if let Some(route) = route_for_candidate(main_provider, configured_model, Some(vt_cfg)) {
138            return LightweightRouteResolution {
139                fallback: (route != main_route).then_some(main_route),
140                primary: route,
141                source: LightweightRouteSource::SharedConfigured,
142                warning,
143            };
144        }
145
146        warning = Some(format!(
147            "ignored lightweight model '{configured_model}' because it does not match the active provider '{main_provider}'"
148        ));
149    }
150
151    let primary = ModelRoute {
152        provider_name: main_route.provider_name.clone(),
153        model: auto_lightweight_model(main_provider, &main_route.model),
154    };
155    LightweightRouteResolution {
156        fallback: (primary != main_route).then_some(main_route),
157        primary,
158        source: LightweightRouteSource::SharedAutomatic,
159        warning,
160    }
161}
162
163/// Build a [`ModelRoute`] for the primary model from runtime configuration.
164pub fn main_model_route(runtime_config: &RuntimeAgentConfig) -> ModelRoute {
165    let provider_name = if runtime_config.provider.trim().is_empty() {
166        infer_provider_from_model(&runtime_config.model)
167            .map(|provider| provider.to_string().to_lowercase())
168            .unwrap_or_else(|| "gemini".to_string())
169    } else {
170        runtime_config.provider.to_lowercase()
171    };
172
173    ModelRoute { provider_name, model: runtime_config.model.clone() }
174}
175
176/// Automatically select a lightweight model for the given provider and active model.
177///
178/// Prefers a same-generation efficient variant when available, then falls back
179/// to provider defaults.
180pub fn auto_lightweight_model(provider_name: &str, active_model: &str) -> String {
181    let trimmed_model = active_model.trim();
182    let Some(provider) = known_provider_from_name(provider_name).or_else(|| infer_provider_from_model(trimmed_model))
183    else {
184        // A custom endpoint without catalog metadata cannot safely receive a
185        // built-in provider's fallback model. Keep its active model on the
186        // route until the endpoint declares lightweight metadata.
187        return trimmed_model.to_string();
188    };
189
190    if let Some(lightweight_model) = catalog_lightweight_model(provider, trimmed_model) {
191        return lightweight_model;
192    }
193
194    if trimmed_model.is_empty() {
195        return provider_default_lightweight_model(provider)
196            .map(str::to_string)
197            .unwrap_or_default();
198    }
199
200    // An unmapped model may be a user-managed endpoint. Never replace it with
201    // an unrelated provider default just because the provider is known.
202    trimmed_model.to_string()
203}
204
205/// Return the list of available lightweight model choices for the given provider.
206///
207/// The automatically selected model is always first in the list.
208pub fn lightweight_model_choices(provider_name: &str, active_model: &str) -> Vec<String> {
209    let provider = resolve_provider_for_model(provider_name, active_model);
210    let auto_model = auto_lightweight_model(provider_name, active_model);
211    let mut choices = Vec::new();
212
213    if !auto_model.trim().is_empty() {
214        choices.push(auto_model.clone());
215    }
216    if !active_model.trim().is_empty() {
217        choices.push(active_model.trim().to_string());
218    }
219
220    if let Some(provider) = provider
221        && let Some(models) = model_helpers::supported_for(provider.as_ref())
222    {
223        for model in models {
224            let include = model
225                .parse::<ModelId>()
226                .map(|model_id| model_id.is_efficient_variant())
227                .unwrap_or(false)
228                || model.eq_ignore_ascii_case(active_model.trim());
229            if include {
230                choices.push((*model).to_string());
231            }
232        }
233    }
234
235    choices.sort();
236    choices.dedup();
237    if let Some(auto_index) = choices
238        .iter()
239        .position(|candidate| candidate.eq_ignore_ascii_case(auto_model.as_str()))
240    {
241        let auto = choices.remove(auto_index);
242        choices.insert(0, auto);
243    }
244    choices
245}
246
247/// Instantiate an [`LLMProvider`] for the given model route.
248///
249/// Resolves the API key from the runtime config or environment and delegates
250/// to the global factory.
251pub fn create_provider_for_model_route(
252    route: &ModelRoute,
253    runtime_config: &RuntimeAgentConfig,
254    vt_cfg: Option<&VTCodeConfig>,
255) -> Result<Box<dyn LLMProvider>> {
256    let storage_mode = vt_cfg.map(|cfg| cfg.agent.credential_storage_mode).unwrap_or_default();
257    let api_key = resolve_api_key_for_model_route_with_mode(route, runtime_config, storage_mode);
258    create_provider_with_config(
259        &route.provider_name,
260        ProviderConfig {
261            api_key,
262            openai_chatgpt_auth: runtime_config.openai_chatgpt_auth.clone(),
263            copilot_auth: vt_cfg.map(|cfg| cfg.auth.copilot.clone()),
264            base_url: route
265                .provider_name
266                .eq_ignore_ascii_case("anthropic")
267                .then(|| {
268                    vt_cfg
269                        .and_then(|cfg| cfg.provider_overrides.get("anthropic"))
270                        .and_then(|config| config.base_url.clone())
271                })
272                .flatten(),
273            model: Some(route.model.clone()),
274            prompt_cache: Some(runtime_config.prompt_cache.clone()),
275            timeouts: None,
276            openai: vt_cfg.map(|cfg| cfg.provider.openai.clone()),
277            anthropic: vt_cfg.map(|cfg| cfg.provider.anthropic.clone()),
278            openrouter: vt_cfg.map(|cfg| cfg.provider.openrouter.clone()),
279            model_behavior: runtime_config.model_behavior.clone(),
280            workspace_root: Some(runtime_config.workspace.clone()),
281        },
282    )
283    .with_context(|| {
284        format!("Failed to initialize lightweight provider '{}' for model '{}'", route.provider_name, route.model)
285    })
286}
287
288/// Resolve the API key for a model route, using the runtime key when the route
289/// targets the same provider as the main model, or falling back to environment
290/// variables, the workspace `.env`, or secure storage otherwise.
291pub fn resolve_api_key_for_model_route(route: &ModelRoute, runtime_config: &RuntimeAgentConfig) -> Option<String> {
292    resolve_api_key_for_model_route_with_mode(route, runtime_config, AuthCredentialsStoreMode::default())
293}
294
295/// Resolve a lightweight route key using the configured secure-storage mode.
296pub fn resolve_api_key_for_model_route_with_mode(
297    route: &ModelRoute,
298    runtime_config: &RuntimeAgentConfig,
299    storage_mode: AuthCredentialsStoreMode,
300) -> Option<String> {
301    if route
302        .provider_name
303        .eq_ignore_ascii_case(main_model_route(runtime_config).provider_name.as_str())
304        && !runtime_config.api_key.trim().is_empty()
305    {
306        return Some(runtime_config.api_key.clone());
307    }
308
309    get_api_key_in_workspace_with_mode(&route.provider_name, Some(&runtime_config.workspace), storage_mode).ok()
310}
311
312fn feature_uses_shared_model(
313    shared_cfg: &vtcode_config::core::agent::AgentSmallModelConfig,
314    feature: LightweightFeature,
315) -> bool {
316    match feature {
317        LightweightFeature::Memory => shared_cfg.use_for_memory,
318        LightweightFeature::LargeReadSummary => shared_cfg.use_for_large_reads,
319        LightweightFeature::WebSummary => shared_cfg.use_for_web_summary,
320        LightweightFeature::GitHistorySummary => shared_cfg.use_for_git_history,
321        LightweightFeature::PromptSuggestions
322        | LightweightFeature::PromptRefinement
323        | LightweightFeature::AutoPermissionReview
324        | LightweightFeature::AutoPermissionProbe
325        | LightweightFeature::Subagent
326        | LightweightFeature::ToolFailureDiagnosis => true,
327    }
328}
329
330fn route_for_candidate(
331    main_provider: &str,
332    candidate_model: &str,
333    vt_cfg: Option<&VTCodeConfig>,
334) -> Option<ModelRoute> {
335    let is_declared_custom_model = vt_cfg
336        .and_then(|cfg| cfg.custom_provider(main_provider))
337        .is_some_and(|provider| provider.effective_models().iter().any(|model| model == candidate_model));
338
339    if infer_provider_from_model(candidate_model)
340        .map(|provider| !provider.as_ref().eq_ignore_ascii_case(main_provider))
341        .unwrap_or(false)
342        && !is_declared_custom_model
343    {
344        return None;
345    }
346
347    Some(ModelRoute {
348        provider_name: main_provider.to_string(),
349        model: candidate_model.to_string(),
350    })
351}
352
353fn resolve_provider_for_model(provider_name: &str, active_model: &str) -> Option<Provider> {
354    known_provider_from_name(provider_name).or_else(|| infer_provider_from_model(active_model))
355}
356
357fn known_provider_from_name(provider_name: &str) -> Option<Provider> {
358    Provider::from_str(provider_name.trim()).ok()
359}
360
361fn provider_default_lightweight_model(provider: Provider) -> Option<&'static str> {
362    let provider_name = provider.as_ref();
363    let default_model = model_helpers::default_for(provider_name)?;
364    let catalog_lightweight = model_catalog_entry(provider_name, default_model)
365        .and_then(|entry| entry.lightweight_model)
366        .filter(|model| !model.trim().is_empty());
367    Some(catalog_lightweight.unwrap_or(default_model))
368}
369
370/// Resolve the catalog-backed lightweight sibling for a provider/model pair.
371///
372/// `ModelId` and generated catalog entries are two views of the same catalog;
373/// keeping their precedence in one helper prevents the automatic route and
374/// provider-default route from drifting apart.
375fn catalog_lightweight_model(provider: Provider, active_model: &str) -> Option<String> {
376    if let Some(entry) = model_catalog_entry(provider.as_ref(), active_model)
377        && let Some(target) = entry.lightweight_model
378        && !target.trim().is_empty()
379    {
380        return Some(normalize_catalog_target(provider, target));
381    }
382
383    if let Ok(model_id) = active_model.parse::<ModelId>() {
384        if model_id.provider() != provider {
385            return None;
386        }
387        if model_id.is_efficient_variant() {
388            return Some(model_id.as_str().to_string());
389        }
390        if let Some(lightweight_model) = model_id.preferred_lightweight_variant() {
391            return Some(lightweight_model.as_str().to_string());
392        }
393    }
394
395    None
396}
397
398fn normalize_catalog_target(provider: Provider, target: &str) -> String {
399    let target = target.trim();
400    if provider == Provider::Evolink && !target.contains('/') {
401        return format!("evolink/{target}");
402    }
403    target.to_string()
404}
405
406#[cfg(test)]
407mod tests {
408    use super::*;
409
410    fn runtime_config() -> RuntimeAgentConfig {
411        RuntimeAgentConfig {
412            model: ModelId::GPT56Sol.as_str().to_string(),
413            api_key: "test-key".to_string(),
414            provider: "openai".to_string(),
415            openai_chatgpt_auth: None,
416            api_key_env: "OPENAI_API_KEY".to_string(),
417            workspace: std::env::temp_dir().join("vtcode-lightweight-routing-tests"),
418            verbose: false,
419            quiet: false,
420            theme: "default".to_string(),
421            reasoning_effort: Default::default(),
422            ui_surface: Default::default(),
423            prompt_cache: Default::default(),
424            model_source: Default::default(),
425            custom_api_keys: Default::default(),
426            checkpointing_enabled: false,
427            checkpointing_storage_dir: None,
428            checkpointing_max_snapshots: 0,
429            checkpointing_max_age_days: None,
430            max_conversation_turns: 0,
431            model_behavior: None,
432        }
433    }
434
435    #[tokio::test]
436    async fn auxiliary_anthropic_route_sends_to_configured_endpoint() {
437        use crate::llm::provider::{LLMRequest, Message};
438        use tokio::io::{AsyncReadExt, AsyncWriteExt};
439        use tokio::net::TcpListener;
440        use tokio::time::{Duration, timeout};
441
442        let listener = TcpListener::bind("127.0.0.1:0").await.expect("local listener");
443        let address = listener.local_addr().expect("listener address");
444        let server = tokio::spawn(async move {
445            let (mut stream, _) = listener.accept().await.expect("accept request");
446            let mut request = Vec::new();
447            let mut buffer = [0u8; 4096];
448            loop {
449                let count = stream.read(&mut buffer).await.expect("read request");
450                assert_ne!(count, 0, "request closed before headers");
451                request.extend_from_slice(&buffer[..count]);
452                if request.windows(4).any(|window| window == b"\r\n\r\n") {
453                    break;
454                }
455            }
456            let body = r#"{"content":[{"type":"text","text":"ok"}],"stop_reason":"end_turn"}"#;
457            let response = format!(
458                "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
459                body.len()
460            );
461            stream.write_all(response.as_bytes()).await.expect("write response");
462            String::from_utf8(request).expect("request headers")
463        });
464
465        let mut runtime = runtime_config();
466        runtime.provider = "anthropic".to_string();
467        runtime.api_key = "fixture-anthropic-key".to_string();
468        let mut config = VTCodeConfig::default();
469        config.provider_overrides.entry("anthropic".to_string()).or_default().base_url =
470            Some(format!("http://{address}/gateway/v1"));
471        let route = ModelRoute {
472            provider_name: "anthropic".to_string(),
473            model: "claude-sonnet-5-5".to_string(),
474        };
475        let provider = create_provider_for_model_route(&route, &runtime, Some(&config)).expect("provider");
476        let response = timeout(
477            Duration::from_secs(5),
478            provider.generate(LLMRequest {
479                model: route.model,
480                messages: vec![Message::user("hello".to_string())].into(),
481                ..Default::default()
482            }),
483        )
484        .await
485        .expect("request timeout")
486        .expect("provider response");
487        assert_eq!(response.content.as_deref(), Some("ok"));
488        let request = timeout(Duration::from_secs(5), server)
489            .await
490            .expect("server timeout")
491            .expect("server task");
492        assert!(request.starts_with("POST /gateway/v1/messages HTTP/1.1\r\n"), "{request}");
493        assert!(request.to_ascii_lowercase().contains("x-api-key: fixture-anthropic-key\r\n"));
494    }
495
496    #[test]
497    fn route_credentials_use_runtime_workspace_and_inherited_environment() {
498        const CHILD: &str = "VTCODE_LIGHTWEIGHT_ROUTE_TEST_CHILD";
499        const KEY: &str = "VTCODE_ROUTE_ISOLATION_API_KEY";
500        if let Some(workspace) = std::env::var_os(CHILD) {
501            let mut runtime = runtime_config();
502            runtime.workspace = workspace.into();
503            let route = ModelRoute {
504                provider_name: "vtcode_route_isolation".to_string(),
505                model: "secondary".to_string(),
506            };
507            let expected = std::env::var(KEY).unwrap_or_else(|_| "workspace-key".to_string());
508            assert_eq!(
509                resolve_api_key_for_model_route_with_mode(&route, &runtime, AuthCredentialsStoreMode::File).as_deref(),
510                Some(expected.as_str())
511            );
512            assert_eq!(
513                resolve_api_key_for_model_route_with_mode(
514                    &main_model_route(&runtime),
515                    &runtime,
516                    AuthCredentialsStoreMode::File
517                )
518                .as_deref(),
519                Some("test-key")
520            );
521            return;
522        }
523
524        let workspace = tempfile::tempdir().expect("workspace");
525        let other = tempfile::tempdir().expect("other workspace");
526        std::fs::write(workspace.path().join(".env"), format!("{KEY}=workspace-key\n")).expect("workspace dotenv");
527        std::fs::write(other.path().join(".env"), format!("{KEY}=other-key\n")).expect("other dotenv");
528        for inherited in [None, Some("inherited-key")] {
529            let mut command = std::process::Command::new(std::env::current_exe().expect("test executable"));
530            command
531                .arg("--exact")
532                .arg("llm::lightweight_routing::tests::route_credentials_use_runtime_workspace_and_inherited_environment")
533                .env(CHILD, workspace.path())
534                .current_dir(other.path());
535            if let Some(value) = inherited {
536                command.env(KEY, value);
537            } else {
538                command.env_remove(KEY);
539            }
540            let output = command.output().expect("run isolated route test");
541            assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr));
542            assert!(String::from_utf8_lossy(&output.stdout).contains("1 passed"));
543        }
544    }
545
546    #[test]
547    fn explicit_override_uses_active_provider() {
548        let runtime = runtime_config();
549        let route = resolve_lightweight_route(
550            &runtime,
551            Some(&VTCodeConfig::default()),
552            LightweightFeature::Memory,
553            Some("gpt-5-mini"),
554        );
555
556        assert_eq!(route.primary.provider_name, "openai");
557        assert_eq!(route.primary.model, "gpt-5-mini");
558        assert_eq!(route.source, LightweightRouteSource::FeatureOverride);
559    }
560
561    #[test]
562    fn cross_provider_shared_model_falls_back_to_auto_same_provider() {
563        let runtime = runtime_config();
564        let mut vt_cfg = VTCodeConfig::default();
565        vt_cfg.agent.small_model.model = "claude-4-5-haiku".to_string();
566
567        let route = resolve_lightweight_route(&runtime, Some(&vt_cfg), LightweightFeature::PromptSuggestions, None);
568
569        assert_eq!(route.primary.provider_name, "openai");
570        assert_eq!(route.primary.model, ModelId::GPT56Terra.as_str());
571        assert_eq!(route.source, LightweightRouteSource::SharedAutomatic);
572        assert!(route.warning.is_some());
573    }
574
575    #[test]
576    fn explicit_override_accepts_declared_custom_provider_model_that_infers_builtin_provider() {
577        // Arrange: the custom provider explicitly declares a GPT-slugged model.
578        let mut runtime = runtime_config();
579        runtime.provider = "my-gateway".to_string();
580        let mut vt_cfg = VTCodeConfig::default();
581        vt_cfg.custom_providers.push(vtcode_config::core::CustomProviderConfig {
582            name: "my-gateway".to_string(),
583            models: vec![" gpt-5.6-luna ".to_string()],
584            ..Default::default()
585        });
586
587        // Act: resolve an explicitly overridden model with surrounding whitespace.
588        let route = resolve_lightweight_route(
589            &runtime,
590            Some(&vt_cfg),
591            LightweightFeature::PromptSuggestions,
592            Some("  gpt-5.6-luna  "),
593        );
594
595        // Assert: declaration wins over built-in provider inference and is normalized.
596        assert_eq!(
597            route.primary,
598            ModelRoute {
599                provider_name: "my-gateway".to_string(),
600                model: "gpt-5.6-luna".to_string(),
601            }
602        );
603        assert_eq!(route.source, LightweightRouteSource::FeatureOverride);
604        assert!(route.warning.is_none());
605    }
606
607    #[test]
608    fn shared_small_model_accepts_declared_custom_provider_model_that_infers_builtin_provider() {
609        // Arrange: shared small-model config selects a model declared by the active custom provider.
610        let mut runtime = runtime_config();
611        runtime.provider = "my-gateway".to_string();
612        let mut vt_cfg = VTCodeConfig::default();
613        vt_cfg.agent.small_model.model = "  gpt-5.6-luna  ".to_string();
614        vt_cfg.custom_providers.push(vtcode_config::core::CustomProviderConfig {
615            name: "my-gateway".to_string(),
616            models: vec!["gpt-5.6-luna".to_string()],
617            ..Default::default()
618        });
619
620        // Act: resolve the shared configured lightweight model.
621        let route = resolve_lightweight_route(&runtime, Some(&vt_cfg), LightweightFeature::PromptSuggestions, None);
622
623        // Assert: the declared model is selected through the active custom provider.
624        assert_eq!(
625            route.primary,
626            ModelRoute {
627                provider_name: "my-gateway".to_string(),
628                model: "gpt-5.6-luna".to_string(),
629            }
630        );
631        assert_eq!(route.source, LightweightRouteSource::SharedConfigured);
632        assert!(route.warning.is_none());
633    }
634
635    #[test]
636    fn auto_lightweight_model_prefers_same_generation_openai_sibling() {
637        assert_eq!(auto_lightweight_model("openai", &ModelId::GPT56Sol.as_str()), ModelId::GPT56Terra.as_str());
638    }
639
640    #[test]
641    fn auto_lightweight_model_uses_catalog_anthropic_pair() {
642        assert_eq!(
643            auto_lightweight_model("anthropic", &ModelId::ClaudeSonnet5.as_str()),
644            ModelId::ClaudeSonnet5.as_str()
645        );
646        assert_eq!(auto_lightweight_model("anthropic", "claude-sonnet-4.5"), "claude-sonnet-4.5");
647    }
648
649    #[test]
650    fn auto_lightweight_model_uses_lower_generation_glm_pair() {
651        assert_eq!(auto_lightweight_model("zai", &ModelId::ZaiGlm53.as_str()), ModelId::ZaiGlm53.as_str());
652    }
653
654    #[test]
655    fn auto_lightweight_model_prefers_same_generation_gemini_flash_lite() {
656        assert_eq!(auto_lightweight_model("gemini", &ModelId::Gemini38Flash.as_str()), ModelId::Gemini38Flash.as_str());
657    }
658
659    #[test]
660    fn auto_lightweight_model_infers_family_for_custom_provider() {
661        assert_eq!(auto_lightweight_model("mycorp", &ModelId::GPT56Sol.as_str()), ModelId::GPT56Terra.as_str());
662    }
663
664    #[test]
665    fn auto_lightweight_model_keeps_unmapped_custom_route() {
666        assert_eq!(auto_lightweight_model("mycorp", "custom-model-v1"), "custom-model-v1");
667    }
668
669    #[test]
670    fn auto_lightweight_model_keeps_unmapped_model_for_known_provider() {
671        assert_eq!(auto_lightweight_model("openai", "custom-model-v1"), "custom-model-v1");
672    }
673
674    #[test]
675    fn auto_lightweight_model_keeps_unmapped_evolink_route() {
676        assert_eq!(auto_lightweight_model("evolink", "evolink/deepseek-v4-pro"), "evolink/deepseek-v4-pro");
677    }
678
679    #[test]
680    fn lightweight_model_choices_do_not_invent_provider_for_unknown_route() {
681        assert_eq!(lightweight_model_choices("mycorp", "custom-model-v1"), vec!["custom-model-v1"]);
682    }
683
684    #[test]
685    fn disabled_feature_uses_main_model() {
686        let runtime = runtime_config();
687        let mut vt_cfg = VTCodeConfig::default();
688        vt_cfg.agent.small_model.use_for_memory = false;
689
690        let route = resolve_lightweight_route(&runtime, Some(&vt_cfg), LightweightFeature::Memory, None);
691
692        assert_eq!(route.primary.model, ModelId::GPT56Sol.as_str());
693        assert_eq!(route.source, LightweightRouteSource::MainModel);
694        assert!(route.fallback.is_none());
695    }
696}