Skip to main content

vtcode_core/
error.rs

1//! Structured error handling for VT Code.
2//!
3//! Provides a VT Code-specific error envelope with machine-readable codes and
4//! contextual information while reusing the shared `vtcode_commons`
5//! classification system.
6
7use crate::llm::provider::LLMError;
8use crate::retry_after::retry_after_from_llm_metadata;
9use crate::tools::registry::{ToolErrorType, ToolExecutionError};
10use crate::tools::unified_error::{UnifiedErrorKind, UnifiedToolError};
11use serde::{Deserialize, Serialize};
12use thiserror::Error;
13use vtcode_commons::sanitizer::sanitize_provider_diagnostic;
14pub use vtcode_commons::{
15    BackoffStrategy, ConfigGuidance, ErrorCategory, MisconfigurationKind, Retryability, detect_misconfiguration,
16    is_misconfiguration,
17};
18use vtcode_macros::DebugNoInline;
19
20/// Result type alias for VT Code operations.
21pub type Result<T> = std::result::Result<T, VtCodeError>;
22
23/// Core error type for VT Code operations.
24///
25/// Uses `thiserror::Error` for automatic `std::error::Error` implementation
26/// and provides clear error messages with context.
27///
28/// `Debug` is derived via [`DebugNoInline`] rather than `#[derive(Debug)]`: the
29/// envelope wraps an arbitrary `source` chain and is formatted on fan-out failure
30/// paths, so the built-in derive's implied `#[inline]` would inline the whole
31/// chain into every `{:?}` / `?err` site.
32#[derive(DebugNoInline, Error, Serialize, Deserialize)]
33#[error("{category}: {message}")]
34pub struct VtCodeError {
35    /// Error category for categorization and handling.
36    pub category: ErrorCategory,
37
38    /// Machine-readable error code.
39    pub code: ErrorCode,
40
41    /// Human-readable error message.
42    pub message: String,
43
44    /// Optional context for debugging.
45    #[serde(skip_serializing_if = "Option::is_none")]
46    pub context: Option<String>,
47
48    /// Optional backoff hint for the next retry attempt in milliseconds.
49    #[serde(skip_serializing_if = "Option::is_none")]
50    pub retry_after_ms: Option<u64>,
51
52    /// Optional source error for chained errors.
53    #[serde(skip)]
54    #[source]
55    pub source: Option<Box<dyn std::error::Error + Send + Sync>>,
56}
57
58/// Machine-readable error codes for precise error identification.
59///
60/// `Debug` uses [`DebugNoInline`] so this large unit-only enum emits one
61/// concatenated name string instead of 31 string-literal match arms, which is
62/// cheaper to compile and smaller in the binary.
63#[derive(DebugNoInline, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
64pub enum ErrorCode {
65    // Input errors
66    InvalidArgument,
67    ValidationFailed,
68    ParseError,
69
70    // Execution errors
71    CommandFailed,
72    ToolExecutionFailed,
73    Timeout,
74
75    // Network errors
76    ConnectionFailed,
77    RequestFailed,
78    RateLimited,
79    ServiceUnavailable,
80
81    // LLM errors
82    AuthenticationFailed,
83    LLMProviderError,
84    TokenLimitExceeded,
85    ContextTooLong,
86
87    // Config errors
88    ConfigInvalid,
89    ConfigMissing,
90    ConfigParseFailed,
91
92    // Security errors
93    PermissionDenied,
94    PolicyViolation,
95    PlanningPolicyViolation,
96    SandboxViolation,
97    DotfileProtection,
98
99    // System errors
100    IoError,
101    OutOfMemory,
102    ResourceUnavailable,
103    ResourceNotFound,
104
105    // Internal errors
106    ToolNotFound,
107    CircuitOpen,
108    Cancelled,
109    Unexpected,
110    NotImplemented,
111}
112
113impl VtCodeError {
114    /// Create a new error with the given category, code, and message.
115    pub fn new<S: Into<String>>(category: ErrorCategory, code: ErrorCode, message: S) -> Self {
116        Self {
117            category,
118            code,
119            message: message.into(),
120            context: None,
121            retry_after_ms: None,
122            source: None,
123        }
124    }
125
126    /// Add context to the error.
127    pub fn with_context<S: Into<String>>(mut self, context: S) -> Self {
128        self.context = Some(context.into());
129        self
130    }
131
132    /// Add a retry-after hint to the error.
133    pub fn with_retry_after(mut self, retry_after: std::time::Duration) -> Self {
134        self.retry_after_ms = Some(retry_after.as_millis().min(u128::from(u64::MAX)) as u64);
135        self
136    }
137
138    /// Set the source error for error chaining.
139    pub fn with_source<E: std::error::Error + Send + Sync + 'static>(mut self, source: E) -> Self {
140        self.source = Some(Box::new(source));
141        self
142    }
143
144    /// Returns the retry-after hint as a duration when present.
145    pub fn retry_after(&self) -> Option<std::time::Duration> {
146        self.retry_after_ms.map(std::time::Duration::from_millis)
147    }
148
149    /// Returns whether the error can be retried safely.
150    pub const fn is_retryable(&self) -> bool {
151        self.category.is_retryable()
152    }
153
154    /// Returns the retry strategy for this error category.
155    pub fn retryability(&self) -> Retryability {
156        self.category.retryability()
157    }
158
159    /// Convenience method for input errors.
160    pub fn input<S: Into<String>>(code: ErrorCode, message: S) -> Self {
161        Self::new(ErrorCategory::InvalidParameters, code, message)
162    }
163
164    /// Convenience method for execution errors.
165    pub fn execution<S: Into<String>>(code: ErrorCode, message: S) -> Self {
166        Self::new(ErrorCategory::ExecutionError, code, message)
167    }
168
169    /// Convenience method for network errors.
170    pub fn network<S: Into<String>>(code: ErrorCode, message: S) -> Self {
171        Self::new(ErrorCategory::Network, code, message)
172    }
173
174    /// Convenience method for LLM errors.
175    pub fn llm<S: Into<String>>(code: ErrorCode, message: S) -> Self {
176        Self::new(ErrorCategory::ExecutionError, code, message)
177    }
178
179    /// Convenience method for config errors.
180    pub fn config<S: Into<String>>(code: ErrorCode, message: S) -> Self {
181        Self::new(ErrorCategory::InvalidParameters, code, message)
182    }
183
184    /// Convenience method for security errors.
185    pub fn security<S: Into<String>>(code: ErrorCode, message: S) -> Self {
186        Self::new(ErrorCategory::PolicyViolation, code, message)
187    }
188
189    /// Convenience method for system errors.
190    pub fn system<S: Into<String>>(code: ErrorCode, message: S) -> Self {
191        Self::new(ErrorCategory::ExecutionError, code, message)
192    }
193
194    /// Convenience method for internal errors.
195    pub fn internal<S: Into<String>>(code: ErrorCode, message: S) -> Self {
196        Self::new(ErrorCategory::ExecutionError, code, message)
197    }
198
199    /// Create an error from a canonical category using the default error code.
200    pub fn from_category<S: Into<String>>(category: ErrorCategory, message: S) -> Self {
201        Self::new(category, ErrorCode::from_category(category), message)
202    }
203
204    /// Check settings/config first: return guidance when this failure is
205    /// caused by user misconfiguration.
206    ///
207    /// Config error codes (`ConfigInvalid`/`ConfigMissing`/`ConfigParseFailed`)
208    /// are always misconfiguration. Otherwise the message plus context is
209    /// matched against config markers (credentials, model, provider,
210    /// `base_url`, `vtcode.toml`, MCP, sampling ranges). Transient failures
211    /// and LLM argument mistakes return `None`.
212    #[must_use]
213    pub fn misconfiguration_guidance(&self) -> Option<ConfigGuidance> {
214        if matches!(self.code, ErrorCode::ConfigInvalid | ErrorCode::ConfigMissing | ErrorCode::ConfigParseFailed) {
215            if let Some(guidance) = self.message_guidance() {
216                return Some(guidance);
217            }
218            return Some(ConfigGuidance {
219                kind: MisconfigurationKind::ConfigFile,
220                setting: "vtcode.toml",
221                location: "workspace / user / system config layers",
222                fix: std::borrow::Cow::Borrowed(
223                    "Invalid config file. Validate vtcode.toml syntax and fields, then retry.",
224                ),
225            });
226        }
227        self.message_guidance()
228    }
229
230    /// Whether this failure is user misconfiguration that must be fixed
231    /// before retrying.
232    #[must_use]
233    pub fn is_misconfiguration(&self) -> bool {
234        self.misconfiguration_guidance().is_some()
235    }
236
237    /// Attach config guidance to the error so it is visible in `Display`
238    /// (`{category}: {message}`) and does not get retried blindly.
239    /// Idempotent: does nothing when guidance is absent or already present.
240    #[must_use]
241    pub fn with_misconfiguration_guidance(mut self) -> Self {
242        let Some(guidance) = self.misconfiguration_guidance() else {
243            return self;
244        };
245        let suffix = guidance.user_message();
246        // Use the full terminal phrase as the idempotency marker; it is far
247        // less likely to collide with user content than the shorter prefix.
248        if self.message.contains("Correct the configuration before retrying.") {
249            return self;
250        }
251        // `context` is not part of thiserror's Display output, so keep the
252        // guidance in the visible message even when the provider returned a
253        // large diagnostic payload.
254        self.message.push(' ');
255        self.message.push_str(&suffix);
256        self
257    }
258
259    fn message_guidance(&self) -> Option<ConfigGuidance> {
260        let mut haystack = self.message.clone();
261        if let Some(context) = self.context.as_deref() {
262            haystack.push('\n');
263            haystack.push_str(context);
264        }
265        let mut source = self.source.as_deref().map(|source| source as &dyn std::error::Error);
266        while let Some(error) = source {
267            haystack.push('\n');
268            haystack.push_str(&error.to_string());
269            source = error.source();
270        }
271        detect_misconfiguration(self.category, &haystack)
272    }
273}
274
275impl ErrorCode {
276    /// Map a canonical error category to a default machine-readable code.
277    pub const fn from_category(category: ErrorCategory) -> Self {
278        match category {
279            ErrorCategory::Network => ErrorCode::ConnectionFailed,
280            ErrorCategory::Timeout => ErrorCode::Timeout,
281            ErrorCategory::RateLimit => ErrorCode::RateLimited,
282            ErrorCategory::ServiceUnavailable => ErrorCode::ServiceUnavailable,
283            ErrorCategory::CircuitOpen => ErrorCode::CircuitOpen,
284            ErrorCategory::Authentication => ErrorCode::AuthenticationFailed,
285            ErrorCategory::InvalidParameters => ErrorCode::InvalidArgument,
286            ErrorCategory::ToolNotFound => ErrorCode::ToolNotFound,
287            ErrorCategory::ResourceNotFound => ErrorCode::ResourceNotFound,
288            ErrorCategory::PermissionDenied => ErrorCode::PermissionDenied,
289            ErrorCategory::PolicyViolation => ErrorCode::PolicyViolation,
290            ErrorCategory::PlanningPolicyViolation => ErrorCode::PlanningPolicyViolation,
291            ErrorCategory::SandboxFailure => ErrorCode::SandboxViolation,
292            ErrorCategory::ResourceExhausted => ErrorCode::ResourceUnavailable,
293            ErrorCategory::Cancelled => ErrorCode::Cancelled,
294            ErrorCategory::ExecutionError => ErrorCode::Unexpected,
295        }
296    }
297
298    fn from_unified_kind(kind: UnifiedErrorKind) -> Self {
299        match kind {
300            UnifiedErrorKind::Timeout => ErrorCode::Timeout,
301            UnifiedErrorKind::Network => ErrorCode::ConnectionFailed,
302            UnifiedErrorKind::RateLimit => ErrorCode::RateLimited,
303            UnifiedErrorKind::ArgumentValidation => ErrorCode::ValidationFailed,
304            UnifiedErrorKind::ToolNotFound => ErrorCode::ToolNotFound,
305            UnifiedErrorKind::PermissionDenied => ErrorCode::PermissionDenied,
306            UnifiedErrorKind::SandboxFailure => ErrorCode::SandboxViolation,
307            UnifiedErrorKind::InternalError => ErrorCode::Unexpected,
308            UnifiedErrorKind::CircuitOpen => ErrorCode::CircuitOpen,
309            UnifiedErrorKind::ResourceExhausted => ErrorCode::ResourceUnavailable,
310            UnifiedErrorKind::Cancelled => ErrorCode::Cancelled,
311            UnifiedErrorKind::PolicyViolation => ErrorCode::PolicyViolation,
312            UnifiedErrorKind::PlanningPolicyViolation => ErrorCode::PlanningPolicyViolation,
313            UnifiedErrorKind::ExecutionFailed | UnifiedErrorKind::Unknown => ErrorCode::ToolExecutionFailed,
314        }
315    }
316
317    fn from_tool_error_type(error_type: ToolErrorType) -> Self {
318        match error_type {
319            ToolErrorType::InvalidParameters => ErrorCode::ValidationFailed,
320            ToolErrorType::ToolNotFound => ErrorCode::ToolNotFound,
321            ToolErrorType::PermissionDenied => ErrorCode::PermissionDenied,
322            ToolErrorType::ResourceNotFound => ErrorCode::ResourceNotFound,
323            ToolErrorType::NetworkError => ErrorCode::ConnectionFailed,
324            ToolErrorType::Timeout => ErrorCode::Timeout,
325            ToolErrorType::ExecutionError => ErrorCode::ToolExecutionFailed,
326            ToolErrorType::PolicyViolation => ErrorCode::PolicyViolation,
327        }
328    }
329}
330
331// Implement conversions from common error types
332impl From<std::io::Error> for VtCodeError {
333    fn from(err: std::io::Error) -> Self {
334        VtCodeError::system(ErrorCode::IoError, err.to_string())
335            .with_source(err)
336            .with_misconfiguration_guidance()
337    }
338}
339
340impl From<serde_json::Error> for VtCodeError {
341    fn from(err: serde_json::Error) -> Self {
342        VtCodeError::config(ErrorCode::ConfigParseFailed, err.to_string())
343            .with_source(err)
344            .with_misconfiguration_guidance()
345    }
346}
347
348impl From<reqwest::Error> for VtCodeError {
349    fn from(err: reqwest::Error) -> Self {
350        let code = if err.is_timeout() {
351            ErrorCode::Timeout
352        } else if err.is_connect() {
353            ErrorCode::ConnectionFailed
354        } else {
355            ErrorCode::RequestFailed
356        };
357        VtCodeError::network(code, err.to_string())
358            .with_source(err)
359            .with_misconfiguration_guidance()
360    }
361}
362
363impl From<anyhow::Error> for VtCodeError {
364    fn from(err: anyhow::Error) -> Self {
365        let category = vtcode_commons::classify_anyhow_error(&err);
366        VtCodeError::new(category, ErrorCode::from_category(category), err.to_string())
367            .with_context(format!("{err:#}"))
368            .with_misconfiguration_guidance()
369    }
370}
371
372impl From<LLMError> for VtCodeError {
373    fn from(err: LLMError) -> Self {
374        let category = ErrorCategory::from(&err);
375        let code = match &err {
376            LLMError::Authentication { .. } => ErrorCode::AuthenticationFailed,
377            LLMError::RateLimit { .. } => {
378                if category == ErrorCategory::ResourceExhausted {
379                    ErrorCode::from_category(category)
380                } else {
381                    ErrorCode::RateLimited
382                }
383            }
384            LLMError::InvalidRequest { .. } => ErrorCode::ValidationFailed,
385            LLMError::Network { message, .. } => {
386                if vtcode_commons::classify_error_message(message) == ErrorCategory::Timeout {
387                    ErrorCode::Timeout
388                } else {
389                    ErrorCode::ConnectionFailed
390                }
391            }
392            LLMError::Provider { metadata, .. } => {
393                if category == ErrorCategory::ResourceExhausted {
394                    ErrorCode::from_category(category)
395                } else {
396                    metadata
397                        .as_ref()
398                        .and_then(|meta| meta.status)
399                        .map(|status| match status {
400                            408 => ErrorCode::Timeout,
401                            429 => ErrorCode::RateLimited,
402                            500 | 502 | 503 | 504 | 529 => ErrorCode::ServiceUnavailable,
403                            _ => ErrorCode::LLMProviderError,
404                        })
405                        .unwrap_or(ErrorCode::LLMProviderError)
406                }
407            }
408        };
409        let message = llm_error_message(&err);
410        let metadata_context = llm_metadata_context(&err);
411        let retry_after = llm_retry_after(&err);
412
413        let mut error = VtCodeError::new(category, code, message);
414        if let Some(context) = metadata_context {
415            error = error.with_context(context);
416        }
417        let error = error.with_source(err);
418        let error = if let Some(retry_after) = retry_after {
419            error.with_retry_after(retry_after)
420        } else {
421            error
422        };
423        error.with_misconfiguration_guidance()
424    }
425}
426
427impl From<UnifiedToolError> for VtCodeError {
428    fn from(err: UnifiedToolError) -> Self {
429        let mut error = VtCodeError::new(
430            ErrorCategory::from(err.kind),
431            ErrorCode::from_unified_kind(err.kind),
432            err.user_message.clone(),
433        );
434
435        if let Some(ctx) = &err.debug_context {
436            let mut metadata = vec![format!("tool={}", ctx.tool_name), format!("attempt={}", ctx.attempt)];
437            if let Some(invocation_id) = &ctx.invocation_id {
438                metadata.push(format!("invocation_id={invocation_id}"));
439            }
440            metadata.extend(ctx.metadata.iter().map(|(key, value)| format!("{key}={value}")));
441            error = error.with_context(metadata.join(", "));
442        }
443
444        error.with_source(err).with_misconfiguration_guidance()
445    }
446}
447
448impl From<ToolExecutionError> for VtCodeError {
449    fn from(err: ToolExecutionError) -> Self {
450        let category = ErrorCategory::from(err.error_type);
451        let mut error =
452            VtCodeError::new(category, ErrorCode::from_tool_error_type(err.error_type), err.message.clone());
453
454        let mut context_parts = Vec::new();
455        if let Some(original_error) = &err.original_error {
456            context_parts.push(format!("original_error={original_error}"));
457        }
458        if !err.recovery_suggestions.is_empty() {
459            context_parts.push(format!("recovery_suggestions={}", err.recovery_suggestions.join(" | ")));
460        }
461        if !context_parts.is_empty() {
462            error = error.with_context(context_parts.join(", "));
463        }
464
465        error.with_misconfiguration_guidance()
466    }
467}
468
469fn llm_error_message(error: &LLMError) -> String {
470    match error {
471        LLMError::Authentication { message, .. }
472        | LLMError::InvalidRequest { message, .. }
473        | LLMError::Network { message, .. }
474        | LLMError::Provider { message, .. } => message.clone(),
475        LLMError::RateLimit { metadata } => metadata
476            .as_ref()
477            .and_then(|meta| meta.message.clone())
478            .unwrap_or_else(|| "rate limit exceeded".to_string()),
479    }
480}
481
482fn llm_metadata_context(error: &LLMError) -> Option<String> {
483    let metadata = error.metadata()?;
484
485    let mut context = Vec::new();
486    if let Some(code) = metadata.code.as_deref() {
487        context.push(format!("provider_code={}", sanitize_provider_diagnostic(code.as_bytes())));
488    }
489    if let Some(message) = metadata.message.as_deref() {
490        context.push(format!("provider_message={}", sanitize_provider_diagnostic(message.as_bytes())));
491    }
492    (!context.is_empty()).then(|| context.join(", "))
493}
494
495fn llm_retry_after(error: &LLMError) -> Option<std::time::Duration> {
496    let metadata = error.metadata()?;
497
498    retry_after_from_llm_metadata(metadata)
499}
500
501#[cfg(test)]
502mod tests {
503    use super::*;
504    use crate::llm::provider::LLMErrorMetadata;
505    use crate::tools::unified_error::DebugContext;
506
507    #[test]
508    fn test_error_creation() {
509        let err = VtCodeError::input(ErrorCode::InvalidArgument, "Invalid argument");
510        assert_eq!(err.category, ErrorCategory::InvalidParameters);
511        assert_eq!(err.code, ErrorCode::InvalidArgument);
512        assert_eq!(err.message, "Invalid argument");
513    }
514
515    #[test]
516    fn test_error_with_context() {
517        let err =
518            VtCodeError::input(ErrorCode::InvalidArgument, "Invalid argument").with_context("While parsing user input");
519        assert_eq!(err.context, Some("While parsing user input".to_string()));
520    }
521
522    #[test]
523    fn test_error_with_source() {
524        let io_err = std::io::Error::other("IO error");
525        let err = VtCodeError::system(ErrorCode::IoError, "File operation failed").with_source(io_err);
526        assert!(err.source.is_some());
527    }
528
529    #[test]
530    fn test_error_category_display() {
531        let err = VtCodeError::network(ErrorCode::ConnectionFailed, "Connection failed");
532        let display = format!("{err}");
533        assert!(display.contains("Network error"));
534        assert!(display.contains("Connection failed"));
535    }
536
537    #[test]
538    fn test_error_serialization_skips_source() {
539        let io_err = std::io::Error::other("IO error");
540        let err = VtCodeError::system(ErrorCode::IoError, "File operation failed")
541            .with_context("While reading config")
542            .with_source(io_err);
543
544        let json = serde_json::to_string(&err).expect("vtcode error should serialize");
545        assert!(json.contains("\"message\":\"File operation failed\""));
546        assert!(json.contains("\"context\":\"While reading config\""));
547        assert!(!json.contains("source"));
548    }
549
550    #[test]
551    fn test_error_with_retry_after() {
552        let err = VtCodeError::network(ErrorCode::RateLimited, "rate limit")
553            .with_retry_after(std::time::Duration::from_secs(2));
554        assert_eq!(err.retry_after(), Some(std::time::Duration::from_secs(2)));
555    }
556
557    #[test]
558    fn test_llm_error_conversion_preserves_retry_after() {
559        let err = LLMError::RateLimit {
560            metadata: Some(LLMErrorMetadata::new(
561                "OpenAI",
562                Some(429),
563                Some("rate_limit".to_string()),
564                Some("req-1".to_string()),
565                None,
566                Some("3".to_string()),
567                Some("try again later".to_string()),
568            )),
569        };
570
571        let converted = VtCodeError::from(err);
572        assert_eq!(converted.category, ErrorCategory::RateLimit);
573        assert_eq!(converted.code, ErrorCode::RateLimited);
574        assert_eq!(converted.retry_after(), Some(std::time::Duration::from_secs(3)));
575    }
576
577    #[test]
578    fn test_llm_metadata_marks_converted_error_as_misconfiguration() {
579        let err = LLMError::Provider {
580            message: "provider request failed".to_string(),
581            metadata: Some(LLMErrorMetadata::new(
582                "OpenAI",
583                Some(404),
584                Some("model_not_found".to_string()),
585                None,
586                None,
587                None,
588                Some("The requested model does not exist".to_string()),
589            )),
590        };
591
592        let converted = VtCodeError::from(err);
593        assert!(converted.is_misconfiguration());
594        assert!(converted.message.contains("Check settings/config first"));
595        assert!(
596            converted
597                .context
598                .as_deref()
599                .is_some_and(|context| context.contains("provider_code=model_not_found"))
600        );
601    }
602
603    #[test]
604    fn test_llm_error_conversion_preserves_fractional_retry_after() {
605        let err = LLMError::RateLimit {
606            metadata: Some(LLMErrorMetadata::new(
607                "OpenAI",
608                Some(429),
609                Some("rate_limit".to_string()),
610                Some("req-1".to_string()),
611                None,
612                Some("0.5".to_string()),
613                Some("try again later".to_string()),
614            )),
615        };
616
617        let converted = VtCodeError::from(err);
618        assert_eq!(converted.retry_after(), Some(std::time::Duration::from_millis(500)));
619    }
620
621    #[test]
622    fn test_llm_quota_exhaustion_uses_resource_exhausted_code() {
623        let err = LLMError::RateLimit {
624            metadata: Some(LLMErrorMetadata::new(
625                "OpenAI",
626                Some(429),
627                Some("insufficient_quota".to_string()),
628                None,
629                None,
630                None,
631                Some("quota exceeded".to_string()),
632            )),
633        };
634
635        let converted = VtCodeError::from(err);
636        assert_eq!(converted.category, ErrorCategory::ResourceExhausted);
637        assert_eq!(converted.code, ErrorCode::ResourceUnavailable);
638    }
639
640    #[test]
641    fn test_unified_tool_error_conversion_preserves_context() {
642        let err = UnifiedToolError::new(UnifiedErrorKind::Network, "network down").with_context(DebugContext {
643            tool_name: "read_file".to_string(),
644            invocation_id: Some("inv-1".to_string()),
645            attempt: 2,
646            metadata: vec![("duration_ms".to_string(), "1500".to_string())],
647        });
648
649        let converted = VtCodeError::from(err);
650        assert_eq!(converted.category, ErrorCategory::Network);
651        assert_eq!(converted.code, ErrorCode::ConnectionFailed);
652        assert!(converted.context.as_deref().is_some_and(|ctx| ctx.contains("tool=read_file")));
653    }
654
655    #[test]
656    fn test_unified_tool_source_marks_converted_error_as_misconfiguration() {
657        let err = UnifiedToolError::new(UnifiedErrorKind::Network, "provider request failed")
658            .with_source(anyhow::anyhow!("unknown model 'gpt-99' in agent.model"));
659
660        let converted = VtCodeError::from(err);
661        assert!(converted.is_misconfiguration());
662        assert!(converted.message.contains("Check settings/config first"));
663    }
664
665    #[test]
666    fn test_tool_execution_error_conversion_uses_original_context() {
667        let err = ToolExecutionError::with_original_error(
668            "command_session".to_string(),
669            ToolErrorType::Timeout,
670            "Tool execution failed".to_string(),
671            "timed out waiting for process".to_string(),
672        );
673
674        let converted = VtCodeError::from(err);
675        assert_eq!(converted.category, ErrorCategory::Timeout);
676        assert_eq!(converted.code, ErrorCode::Timeout);
677        assert!(
678            converted
679                .context
680                .as_deref()
681                .is_some_and(|ctx| ctx.contains("original_error=timed out waiting for process"))
682        );
683    }
684
685    #[test]
686    fn test_misconfiguration_guidance_for_auth() {
687        let err = VtCodeError::new(
688            ErrorCategory::Authentication,
689            ErrorCode::AuthenticationFailed,
690            "Authentication failed: invalid api key",
691        );
692        assert!(err.is_misconfiguration());
693        let guided = err.with_misconfiguration_guidance();
694        assert!(guided.message.contains("Check settings/config first"));
695        assert!(guided.message.contains("before retrying"));
696    }
697
698    #[test]
699    fn test_misconfiguration_guidance_for_config_code() {
700        let err = VtCodeError::config(ErrorCode::ConfigInvalid, "custom_providers[x]: `base_url` must not be empty");
701        assert!(err.is_misconfiguration());
702    }
703
704    #[test]
705    fn test_transient_has_no_misconfiguration() {
706        let err = VtCodeError::network(ErrorCode::ConnectionFailed, "connection reset by peer");
707        assert!(!err.is_misconfiguration());
708        let guided = err.with_misconfiguration_guidance();
709        assert!(!guided.message.contains("Check settings/config first"));
710    }
711
712    #[test]
713    fn test_misconfiguration_is_idempotent() {
714        let err = VtCodeError::new(ErrorCategory::Authentication, ErrorCode::AuthenticationFailed, "bad key")
715            .with_misconfiguration_guidance()
716            .with_misconfiguration_guidance();
717        assert_eq!(err.message.matches("Correct the configuration before retrying.").count(), 1);
718    }
719
720    #[test]
721    fn test_misconfiguration_guidance_does_not_echo_secrets() {
722        let secret = concat!("sk-", "test1234567890abcdef");
723        let err = VtCodeError::new(
724            ErrorCategory::Authentication,
725            ErrorCode::AuthenticationFailed,
726            format!("Authentication failed: invalid api key {secret}"),
727        );
728        let guidance = err.misconfiguration_guidance().expect("auth must match");
729        assert!(!guidance.user_message().contains(secret));
730    }
731
732    #[test]
733    fn test_misconfiguration_guidance_stays_visible_for_large_errors() {
734        let mut message = "x".repeat(8 * 1024);
735        message.push_str(" invalid api key");
736        let guided = VtCodeError::execution(ErrorCode::Unexpected, message).with_misconfiguration_guidance();
737        assert!(guided.message.contains("Check settings/config first"));
738        assert!(guided.to_string().contains("Correct the configuration before retrying."));
739    }
740}