1use anyhow::{Result, bail};
6use std::path::Path;
7use vtcode_commons::MultiErrors;
8use vtcode_commons::provider::{CODEX_PROVIDER_ID, Provider};
9
10use crate::config::FullAutoConfig;
11use crate::config::loader::VTCodeConfig;
12use crate::config::models::{catalog_provider_keys, model_catalog_entry, supported_models_for_provider};
13use vtcode_config::core::CustomProviderConfig;
14
15#[derive(Debug, Clone)]
17pub struct ValidationResult {
18 pub is_valid: bool,
19 pub errors: MultiErrors<String>,
20 pub warnings: Vec<String>,
21}
22
23impl ValidationResult {
24 pub fn new() -> Self {
25 Self {
26 is_valid: true,
27 errors: MultiErrors::new(),
28 warnings: Vec::new(),
29 }
30 }
31
32 pub fn add_error(&mut self, error: String) {
33 self.is_valid = false;
34 self.errors.push(error);
35 }
36
37 pub fn add_warning(&mut self, warning: String) {
38 self.warnings.push(warning);
39 }
40}
41
42impl Default for ValidationResult {
43 fn default() -> Self {
44 Self::new()
45 }
46}
47
48pub fn validate_model_exists(provider: &str, model: &str) -> Result<()> {
50 if provider.eq_ignore_ascii_case("copilot") || provider.eq_ignore_ascii_case("merge-gateway") {
51 if model.trim().is_empty() {
52 bail!("Model must not be empty for provider '{provider}'");
53 }
54 return Ok(());
55 }
56
57 if let Some(models) = supported_models_for_provider(provider) {
58 if !models.contains(&model) {
59 if Provider::OpenAI.name_matches(provider)
61 && let Some((replacement, reason)) =
62 vtcode_config::constants::models::openai::deprecated_model_replacement(model)
63 {
64 bail!("{reason}. Update your config to use '{replacement}' or run /model to pick a current model.");
65 }
66 bail!("Model '{}' not found for provider '{}'. Available models: {}", model, provider, models.join(", "));
67 }
68 Ok(())
69 } else {
70 bail!(
71 "Provider '{}' not recognized. Available providers: {}",
72 provider,
73 catalog_provider_keys().join(", ")
74 );
75 }
76}
77
78fn catalog_model_context_window(provider: &str, model: &str) -> Result<Option<usize>> {
80 Ok(model_catalog_entry(provider, model)
81 .map(|entry| entry.context_window)
82 .filter(|context_window| *context_window > 0))
83}
84
85pub fn effective_model_context_window(provider: &str, model: &str) -> Result<Option<usize>> {
87 if Provider::Anthropic.name_matches(provider) {
88 return Ok(Some(crate::llm::providers::anthropic::capabilities::effective_context_size(model)));
89 }
90
91 catalog_model_context_window(provider, model)
92}
93
94fn custom_provider_for_model<'a>(
95 config: &'a VTCodeConfig,
96 provider: &str,
97 model: &str,
98) -> Option<&'a CustomProviderConfig> {
99 config
100 .custom_providers
101 .iter()
102 .find(|custom| custom.name.eq_ignore_ascii_case(provider))
103 .and_then(|custom| {
104 custom.effective_models().into_iter().find(|candidate| candidate == model)?;
105 Some(custom)
106 })
107}
108
109fn effective_model_context_window_for_config(
110 config: &VTCodeConfig,
111 provider: &str,
112 model: &str,
113) -> Result<Option<usize>> {
114 if let Some(custom) = custom_provider_for_model(config, provider, model) {
115 let profile = custom.resolved_profile(model);
116 if let Some(context_window) = profile.context_window {
117 return Ok(Some(context_window));
118 }
119
120 return match profile.api_format {
121 Some(vtcode_config::core::CustomProviderApiFormat::AnthropicMessages) => {
122 effective_model_context_window("anthropic", model)
123 }
124 _ => Ok(effective_model_context_window("openai", model)?.or(Some(128_000))),
125 };
126 }
127
128 effective_model_context_window(provider, model)
129}
130
131pub fn validate_config(config: &VTCodeConfig, workspace: &Path) -> Result<ValidationResult> {
133 let mut result = ValidationResult::new();
134
135 validate_agent_model(config, &mut result);
137
138 if !config.providers_whitelist.is_empty()
140 && !config
141 .providers_whitelist
142 .iter()
143 .any(|w| w.eq_ignore_ascii_case(&config.agent.provider))
144 {
145 result.add_error(format!(
146 "Provider '{}' is not in providers_whitelist: {:?}",
147 config.agent.provider, config.providers_whitelist
148 ));
149 }
150
151 validate_context_window(config, &mut result);
153
154 if config.agent.checkpointing.enabled
156 && let Some(storage_dir) = &config.agent.checkpointing.storage_dir
157 {
158 validate_checkpointing_dir(storage_dir, workspace, &mut result);
159 }
160
161 if config.automation.full_auto.enabled {
163 validate_full_auto_config(&config.automation.full_auto, workspace, &mut result);
164 }
165
166 Ok(result)
167}
168
169fn validate_agent_model(config: &VTCodeConfig, result: &mut ValidationResult) {
170 let provider = &config.agent.provider;
171 let model = &config.agent.default_model;
172 if provider.eq_ignore_ascii_case(CODEX_PROVIDER_ID) {
173 return;
174 }
175
176 let validation = if let Some(custom) = config
177 .custom_providers
178 .iter()
179 .find(|custom| custom.name.eq_ignore_ascii_case(provider))
180 {
181 if custom.effective_models().iter().any(|candidate| candidate == model) {
182 Ok(())
183 } else {
184 Err(anyhow::anyhow!(
185 "Model '{}' not found for custom provider '{}'. Available models: {}",
186 model,
187 custom.display_name,
188 custom.effective_models().join(", ")
189 ))
190 }
191 } else {
192 validate_model_exists(provider, model)
193 };
194
195 match validation {
196 Ok(_) => {
197 if let Ok(Some(context_size)) = effective_model_context_window_for_config(config, provider, model) {
199 let display_size = if context_size >= 1_000_000 {
200 format!("{}M", context_size / 1_000_000)
201 } else if context_size >= 1_000 {
202 format!("{}K", context_size / 1_000)
203 } else {
204 context_size.to_string()
205 };
206 tracing::debug!("Agent model '{}' context window: {}", model, display_size);
207 }
208 }
209 Err(e) => {
210 result.add_error(format!("Agent model configuration invalid: {e}"));
211 }
212 }
213}
214
215fn validate_context_window(config: &VTCodeConfig, result: &mut ValidationResult) {
216 if config.agent.provider.eq_ignore_ascii_case(CODEX_PROVIDER_ID) {
217 return;
218 }
219
220 let context_window = config.context.max_context_tokens;
221 if context_window > 0
222 && let Ok(Some(model_context)) =
223 effective_model_context_window_for_config(config, &config.agent.provider, &config.agent.default_model)
224 && context_window > model_context
225 {
226 result.add_warning(format!(
227 "Configured session context safety budget {context_window} exceeds provider capacity {model_context}. \
228 The provider capacity remains the hard upper bound for compaction and request validation."
229 ));
230 }
231}
232
233fn validate_checkpointing_dir(storage_dir: &str, workspace: &Path, result: &mut ValidationResult) {
234 let path = if Path::new(storage_dir).is_absolute() {
235 std::path::PathBuf::from(storage_dir)
236 } else {
237 workspace.join(storage_dir)
238 };
239
240 if let Some(parent) = path.parent()
242 && !parent.exists()
243 {
244 result.add_warning(format!(
245 "Checkpointing storage directory parent '{}' does not exist. \
246 It will be created when checkpointing is first used.",
247 parent.display()
248 ));
249 }
250}
251
252fn validate_full_auto_config(full_auto_cfg: &FullAutoConfig, workspace: &Path, result: &mut ValidationResult) {
253 if full_auto_cfg.require_profile_ack {
254 if let Some(profile_path) = &full_auto_cfg.profile_path {
255 let resolved = if Path::new(profile_path).is_absolute() {
256 std::path::PathBuf::from(profile_path)
257 } else {
258 workspace.join(profile_path)
259 };
260
261 if !resolved.exists() {
262 result.add_error(format!(
263 "Full-auto profile '{}' required but not found. \
264 Create the acknowledgement file before using --full-auto.",
265 resolved.display()
266 ));
267 }
268 } else {
269 result.add_error("Full-auto profile_path is required when require_profile_ack = true".to_owned());
270 }
271 }
272}
273
274#[cfg(test)]
275mod tests {
276 use super::*;
277
278 #[test]
279 fn generated_catalog_contains_providers() {
280 let providers = catalog_provider_keys();
281 assert!(!providers.is_empty(), "Should expose generated providers");
282 assert!(
283 providers.contains(&"gemini") || providers.contains(&"openai"),
284 "Should have at least one major provider"
285 );
286 }
287
288 #[test]
289 fn validates_known_model() {
290 let result = validate_model_exists("google", "gemini-3.7-flash");
291 assert!(result.is_ok(), "Should validate gemini-3.7-flash for google provider");
292 }
293
294 #[test]
295 fn rejects_unknown_model() {
296 let result = validate_model_exists("google", "model-does-not-exist");
297 assert!(result.is_err(), "Should reject unknown model");
298 }
299
300 #[test]
301 fn accepts_live_copilot_model_id() {
302 let result = validate_model_exists("copilot", "gpt-5-codex");
303 assert!(result.is_ok(), "Should accept live Copilot model ids");
304 }
305
306 #[test]
307 fn accepts_arbitrary_merge_gateway_model_id() {
308 let result = validate_model_exists("merge-gateway", "deepseek/deepseek-v4-pro");
309 assert!(result.is_ok(), "Merge Gateway should accept valid explicit route ids");
310 }
311
312 #[test]
313 fn validate_config_skips_codex_model_catalog_checks() {
314 let mut config = VTCodeConfig::default();
315 config.agent.provider = "codex".to_string();
316 config.agent.default_model = "upstream-managed-model".to_string();
317
318 let result = validate_config(&config, Path::new(".")).expect("config validation should run");
319
320 assert!(result.errors.is_empty());
321 }
322
323 #[test]
324 fn rejects_unknown_provider() {
325 let result = validate_model_exists("provider-does-not-exist", "some-model");
326 assert!(result.is_err(), "Should reject unknown provider");
327 }
328
329 #[test]
330 fn gets_context_window() {
331 let result = effective_model_context_window("google", "gemini-3.7-flash");
332 assert!(result.is_ok(), "Should get context window");
333
334 let context = result.unwrap();
335 assert!(context.is_some() && context.unwrap() > 0, "Should have positive context window");
336 }
337
338 #[test]
339 fn anthropic_46_uses_effective_context_window() {
340 let result = effective_model_context_window("anthropic", "claude-sonnet-5");
341 assert_eq!(result.unwrap(), Some(1_000_000));
342 }
343
344 #[test]
345 fn validation_result_collects_errors() {
346 let mut result = ValidationResult::new();
347 assert!(result.is_valid);
348
349 result.add_error("Error 1".to_owned());
350 assert!(!result.is_valid);
351
352 result.add_error("Error 2".to_owned());
353 assert_eq!(result.errors.len(), 2);
354 }
355
356 #[test]
357 fn validation_result_collects_warnings() {
358 let mut result = ValidationResult::new();
359 result.add_warning("Warning 1".to_owned());
360 assert_eq!(result.warnings.len(), 1);
361 assert!(result.is_valid); }
363
364 #[test]
365 fn whitelist_allows_configured_provider() {
366 let mut config = VTCodeConfig::default();
367 config.agent.provider = "openai".to_string();
368 config.agent.default_model = "gpt-5.6-sol".to_string();
369 config.providers_whitelist = vec!["openai".to_string()];
370
371 let result = validate_config(&config, Path::new(".")).expect("validation should run");
372 assert!(result.errors.is_empty(), "openai should pass when whitelisted: {:?}", result.errors);
373 }
374
375 #[test]
376 fn whitelist_blocks_non_whitelisted_provider() {
377 let mut config = VTCodeConfig::default();
378 config.agent.provider = "openai".to_string();
379 config.agent.default_model = "gpt-5.6-sol".to_string();
380 config.providers_whitelist = vec!["anthropic".to_string()];
381
382 let result = validate_config(&config, Path::new(".")).expect("validation should run");
383 assert!(
384 result.errors.iter().any(|e| e.contains("not in providers_whitelist")),
385 "expected whitelist error, got: {:?}",
386 result.errors
387 );
388 }
389
390 #[test]
391 fn empty_whitelist_allows_all_providers() {
392 let mut config = VTCodeConfig::default();
393 config.agent.provider = "openai".to_string();
394 config.agent.default_model = "gpt-5.6-sol".to_string();
395 config.providers_whitelist.clear();
396
397 let result = validate_config(&config, Path::new(".")).expect("validation should run");
398 assert!(result.errors.is_empty(), "empty whitelist should allow all: {:?}", result.errors);
399 }
400
401 #[test]
402 fn deprecated_openai_model_produces_actionable_error() {
403 let mut config = VTCodeConfig::default();
404 config.agent.provider = "openai".to_string();
405 config.agent.default_model = "gpt-5".to_string();
406 config.providers_whitelist.clear();
407
408 let result = validate_config(&config, Path::new(".")).expect("validation should run");
409 assert!(
410 result.errors.iter().any(|e| e.contains("gpt-5.6-sol")),
411 "expected actionable deprecation replacement, got: {:?}",
412 result.errors
413 );
414 }
415
416 #[test]
417 fn non_openai_provider_with_deprecated_id_gets_generic_error() {
418 let mut config = VTCodeConfig::default();
421 config.agent.provider = "custom-provider".to_string();
422 config.agent.default_model = "gpt-5".to_string();
423 config.providers_whitelist.clear();
424 config.custom_providers.push(CustomProviderConfig {
427 name: "custom-provider".to_string(),
428 models: vec!["gpt-5".to_string()],
429 ..Default::default()
430 });
431
432 let result = validate_config(&config, Path::new(".")).expect("validation should run");
433 assert!(
434 !result.errors.iter().any(|e| e.contains("gpt-5.6-sol")),
435 "non-OpenAI provider should not get OpenAI migration advice: {:?}",
436 result.errors
437 );
438 }
439}