Skip to main content

vtcode_commons/
misconfiguration.rs

1//! Misconfiguration-first failure classification.
2//!
3//! For every runtime failure, callers must check settings/config before
4//! retrying. This module is the shared detector: given an [`ErrorCategory`]
5//! plus the raw error text, it returns actionable [`ConfigGuidance`] when the
6//! failure is caused by user misconfiguration (bad credentials, unknown
7//! model/provider, invalid `base_url`, malformed `vtcode.toml`, bad MCP or
8//! sampling params).
9//!
10//! Transient failures (network, timeout, rate-limit, 5xx) return `None` so
11//! existing retry policy applies unchanged. LLM argument mistakes (bad patch,
12//! bad tool args) also return `None` — they lack config markers.
13
14use std::borrow::Cow;
15
16use crate::config_keys::ConfigKey;
17use crate::error_category::ErrorCategory;
18
19/// Kind of user misconfiguration detected.
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
21pub enum MisconfigurationKind {
22    Authentication,
23    Model,
24    Provider,
25    BaseUrl,
26    ApiKeyEnv,
27    ConfigFile,
28    Mcp,
29    SamplingParams,
30}
31
32/// Actionable guidance for fixing a misconfiguration.
33///
34/// All strings are static to avoid allocation on the failure path.
35/// Callers format them with [`ConfigGuidance::user_message`].
36#[derive(Debug, Clone, PartialEq, Eq)]
37pub struct ConfigGuidance {
38    /// What kind of misconfiguration was detected.
39    pub kind: MisconfigurationKind,
40    /// Settings key to check (e.g. `agent.model`).
41    pub setting: &'static str,
42    /// Where the setting lives (e.g. `vtcode.toml`).
43    pub location: &'static str,
44    /// Actionable fix steps.
45    pub fix: Cow<'static, str>,
46}
47
48impl ConfigGuidance {
49    /// Render a user-facing message that directs to settings/config first.
50    #[must_use]
51    pub fn user_message(&self) -> String {
52        format!(
53            "Check settings/config first ({} in {}): {} Correct the configuration before retrying.",
54            self.setting, self.location, self.fix
55        )
56    }
57}
58
59/// Return guidance when `message` indicates user misconfiguration.
60///
61/// `category` is used to short-circuit obvious cases (e.g. `Authentication`
62/// is always misconfiguration) and to avoid false positives on transient
63/// categories without config markers.
64#[must_use]
65pub fn detect_misconfiguration(category: ErrorCategory, message: &str) -> Option<ConfigGuidance> {
66    // Authentication failures are always user-fixable credentials issues.
67    if matches!(category, ErrorCategory::Authentication) {
68        return Some(auth_guidance());
69    }
70
71    let msg = message.to_ascii_lowercase();
72
73    // Config-file markers take priority: explicit vtcode.toml problems.
74    if contains_any(
75        &msg,
76        &[
77            "vtcode.toml",
78            "config invalid",
79            "config missing",
80            "config parse",
81            "configparse",
82            "failed to parse config",
83            "malformed config",
84            "invalid custom_providers",
85            "invalid provider_overrides",
86            "repository-controlled",
87            "protected field",
88        ],
89    ) || (msg.contains("workspace_lifecycle_hooks")
90        && contains_any(&msg, &["invalid", "missing", "not allowed", "config"]))
91    {
92        return Some(ConfigGuidance {
93            kind: MisconfigurationKind::ConfigFile,
94            setting: "vtcode.toml",
95            location: "workspace / user / system config layers",
96            fix: Cow::Borrowed(
97                "Invalid config file. Validate vtcode.toml syntax and fields, keep `custom_providers` and `provider_overrides.*.base_url`/`api_key_env` out of repository layers, then retry.",
98            ),
99        });
100    }
101
102    // Endpoint / base_url problems. Checked before generic provider
103    // markers because `custom_providers[x]: base_url ...` contains both.
104    if contains_any(
105        &msg,
106        &[
107            "invalid endpoint",
108            "invalid base url",
109            "unsupported protocol",
110            "endpoint must",
111            "endpoint is invalid",
112        ],
113    ) || (msg.contains("base_url")
114        && contains_any(
115            &msg,
116            &[
117                "invalid",
118                "empty",
119                "missing",
120                "must",
121                "cannot",
122                "malformed",
123                "parse",
124                "scheme",
125            ],
126        ))
127    {
128        return Some(ConfigGuidance {
129            kind: MisconfigurationKind::BaseUrl,
130            setting: "provider_overrides.*.base_url / custom_providers.*.base_url",
131            location: "system / user / explicit config file only",
132            fix: Cow::Borrowed(
133                "Invalid endpoint. Check `base_url` is non-empty, uses a supported URL scheme, and is reachable, then retry.",
134            ),
135        });
136    }
137
138    // API-key env problems (distinct from authentication rejections above).
139    if contains_any(
140        &msg,
141        &[
142            "invalid `api_key_env`",
143            "invalid api_key_env",
144            "api key env",
145            "api_key_env must",
146            "missing api key",
147            "no api key",
148            "api key not found",
149            "api key is not set",
150            "api key not configured",
151            "api key is required",
152            "api key environment variable must",
153            "missing mcp api key",
154            "api-key env",
155        ],
156    ) {
157        return Some(ConfigGuidance {
158            kind: MisconfigurationKind::ApiKeyEnv,
159            setting: "api_key_env",
160            location: "vtcode.toml + environment",
161            fix: Cow::Borrowed(
162                "Invalid API-key config. Check `api_key_env` names a valid exported env var (or use `/secret`), then retry.",
163            ),
164        });
165    }
166
167    // Provider identity problems.
168    if contains_any(
169        &msg,
170        &[
171            "unknown provider",
172            "unknown_provider",
173            "invalid provider",
174            "invalid_provider",
175            "unsupported provider",
176            "unsupported_provider",
177            "provider not found",
178            "provider_not_found",
179        ],
180    ) || (contains_any(&msg, &[ConfigKey::PROVIDER, "custom_providers", "provider_overrides"])
181        && contains_any(&msg, &["invalid", "unknown", "unsupported", "not found", "missing", "empty"]))
182    {
183        return Some(ConfigGuidance {
184            kind: MisconfigurationKind::Provider,
185            setting: ConfigKey::PROVIDER,
186            location: "vtcode.toml",
187            fix: Cow::Borrowed(
188                "Unknown/invalid provider. Check `agent.provider` and `custom_providers` in vtcode.toml, then retry.",
189            ),
190        });
191    }
192
193    // Model identity problems. Require model-specific markers so generic
194    // "not found" file errors do not match.
195    if contains_any(
196        &msg,
197        &[
198            "unknown model",
199            "unknown_model",
200            "invalid model",
201            "invalid_model",
202            "model not found",
203            "model_not_found",
204            "model not available",
205            "model_not_available",
206            "unsupported model",
207            "unsupported_model",
208            "model does not exist",
209            "model doesn't exist",
210            "model is not supported",
211            "model not supported",
212            "catalog-missing",
213            "catalog missing",
214        ],
215    ) || (msg.contains("model ")
216        && contains_any(&msg, &[" is not supported", " not supported by", " not supported with"]))
217        || (contains_any(&msg, &["model id", "model_id", "agent.model", ConfigKey::DEFAULT_MODEL])
218            && contains_any(
219                &msg,
220                &[
221                    "invalid",
222                    "unknown",
223                    "not found",
224                    "not available",
225                    "unsupported",
226                    "missing",
227                    "empty",
228                ],
229            ))
230    {
231        return Some(ConfigGuidance {
232            kind: MisconfigurationKind::Model,
233            setting: ConfigKey::DEFAULT_MODEL,
234            location: "vtcode.toml / `/model` picker",
235            fix: Cow::Borrowed(
236                "Unknown/invalid model. Check `agent.default_model` in vtcode.toml or run `/model` to pick a supported ModelId, then retry.",
237            ),
238        });
239    }
240
241    // MCP / WebMCP config problems.
242    if contains_any(&msg, &["mcp config", "https when enabled"])
243        || (contains_any(&msg, &["mcp server", "mcp url", "webmcp"])
244            && contains_any(&msg, &["invalid", "missing", "not allowed", "must", "unsupported"]))
245        || (msg.contains("mcp")
246            && contains_any(&msg, &["origin", "roots", "https", "url", "config"])
247            && contains_any(&msg, &["invalid", "missing", "not allowed", "must", "unsupported"]))
248    {
249        return Some(ConfigGuidance {
250            kind: MisconfigurationKind::Mcp,
251            setting: "mcp / webmcp",
252            location: "vtcode.toml",
253            fix: Cow::Borrowed(
254                "MCP misconfiguration. Check `mcp`/`webmcp` URLs are HTTPS, origins and roots are allowed, then retry.",
255            ),
256        });
257    }
258
259    // Sampling param range problems. Require a param name plus a range hint
260    // so generic "max_tokens" context-capacity messages do not match.
261    if contains_any(
262        &msg,
263        &[
264            "temperature",
265            "top_p",
266            "top_k",
267            "reasoning_effort",
268            "max_tokens",
269            "penalt",
270        ],
271    ) && contains_any(&msg, &["range", "out of range", "invalid", "must be", "validation"])
272    {
273        return Some(ConfigGuidance {
274            kind: MisconfigurationKind::SamplingParams,
275            setting: "sampling params",
276            location: "vtcode.toml custom_providers / profile",
277            fix: Cow::Borrowed(
278                "Invalid sampling param. Check temperature/top_p/top_k/penalties/max_tokens/reasoning_effort ranges in the provider profile, then retry.",
279            ),
280        });
281    }
282
283    // Generic credential-adjacent markers that did not classify as
284    // Authentication (e.g. ExecutionError wrappers around 401 text).
285    if contains_any(
286        &msg,
287        &[
288            "invalid api key",
289            "invalid_api_key",
290            "authentication failed",
291            "authentication_failed",
292            "unauthorized",
293            "invalid credentials",
294            "key was rejected",
295            "re-authenticate",
296            "/secret add",
297            "/login ",
298        ],
299    ) {
300        return Some(auth_guidance());
301    }
302
303    None
304}
305
306/// Detect configuration failures from an error that may still retain its
307/// typed provider cause. Provider metadata often contains the actionable model
308/// or credential code even when the `Display` message is only a generic HTTP
309/// failure.
310#[must_use]
311pub fn detect_misconfiguration_in_anyhow(error: &anyhow::Error) -> Option<ConfigGuidance> {
312    let message = format!("{error:#}");
313    detect_misconfiguration(crate::error_category::classify_anyhow_error(error), &message).or_else(|| {
314        error
315            .downcast_ref::<crate::llm::LLMError>()
316            .and_then(detect_misconfiguration_in_llm_error)
317    })
318}
319
320/// Detect configuration failures using both the primary LLM error message and
321/// provider metadata such as `model_not_found` or `invalid_api_key`.
322#[must_use]
323pub fn detect_misconfiguration_in_llm_error(error: &crate::llm::LLMError) -> Option<ConfigGuidance> {
324    let mut message = error.to_string();
325    if let Some(metadata) = error.metadata() {
326        if let Some(code) = metadata.code.as_deref() {
327            message.push(' ');
328            message.push_str(code);
329        }
330        if let Some(provider_message) = metadata.message.as_deref() {
331            message.push(' ');
332            message.push_str(provider_message);
333        }
334    }
335
336    detect_misconfiguration(ErrorCategory::from(error), &message)
337}
338
339/// Single source for authentication guidance (used by both the typed
340/// `Authentication` branch and generic credential-text fallback).
341fn auth_guidance() -> ConfigGuidance {
342    ConfigGuidance {
343        kind: MisconfigurationKind::Authentication,
344        setting: "API key / credentials",
345        location: "secure storage (`vtcode secret` or `/secret`) or environment",
346        fix: Cow::Borrowed(
347            "Authentication failed. Run `vtcode secret add <provider>` (or `/secret add <provider>` in TUI) for API-key providers or `vtcode login <provider>` (or `/login <provider>` in TUI) for managed auth, verify the env var is exported, then retry.",
348        ),
349    }
350}
351
352/// Convenience predicate for fail-fast checks.
353#[inline]
354#[must_use]
355pub fn is_misconfiguration(category: ErrorCategory, message: &str) -> bool {
356    detect_misconfiguration(category, message).is_some()
357}
358
359#[inline]
360fn contains_any(message: &str, markers: &[&str]) -> bool {
361    markers.iter().any(|marker| message.contains(marker))
362}
363
364#[cfg(test)]
365mod tests {
366    use super::*;
367
368    #[test]
369    fn auth_category_is_always_misconfiguration() {
370        let guidance = detect_misconfiguration(ErrorCategory::Authentication, "anything").expect("auth must match");
371        assert_eq!(guidance.kind, MisconfigurationKind::Authentication);
372        assert!(guidance.user_message().contains("before retrying"));
373    }
374
375    #[test]
376    fn transient_without_markers_is_not_misconfiguration() {
377        assert!(detect_misconfiguration(ErrorCategory::Network, "connection reset by peer").is_none());
378        assert!(detect_misconfiguration(ErrorCategory::Timeout, "request timed out after 30s").is_none());
379        assert!(detect_misconfiguration(ErrorCategory::RateLimit, "429 too many requests").is_none());
380        assert!(detect_misconfiguration(ErrorCategory::ServiceUnavailable, "503 service unavailable").is_none());
381        assert!(
382            detect_misconfiguration(
383                ErrorCategory::Network,
384                "connection reset while requesting provider_overrides.openai.base_url",
385            )
386            .is_none()
387        );
388        assert!(detect_misconfiguration(ErrorCategory::Network, "mcp server connection reset by peer").is_none());
389    }
390
391    #[test]
392    fn llm_mistakes_are_not_misconfiguration() {
393        // Asymmetric pair: patch/arg mistakes share InvalidParameters with
394        // real config errors but must not trigger config guidance.
395        assert!(
396            detect_misconfiguration(
397                ErrorCategory::InvalidParameters,
398                "invalid patch format: missing '*** Begin Patch' marker"
399            )
400            .is_none()
401        );
402        assert!(
403            detect_misconfiguration(
404                ErrorCategory::InvalidParameters,
405                "failed to parse arguments for read_file handler: invalid type"
406            )
407            .is_none()
408        );
409        assert!(
410            detect_misconfiguration(ErrorCategory::ResourceNotFound, "no such file or directory: /tmp/missing")
411                .is_none()
412        );
413        // Positive side of the same boundary: model markers do trigger.
414        assert!(
415            detect_misconfiguration(ErrorCategory::InvalidParameters, "unknown model 'gpt-99' in agent.model")
416                .is_some()
417        );
418    }
419
420    #[test]
421    fn model_vs_file_not_found_boundary() {
422        let model =
423            detect_misconfiguration(ErrorCategory::ResourceNotFound, "model not found: foo-bar").expect("model");
424        assert_eq!(model.kind, MisconfigurationKind::Model);
425        assert!(detect_misconfiguration(ErrorCategory::ResourceNotFound, "file not found: /tmp/x").is_none());
426
427        for message in [
428            "The 'gpt-5.4' model is not supported with this method.",
429            "The requested model does not exist",
430            "Model 'gpt-5.4' is not supported by OpenResponses provider.",
431        ] {
432            let guidance = detect_misconfiguration(ErrorCategory::InvalidParameters, message).expect("model");
433            assert_eq!(guidance.kind, MisconfigurationKind::Model);
434        }
435    }
436
437    #[test]
438    fn provider_and_config_markers() {
439        let provider = detect_misconfiguration(
440            ErrorCategory::InvalidParameters,
441            "unknown provider 'mycloud'; check agent.provider",
442        )
443        .expect("provider");
444        assert_eq!(provider.kind, MisconfigurationKind::Provider);
445
446        let config =
447            detect_misconfiguration(ErrorCategory::ExecutionError, "config invalid: vtcode.toml has unknown field")
448                .expect("config");
449        assert_eq!(config.kind, MisconfigurationKind::ConfigFile);
450        let invalid_provider = detect_misconfiguration(
451            ErrorCategory::InvalidParameters,
452            "Invalid provider_overrides configuration: provider key is empty",
453        )
454        .expect("invalid provider config");
455        assert_eq!(invalid_provider.kind, MisconfigurationKind::ConfigFile);
456    }
457
458    #[test]
459    fn base_url_and_key_env_markers() {
460        let base =
461            detect_misconfiguration(ErrorCategory::ExecutionError, "custom_providers[x]: `base_url` must not be empty")
462                .expect("base_url");
463        assert_eq!(base.kind, MisconfigurationKind::BaseUrl);
464
465        let key = detect_misconfiguration(
466            ErrorCategory::InvalidParameters,
467            "providers[openai]: invalid `api_key_env`: bad name",
468        )
469        .expect("api_key_env");
470        assert_eq!(key.kind, MisconfigurationKind::ApiKeyEnv);
471
472        let missing = detect_misconfiguration(
473            ErrorCategory::ExecutionError,
474            "API key not found for provider 'openai'. Set OPENAI_API_KEY or run /secret add openai.",
475        )
476        .expect("missing API key");
477        assert_eq!(missing.kind, MisconfigurationKind::ApiKeyEnv);
478
479        for message in [
480            "API key is required",
481            "API key environment variable must be set when auth is enabled",
482            "Missing MCP API key environment variable: MCP_TOKEN",
483        ] {
484            let guidance = detect_misconfiguration(ErrorCategory::ExecutionError, message).expect("missing API key");
485            assert_eq!(guidance.kind, MisconfigurationKind::ApiKeyEnv);
486        }
487    }
488
489    #[test]
490    fn mcp_and_sampling_boundaries() {
491        let mcp = detect_misconfiguration(
492            ErrorCategory::InvalidParameters,
493            "webmcp remote mcp url must be https when enabled",
494        )
495        .expect("mcp");
496        assert_eq!(mcp.kind, MisconfigurationKind::Mcp);
497        // Bare "mcp" without config context stays out.
498        assert!(detect_misconfiguration(ErrorCategory::ExecutionError, "mcp tool finished").is_none());
499
500        let sampling =
501            detect_misconfiguration(ErrorCategory::InvalidParameters, "temperature out of range: must be 0..2")
502                .expect("sampling");
503        assert_eq!(sampling.kind, MisconfigurationKind::SamplingParams);
504        let max_tokens =
505            detect_misconfiguration(ErrorCategory::InvalidParameters, "max_tokens must be greater than zero")
506                .expect("max_tokens sampling");
507        assert_eq!(max_tokens.kind, MisconfigurationKind::SamplingParams);
508        // Context-capacity max_tokens prose must not match sampling.
509        assert!(
510            detect_misconfiguration(
511                ErrorCategory::ExecutionError,
512                "input token count exceeds the maximum number of tokens"
513            )
514            .is_none()
515        );
516    }
517
518    #[test]
519    fn auth_text_inside_generic_error_is_misconfiguration() {
520        let guidance = detect_misconfiguration(ErrorCategory::ExecutionError, "provider error: 401 unauthorized")
521            .expect("auth text");
522        assert_eq!(guidance.kind, MisconfigurationKind::Authentication);
523    }
524
525    #[test]
526    fn typed_llm_metadata_overrides_generic_provider_text() {
527        let error = anyhow::Error::new(crate::llm::LLMError::Provider {
528            message: "HTTP 503 Service Unavailable".to_string(),
529            metadata: Some(crate::llm::LLMErrorMetadata::new(
530                "openai",
531                Some(404),
532                Some("model_not_found".to_string()),
533                None,
534                None,
535                None,
536                Some("The requested model does not exist".to_string()),
537            )),
538        });
539
540        let guidance = detect_misconfiguration_in_anyhow(&error).expect("metadata model marker");
541        assert_eq!(guidance.kind, MisconfigurationKind::Model);
542    }
543
544    #[test]
545    fn guidance_never_echoes_secrets() {
546        let secret = concat!("sk-", "test1234567890abcdef");
547        let message = format!("Authentication failed: invalid api key {secret}");
548        let guidance = detect_misconfiguration(ErrorCategory::ExecutionError, &message).expect("auth text must match");
549        let rendered = guidance.user_message();
550        assert!(rendered.contains("before retrying"));
551        assert!(!rendered.contains(secret), "guidance must be static and never echo input secrets");
552    }
553
554    #[test]
555    fn misconfiguration_check_is_fail_closed() {
556        // Even with generous retry budgets, misconfiguration must not retry.
557        // This is the fail-closed property: fix config first, never blind-retry.
558        for category in [ErrorCategory::Authentication, ErrorCategory::InvalidParameters] {
559            let guidance = detect_misconfiguration(category, "unknown model 'x' in agent.model");
560            if category == ErrorCategory::Authentication {
561                assert!(guidance.is_some());
562            }
563        }
564        assert!(!ErrorCategory::Authentication.is_retryable());
565    }
566}