Skip to main content

vtcode_core/tools/registry/
error.rs

1use anyhow::Error;
2use serde::{Deserialize, Serialize};
3use serde_json::{Value, json};
4use std::borrow::Cow;
5use vtcode_commons::ErrorCategory;
6
7use crate::retry::{RetryDecision, RetryPolicy, RetryPolicyCoreExt};
8use crate::tools::tool_intent::is_command_tool;
9
10const EXEC_SESSION_NOT_FOUND_CODE: &str = "exec_session_not_found";
11
12#[derive(Debug, Clone, Serialize, Deserialize, Default)]
13pub struct ToolErrorDebugContext {
14    pub surface: Option<String>,
15    pub attempt: Option<u32>,
16    pub invocation_id: Option<String>,
17    pub metadata: Vec<(String, String)>,
18}
19
20/// Typed patch diagnostics, independent of words quoted from source files.
21#[derive(Debug, Clone, Serialize, Deserialize)]
22pub enum PatchFailure {
23    ContextMismatch { path: String, evidence: String },
24    RedactedContext { path: String },
25    Other,
26}
27
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
29#[serde(rename_all = "snake_case")]
30pub enum EditFailureKind {
31    NoMatch,
32    AmbiguousMatch,
33}
34
35#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
36pub struct EditLocation {
37    pub start_line: usize,
38    pub end_line: usize,
39}
40
41/// Bounded literal-edit diagnostics; candidate locations come only from matches.
42#[derive(Debug, Clone, Serialize, Deserialize, thiserror::Error)]
43#[error(
44    "Literal edit {failure_kind:?} in '{path}'; refresh current source and correct the edit. Use anchored apply_patch to disambiguate. Never retry unchanged failed input."
45)]
46pub struct EditFailure {
47    pub failure_kind: EditFailureKind,
48    pub path: String,
49    pub candidate_locations: Vec<EditLocation>,
50    #[serde(default, skip_serializing_if = "Option::is_none")]
51    pub next_read_args: Option<Box<Value>>,
52    #[serde(default, skip_serializing_if = "Option::is_none")]
53    pub next_search_args: Option<Box<Value>>,
54}
55
56impl EditFailure {
57    pub(crate) fn new(kind: EditFailureKind, path: &std::path::Path, locations: Vec<EditLocation>, old: &str) -> Self {
58        let next_read_args = locations.first().map(|location| {
59            let start = location.start_line.saturating_sub(3).max(1);
60            let limit = (location.end_line + 3 - start + 1).min(200);
61            Box::new(json!({"path":path, "offset":start, "limit":limit, "condense":false, "max_tokens":6000}))
62        });
63        let query = old
64            .lines()
65            .find(|line| !line.trim().is_empty())
66            .unwrap_or(old)
67            .trim()
68            .chars()
69            .take(120)
70            .collect::<String>();
71        let next_search_args = next_read_args
72            .is_none()
73            .then_some(query)
74            .filter(|query| !query.is_empty())
75            .map(|query| Box::new(json!({"path":path, "query":query, "max_results":5})));
76        Self {
77            failure_kind: kind,
78            path: path.to_string_lossy().into_owned(),
79            candidate_locations: locations,
80            next_read_args,
81            next_search_args,
82        }
83    }
84}
85
86#[derive(Debug, Clone, Serialize, Deserialize)]
87pub struct ToolExecutionError {
88    pub tool_name: String,
89    pub error_type: ToolErrorType,
90    pub category: ErrorCategory,
91    pub message: String,
92    pub retryable: bool,
93    pub is_recoverable: bool,
94    pub recovery_suggestions: Vec<Cow<'static, str>>,
95    pub retry_delay_ms: Option<u64>,
96    pub retry_after_ms: Option<u64>,
97    pub circuit_breaker_impact: bool,
98    pub partial_state_possible: bool,
99    pub rollback_performed: bool,
100    pub debug_context: Option<ToolErrorDebugContext>,
101    pub original_error: Option<String>,
102    #[serde(default, skip_serializing_if = "Option::is_none")]
103    pub patch_failure: Option<PatchFailure>,
104    #[serde(default, skip_serializing_if = "Option::is_none")]
105    pub inspection_failure: Option<Value>,
106    #[serde(default, skip_serializing_if = "Option::is_none")]
107    pub edit_failure: Option<EditFailure>,
108}
109
110#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
111pub enum ToolErrorType {
112    InvalidParameters,
113    ToolNotFound,
114    PermissionDenied,
115    ResourceNotFound,
116    NetworkError,
117    Timeout,
118    ExecutionError,
119    PolicyViolation,
120}
121
122impl ToolErrorType {
123    /// Return the error type as a static string for serialization.
124    #[must_use]
125    pub const fn as_str(&self) -> &'static str {
126        match self {
127            Self::InvalidParameters => "InvalidParameters",
128            Self::ToolNotFound => "ToolNotFound",
129            Self::PermissionDenied => "PermissionDenied",
130            Self::ResourceNotFound => "ResourceNotFound",
131            Self::NetworkError => "NetworkError",
132            Self::Timeout => "Timeout",
133            Self::ExecutionError => "ExecutionError",
134            Self::PolicyViolation => "PolicyViolation",
135        }
136    }
137}
138
139impl ToolExecutionError {
140    #[inline]
141    #[must_use]
142    pub fn new(tool_name: impl Into<String>, error_type: ToolErrorType, message: impl Into<String>) -> Self {
143        Self::from_parts(tool_name.into(), ErrorCategory::from(error_type), error_type, message.into())
144    }
145
146    /// Construct from a full-fidelity `ErrorCategory`, deriving the lossy
147    /// `error_type` view from it. Prefer this over [`Self::new`] when the
148    /// category came from `vtcode_commons::classify_anyhow_error` /
149    /// `classify_error_message`, so distinctions such as `RateLimit` vs
150    /// `Network` are preserved on the struct.
151    #[must_use]
152    fn from_category(tool_name: impl Into<String>, category: ErrorCategory, message: impl Into<String>) -> Self {
153        Self::from_parts(tool_name.into(), category, ToolErrorType::from(category), message.into())
154    }
155
156    fn from_parts(tool_name: String, category: ErrorCategory, error_type: ToolErrorType, message: String) -> Self {
157        let (retryable, is_recoverable, recovery_suggestions) =
158            generate_recovery_info(tool_name.as_str(), category, error_type);
159
160        Self {
161            tool_name,
162            error_type,
163            category,
164            message,
165            retryable,
166            is_recoverable,
167            recovery_suggestions,
168            retry_delay_ms: None,
169            retry_after_ms: None,
170            circuit_breaker_impact: category.should_trip_circuit_breaker(),
171            partial_state_possible: false,
172            rollback_performed: false,
173            debug_context: None,
174            original_error: None,
175            patch_failure: None,
176            inspection_failure: None,
177            edit_failure: None,
178        }
179    }
180
181    #[inline]
182    #[must_use]
183    pub fn with_original_error(
184        tool_name: impl Into<String>,
185        error_type: ToolErrorType,
186        message: impl Into<String>,
187        original_error: impl Into<String>,
188    ) -> Self {
189        let mut error = Self::new(tool_name, error_type, message);
190        error.original_error = Some(original_error.into());
191        error
192    }
193
194    #[must_use]
195    pub fn from_anyhow(
196        tool_name: impl Into<String>,
197        error: &Error,
198        attempt_index: u32,
199        partial_state_possible: bool,
200        rollback_performed: bool,
201        surface: Option<&str>,
202    ) -> Self {
203        let tool_name = tool_name.into();
204        if let Some(edit) = error.downcast_ref::<EditFailure>() {
205            let mut structured = Self::new(tool_name, ToolErrorType::InvalidParameters, edit.to_string());
206            structured.edit_failure = Some(edit.clone());
207            structured.retryable = false;
208            structured.is_recoverable = true;
209            structured.circuit_breaker_impact = false;
210            structured.recovery_suggestions = vec![Cow::Borrowed(
211                "Use edit_failure.next_read_args when present; otherwise use next_search_args, then read a targeted range at the returned location. One uncached read of at most 200 lines per canonical path/user turn shares the patch recovery quota. Correct old_str or use anchored apply_patch; never retry unchanged failed input.",
212            )];
213            structured = structured.with_attempt(attempt_index);
214            if let Some(surface) = surface {
215                structured = structured.with_surface(surface);
216            }
217            return structured;
218        }
219        if let Some(inspection) = error.downcast_ref::<crate::tools::source_inspection::InspectionRequired>() {
220            let mut structured = Self::new(tool_name, ToolErrorType::InvalidParameters, inspection.to_string());
221            structured.inspection_failure = Some(inspection.details.clone());
222            structured.retryable = false;
223            structured.is_recoverable = true;
224            structured.circuit_breaker_impact = false;
225            structured.recovery_suggestions = vec![Cow::Borrowed(
226                if inspection.details.get("next_read_args").is_some() {
227                    "Use inspection_failure.next_read_args to refresh the missing source, then retry a bounded edit."
228                } else {
229                    "Use apply_patch for authored file changes; mechanical commands require an exact trusted-user exemption."
230                },
231            )];
232            return structured;
233        }
234        // Classify exactly once into the canonical category; the wire-visible
235        // `error_type` is derived from it inside `from_category`.
236        if let Some(session_error) = error.downcast_ref::<crate::tools::exec_session::ExecSessionNotFound>() {
237            let mut structured =
238                Self::from_category(tool_name, ErrorCategory::ResourceNotFound, session_error.to_string())
239                    .with_debug_metadata("failure_code", EXEC_SESSION_NOT_FOUND_CODE);
240            structured.original_error =
241                Some(vtcode_commons::formatting::head_tail_truncate(&format!("{error:#}"), 640, " ... ").0);
242            structured.partial_state_possible = partial_state_possible;
243            structured.rollback_performed = rollback_performed;
244            structured.recovery_suggestions = vec![Cow::Borrowed(
245                "Recover the exact session ID from the original response. Reuse recorded completion output; rerun only if fresh execution is still needed.",
246            )];
247            if let Some(surface) = surface {
248                structured = structured.with_surface(surface);
249            }
250            return structured;
251        }
252        if let Some(patch_error) = error.downcast_ref::<crate::tools::editing::PatchError>() {
253            use crate::tools::editing::PatchError;
254            let category = match patch_error {
255                PatchError::InvalidPath { .. } => ErrorCategory::PolicyViolation,
256                PatchError::MissingFile { .. } => ErrorCategory::ResourceNotFound,
257                PatchError::EmptyInput
258                | PatchError::NoOperations
259                | PatchError::InvalidFormat(_)
260                | PatchError::InvalidHunk { .. } => ErrorCategory::InvalidParameters,
261                PatchError::Io { source, .. } if source.kind() == std::io::ErrorKind::PermissionDenied => {
262                    ErrorCategory::PermissionDenied
263                }
264                _ => ErrorCategory::ExecutionError,
265            };
266            let mut structured = Self::from_category(tool_name.clone(), category, patch_error.to_string());
267            structured.original_error =
268                Some(vtcode_commons::formatting::head_tail_truncate(&format!("{error:#}"), 640, " ... ").0);
269            structured.patch_failure =
270                Some(match (patch_error.redacted_context_path(), patch_error.context_mismatch()) {
271                    (Some(path), _) => PatchFailure::RedactedContext { path: path.to_string() },
272                    (_, Some((path, evidence))) => PatchFailure::ContextMismatch {
273                        path: path.to_string(),
274                        evidence: vtcode_commons::formatting::head_tail_truncate(evidence, 320, " ... ").0,
275                    },
276                    _ => PatchFailure::Other,
277                });
278            if patch_error.redacted_context_path().is_some() {
279                structured.recovery_suggestions = vec![Cow::Borrowed(
280                    "Repeated reads show the same redaction. Split the edit around the hidden line if possible; ask the user for help if that line must change. Do not guess or write the redaction marker as a replacement.",
281                )];
282            } else if let Some(path) = structured.patch_context_mismatch_path() {
283                structured.message = format!(
284                    "Patch context mismatch in '{path}': use complete current lines and preserve internal whitespace."
285                );
286                structured.recovery_suggestions = vec![Cow::Borrowed(
287                    "Read the affected path once with a file read limit of 1-200 lines or a single sed -n range, then rebuild apply_patch with complete current context. Never retry the unchanged failed patch. Do not probe matching with scratch edits or inspect the patch implementation. One fresh recovery read per path per turn can pass either read cap; other limits still apply.",
288                )];
289            } else if category == ErrorCategory::InvalidParameters {
290                structured.recovery_suggestions = vec![Cow::Borrowed(
291                    crate::tools::apply_patch::APPLY_PATCH_ARGUMENT_CORRECTION,
292                )];
293            } else {
294                structured.recovery_suggestions = vec![Cow::Borrowed(
295                    "Resolve the reported patch target or filesystem error before retrying; retain permission and workspace boundaries.",
296                )];
297            }
298            structured.retryable = false;
299            structured.is_recoverable =
300                !matches!(category, ErrorCategory::PolicyViolation | ErrorCategory::PermissionDenied);
301            structured.circuit_breaker_impact = false;
302            structured = apply_explicit_error_state(structured, tool_name.as_str(), error);
303            if let Some(surface) = surface {
304                structured = structured.with_surface(surface);
305            }
306            return structured;
307        }
308        let category = vtcode_commons::classify_anyhow_error(error);
309        let mut structured = Self::from_category(tool_name.clone(), category, error.to_string());
310        structured.original_error = Some(format!("{error:#}"));
311        structured =
312            RetryPolicy::default().apply_to_tool_execution_error(structured, attempt_index, Some(tool_name.as_str()));
313        structured.partial_state_possible = partial_state_possible;
314        structured.rollback_performed = rollback_performed;
315        structured = apply_explicit_error_state(structured, tool_name.as_str(), error);
316        if let Some(surface) = surface {
317            structured = structured.with_surface(surface);
318        }
319        structured
320    }
321
322    /// Recovery path for typed patch or literal mismatches; never infer from source text.
323    #[must_use]
324    pub fn patch_context_mismatch_path(&self) -> Option<&str> {
325        match &self.patch_failure {
326            Some(PatchFailure::ContextMismatch { path, .. }) => Some(path),
327            _ => self.edit_failure.as_ref().map(|failure| failure.path.as_str()),
328        }
329    }
330
331    /// Whether a patch failed because its source view was redacted.
332    #[must_use]
333    pub fn is_redacted_patch_context(&self) -> bool {
334        matches!(self.patch_failure, Some(PatchFailure::RedactedContext { .. }))
335    }
336
337    /// Whether a typed runtime lookup failed, independent of quoted text.
338    #[must_use]
339    pub fn is_exec_session_not_found(&self) -> bool {
340        self.category == ErrorCategory::ResourceNotFound
341            && self.debug_context.as_ref().is_some_and(|context| {
342                context
343                    .metadata
344                    .iter()
345                    .any(|(key, value)| key == "failure_code" && value == EXEC_SESSION_NOT_FOUND_CODE)
346            })
347    }
348
349    #[must_use]
350    pub fn policy_violation(tool_name: impl Into<String>, message: impl Into<String>) -> Self {
351        Self::new(tool_name, ToolErrorType::PolicyViolation, message)
352    }
353
354    #[must_use]
355    pub fn with_retry_decision(mut self, decision: RetryDecision) -> Self {
356        self.category = decision.category;
357        // Keep the derived view in lockstep with the authoritative category.
358        // `ToolErrorType::from` is the identity on every ToolErrorType ->
359        // ErrorCategory -> ToolErrorType round trip, so this only changes
360        // `error_type` when the decision actually recategorized the error.
361        self.error_type = ToolErrorType::from(decision.category);
362        self.retryable = decision.retryable;
363        self.retry_delay_ms = decision.delay.map(|delay| delay.as_millis() as u64);
364        self.retry_after_ms = decision.retry_after.map(|delay| delay.as_millis() as u64);
365        self.circuit_breaker_impact = decision.category.should_trip_circuit_breaker();
366        self
367    }
368
369    #[must_use]
370    pub fn with_partial_state(mut self, partial_state_possible: bool, rollback_performed: bool) -> Self {
371        self.partial_state_possible = partial_state_possible;
372        self.rollback_performed = rollback_performed;
373        self
374    }
375
376    #[must_use]
377    pub fn with_surface(mut self, surface: impl Into<String>) -> Self {
378        let debug = self.debug_context.get_or_insert_with(ToolErrorDebugContext::default);
379        debug.surface = Some(surface.into());
380        self
381    }
382
383    #[must_use]
384    pub fn with_attempt(mut self, attempt: u32) -> Self {
385        let debug = self.debug_context.get_or_insert_with(ToolErrorDebugContext::default);
386        debug.attempt = Some(attempt);
387        self
388    }
389
390    #[must_use]
391    pub fn with_invocation_id(mut self, invocation_id: impl Into<String>) -> Self {
392        let debug = self.debug_context.get_or_insert_with(ToolErrorDebugContext::default);
393        debug.invocation_id = Some(invocation_id.into());
394        self
395    }
396
397    #[must_use]
398    pub fn with_debug_metadata(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
399        let debug = self.debug_context.get_or_insert_with(ToolErrorDebugContext::default);
400        debug.metadata.push((key.into(), value.into()));
401        self
402    }
403
404    #[must_use]
405    pub fn with_tool_call_context(mut self, tool_name: &str, args: &Value) -> Self {
406        self.tool_name = tool_name.to_string();
407
408        if self.inspection_failure.is_some() || self.edit_failure.is_some() {
409            self.partial_state_possible = false;
410            return self;
411        }
412        if tool_name == crate::config::constants::tools::APPLY_PATCH {
413            return self;
414        }
415
416        let intent = crate::tools::tool_intent::classify_tool_intent(tool_name, args);
417        if intent.mutating || is_command_tool(tool_name) {
418            self.partial_state_possible = true;
419        }
420
421        self
422    }
423
424    #[must_use]
425    pub fn attempts_made(&self) -> Option<u32> {
426        self.debug_context.as_ref().and_then(|context| context.attempt)
427    }
428
429    #[must_use]
430    pub fn retry_summary(&self) -> Option<String> {
431        let retry_count = self.attempts_made().map(|attempts| attempts.saturating_sub(1)).unwrap_or(0);
432
433        let mut summary = if matches!(self.category, ErrorCategory::CircuitOpen) {
434            Some("The service is pausing new calls after repeated transient failures.".to_string())
435        } else if retry_count > 0 {
436            let suffix = if retry_count == 1 { "" } else { "s" };
437            Some(format!("Retried {retry_count} time{suffix} before failing."))
438        } else {
439            None
440        };
441
442        if let Some(delay_ms) = self.retry_after_ms.or(self.retry_delay_ms) {
443            let delay = format_retry_delay(delay_ms);
444            match summary.as_mut() {
445                Some(existing) => {
446                    existing.push(' ');
447                    existing.push_str("Recommended wait: ");
448                    existing.push_str(&delay);
449                    existing.push('.');
450                }
451                None => {
452                    summary = Some(format!("Recommended wait: {delay}."));
453                }
454            }
455        }
456
457        summary
458    }
459
460    #[must_use]
461    pub fn user_message(&self) -> String {
462        let mut message = format!("[{}] {}", self.category.user_label(), self.message);
463
464        if self.rollback_performed {
465            message.push_str(" Any partial changes were rolled back.");
466        } else if self.partial_state_possible {
467            message.push_str(" Partial changes may still exist.");
468        }
469
470        if let Some(retry_summary) = self.retry_summary() {
471            message.push(' ');
472            message.push_str(&retry_summary);
473        }
474
475        if let Some(next_action) = self.recovery_suggestions.first() {
476            message.push_str(" Next: ");
477            message.push_str(next_action.as_ref());
478        }
479
480        message
481    }
482
483    #[must_use]
484    pub fn retry_delay(&self) -> Option<std::time::Duration> {
485        self.retry_delay_ms.map(std::time::Duration::from_millis)
486    }
487
488    #[must_use]
489    pub fn retry_after(&self) -> Option<std::time::Duration> {
490        self.retry_after_ms.map(std::time::Duration::from_millis)
491    }
492
493    #[must_use]
494    pub fn from_tool_output(output: &Value) -> Option<Self> {
495        let error_payload = output.get("error")?;
496        let mut error = Self::from_error_payload(error_payload)?;
497        if let Some(status) = output.get("http_status").and_then(Value::as_u64) {
498            error.category = if status == 429 {
499                ErrorCategory::RateLimit
500            } else {
501                ErrorCategory::Network
502            };
503            error.error_type = ToolErrorType::NetworkError;
504            error.retryable = status == 429 || (500..600).contains(&status);
505            let context = error.debug_context.get_or_insert_with(ToolErrorDebugContext::default);
506            context.metadata.push(("http_status".to_owned(), status.to_string()));
507        }
508        if output.get("error_type").and_then(Value::as_str) == Some("policy_blocked") {
509            error.error_type = ToolErrorType::PolicyViolation;
510            error.category = ErrorCategory::PermissionDenied;
511            error.retryable = false;
512        }
513        if let Some(action) = output.get("next_action").and_then(Value::as_str) {
514            error.recovery_suggestions = vec![Cow::Owned(action.to_owned())];
515        }
516        if let Some(delay) = output.get("retry_after_ms").and_then(Value::as_u64) {
517            error.retry_after_ms = Some(delay);
518        }
519        Some(error)
520    }
521
522    #[must_use]
523    pub fn from_error_payload(error_payload: &Value) -> Option<Self> {
524        if let Some(inner) = error_payload.get("error") {
525            return Self::from_error_payload(inner);
526        }
527
528        if error_payload.is_object() && error_payload.get("message").is_some() {
529            // Single source of truth: deserialize via serde. The previous
530            // implementation hand-built the error struct from individual
531            // fields, which silently dropped any new field that was added to
532            // `ToolExecutionError` (it would fall through to `Self::new`'s
533            // default for that field, which could be subtly wrong).
534            //
535            // `serde_json::from_value` honors every `#[serde(default)]` on
536            // the struct, so a partial payload still reconstructs safely.
537            if let Ok(structured) = serde_json::from_value::<Self>(error_payload.clone()) {
538                return Some(structured);
539            }
540
541            // Last-resort fallback: pull out the minimum fields needed to
542            // construct a usable error. This branch only fires when the
543            // payload is malformed (e.g. wrong type for `category`).
544            let tool_name = error_payload.get("tool_name").and_then(Value::as_str).unwrap_or("tool");
545            let message = error_payload
546                .get("message")
547                .and_then(Value::as_str)
548                .unwrap_or("Unknown tool execution error");
549            let category = error_payload
550                .get("category")
551                .and_then(|value| serde_json::from_value(value.clone()).ok())
552                .unwrap_or_else(|| vtcode_commons::classify_error_message(message));
553            let error_type = error_payload
554                .get("error_type")
555                .and_then(Value::as_str)
556                .map(parse_error_type)
557                .unwrap_or_else(|| ToolErrorType::from(category));
558            let mut structured = Self::new(tool_name.to_string(), error_type, message.to_string());
559            structured.category = category;
560            structured.original_error = error_payload
561                .get("original_error")
562                .and_then(Value::as_str)
563                .map(ToOwned::to_owned);
564            return Some(structured);
565        }
566
567        error_payload.as_str().map(|message| {
568            let category = vtcode_commons::classify_error_message(message);
569            Self::new("tool".to_string(), ToolErrorType::from(category), message.to_string())
570        })
571    }
572
573    #[must_use]
574    pub fn to_json_value(&self) -> Value {
575        let mut output = json!({
576            "error": {
577                "tool_name": self.tool_name,
578                "error_type": self.error_type.as_str(),
579                "category": self.category,
580                "message": self.message,
581                "retryable": self.retryable,
582                "is_recoverable": self.is_recoverable,
583                "recovery_suggestions": self.recovery_suggestions,
584                "retry_delay_ms": self.retry_delay_ms,
585                "retry_after_ms": self.retry_after_ms,
586                "circuit_breaker_impact": self.circuit_breaker_impact,
587                "partial_state_possible": self.partial_state_possible,
588                "rollback_performed": self.rollback_performed,
589                "debug_context": self.debug_context,
590                "original_error": self.original_error,
591                "patch_failure": self.patch_failure,
592                "inspection_failure": self.inspection_failure,
593                "edit_failure": self.edit_failure,
594            }
595        });
596        if let Some(context) = &self.debug_context
597            && let Some((_, status)) = context.metadata.iter().find(|(key, _)| key == "http_status")
598            && let Ok(status) = status.parse::<u16>()
599        {
600            output["error"]["http_status"] = json!(status);
601        }
602        output
603    }
604}
605
606impl std::fmt::Display for ToolExecutionError {
607    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
608        f.write_str(&self.message)
609    }
610}
611
612impl std::error::Error for ToolExecutionError {}
613
614// Use static string slices to avoid allocations for recovery suggestions.
615// Delegates to the shared `ErrorCategory` recovery suggestions where possible.
616#[inline]
617fn generate_recovery_info(
618    tool_name: &str,
619    category: ErrorCategory,
620    error_type: ToolErrorType,
621) -> (bool, bool, Vec<Cow<'static, str>>) {
622    let is_recoverable = category.is_retryable()
623        || matches!(
624            error_type,
625            ToolErrorType::InvalidParameters | ToolErrorType::PermissionDenied | ToolErrorType::ResourceNotFound
626        );
627    let retryable =
628        category.is_retryable() && !crate::retry::is_non_retryable_command_timeout(category, Some(tool_name));
629    (retryable, is_recoverable, category.recovery_suggestions())
630}
631
632fn parse_error_type(raw: &str) -> ToolErrorType {
633    match raw {
634        "InvalidParameters" => ToolErrorType::InvalidParameters,
635        "ToolNotFound" => ToolErrorType::ToolNotFound,
636        "PermissionDenied" => ToolErrorType::PermissionDenied,
637        "ResourceNotFound" => ToolErrorType::ResourceNotFound,
638        "NetworkError" => ToolErrorType::NetworkError,
639        "Timeout" => ToolErrorType::Timeout,
640        "ExecutionError" => ToolErrorType::ExecutionError,
641        "PolicyViolation" => ToolErrorType::PolicyViolation,
642        _ => ToolErrorType::ExecutionError,
643    }
644}
645
646fn format_retry_delay(delay_ms: u64) -> String {
647    if delay_ms >= 1_000 {
648        format!("{:.1}s", delay_ms as f64 / 1_000.0)
649    } else {
650        format!("{delay_ms}ms")
651    }
652}
653
654fn apply_explicit_error_state(mut error: ToolExecutionError, tool_name: &str, source: &Error) -> ToolExecutionError {
655    if tool_name != crate::config::constants::tools::APPLY_PATCH {
656        return error;
657    }
658
659    if let Some(patch_error) = source.downcast_ref::<crate::tools::editing::PatchError>() {
660        match patch_error {
661            crate::tools::editing::PatchError::RolledBack { .. } => {
662                error = error.with_partial_state(false, true);
663            }
664            crate::tools::editing::PatchError::Recovery { .. } => {
665                error = error.with_partial_state(true, false);
666            }
667            _ => {}
668        }
669    }
670
671    error
672}
673
674// === Bridge conversions between ErrorCategory and ToolErrorType ===
675
676impl From<ErrorCategory> for ToolErrorType {
677    fn from(cat: ErrorCategory) -> Self {
678        match cat {
679            ErrorCategory::InvalidParameters => ToolErrorType::InvalidParameters,
680            ErrorCategory::ToolNotFound => ToolErrorType::ToolNotFound,
681            ErrorCategory::ResourceNotFound => ToolErrorType::ResourceNotFound,
682            ErrorCategory::PermissionDenied => ToolErrorType::PermissionDenied,
683            ErrorCategory::Network | ErrorCategory::ServiceUnavailable => ToolErrorType::NetworkError,
684            ErrorCategory::Timeout => ToolErrorType::Timeout,
685            ErrorCategory::PolicyViolation | ErrorCategory::PlanningPolicyViolation => ToolErrorType::PolicyViolation,
686            ErrorCategory::RateLimit => ToolErrorType::NetworkError,
687            ErrorCategory::CircuitOpen => ToolErrorType::ExecutionError,
688            ErrorCategory::Authentication => ToolErrorType::PermissionDenied,
689            ErrorCategory::SandboxFailure => ToolErrorType::PolicyViolation,
690            ErrorCategory::ResourceExhausted => ToolErrorType::ExecutionError,
691            ErrorCategory::Cancelled => ToolErrorType::ExecutionError,
692            ErrorCategory::ExecutionError => ToolErrorType::ExecutionError,
693        }
694    }
695}
696
697impl From<ToolErrorType> for ErrorCategory {
698    fn from(t: ToolErrorType) -> Self {
699        match t {
700            ToolErrorType::InvalidParameters => ErrorCategory::InvalidParameters,
701            ToolErrorType::ToolNotFound => ErrorCategory::ToolNotFound,
702            ToolErrorType::ResourceNotFound => ErrorCategory::ResourceNotFound,
703            ToolErrorType::PermissionDenied => ErrorCategory::PermissionDenied,
704            ToolErrorType::NetworkError => ErrorCategory::Network,
705            ToolErrorType::Timeout => ErrorCategory::Timeout,
706            ToolErrorType::PolicyViolation => ErrorCategory::PolicyViolation,
707            ToolErrorType::ExecutionError => ErrorCategory::ExecutionError,
708        }
709    }
710}
711
712#[cfg(test)]
713mod tests {
714    use super::*;
715    use anyhow::anyhow;
716
717    fn classify(err: &Error) -> ToolErrorType {
718        ToolErrorType::from(vtcode_commons::classify_anyhow_error(err))
719    }
720
721    #[test]
722    fn classify_error_marks_rate_limit_as_network_error() {
723        let err = anyhow!("provider returned 429 Too Many Requests");
724        assert!(matches!(classify(&err), ToolErrorType::NetworkError));
725    }
726
727    #[test]
728    fn classify_error_marks_service_unavailable_as_network_error() {
729        let err = anyhow!("503 Service Unavailable");
730        assert!(matches!(classify(&err), ToolErrorType::NetworkError));
731    }
732
733    #[test]
734    fn classify_error_marks_weekly_usage_limit_as_execution_error() {
735        let err = anyhow!("you have reached your weekly usage limit");
736        assert!(matches!(classify(&err), ToolErrorType::ExecutionError));
737    }
738
739    #[test]
740    fn classify_error_marks_tool_not_found() {
741        let err = anyhow!("unknown tool: ask_questions");
742        assert!(matches!(classify(&err), ToolErrorType::ToolNotFound));
743    }
744
745    #[test]
746    fn classify_error_marks_policy_violation_before_permission() {
747        let err = anyhow!("tool permission denied by policy");
748        assert!(matches!(classify(&err), ToolErrorType::PolicyViolation));
749    }
750
751    const ALL_TOOL_ERROR_TYPES: [ToolErrorType; 8] = [
752        ToolErrorType::InvalidParameters,
753        ToolErrorType::ToolNotFound,
754        ToolErrorType::PermissionDenied,
755        ToolErrorType::ResourceNotFound,
756        ToolErrorType::NetworkError,
757        ToolErrorType::Timeout,
758        ToolErrorType::ExecutionError,
759        ToolErrorType::PolicyViolation,
760    ];
761
762    #[test]
763    fn error_type_wire_string_round_trips() {
764        for error_type in ALL_TOOL_ERROR_TYPES {
765            assert_eq!(parse_error_type(error_type.as_str()), error_type);
766        }
767    }
768
769    #[test]
770    fn error_type_category_round_trip_is_identity() {
771        // Guarantees `with_retry_decision` never changes error_type unless the
772        // decision actually recategorized the error.
773        for error_type in ALL_TOOL_ERROR_TYPES {
774            assert_eq!(ToolErrorType::from(ErrorCategory::from(error_type)), error_type);
775        }
776    }
777
778    #[test]
779    fn from_anyhow_derives_error_type_from_category() {
780        let err = anyhow!("provider returned 429 Too Many Requests");
781        let structured = ToolExecutionError::from_anyhow("grep_search", &err, 0, false, false, None);
782        assert_eq!(structured.category, ErrorCategory::RateLimit);
783        assert_eq!(structured.error_type, ToolErrorType::from(structured.category));
784    }
785
786    #[test]
787    fn missing_exec_session_classification_survives_context_and_round_trip() {
788        let source = Error::new(crate::tools::exec_session::ExecSessionNotFound { session_id: "run-missing".into() })
789            .context("quoted diagnostic: permission denied in vtcode.toml");
790        let structured = ToolExecutionError::from_anyhow("write_stdin", &source, 0, false, false, Some("registry"));
791        assert_eq!(structured.category, ErrorCategory::ResourceNotFound);
792        assert!(structured.is_exec_session_not_found());
793        assert!(!structured.retryable);
794        assert!(!structured.circuit_breaker_impact);
795        assert_eq!(structured.debug_context.as_ref().unwrap().surface.as_deref(), Some("registry"));
796        assert!(structured.message.contains("reuse its output"));
797        assert!(!structured.message.contains("re-run the command instead of waiting"));
798        let decoded = ToolExecutionError::from_error_payload(&structured.to_json_value()).unwrap();
799        assert!(decoded.is_exec_session_not_found());
800
801        let lookalike = anyhow!("exec session 'run-missing' not found: permission denied");
802        let untyped = ToolExecutionError::from_anyhow("write_stdin", &lookalike, 0, false, false, None);
803        assert_eq!(untyped.category, ErrorCategory::PermissionDenied);
804        assert!(!untyped.is_exec_session_not_found());
805    }
806
807    #[test]
808    fn retryable_matches_error_category_predicate() {
809        for error_type in ALL_TOOL_ERROR_TYPES {
810            let category = ErrorCategory::from(error_type);
811            let structured = ToolExecutionError::new("grep_search".to_string(), error_type, "boom".to_string());
812            assert_eq!(structured.retryable, category.is_retryable(), "retryable mismatch for {error_type:?}");
813        }
814    }
815
816    #[test]
817    fn command_tool_timeouts_are_not_retryable() {
818        let structured = ToolExecutionError::new(
819            crate::config::constants::tools::CREATE_PTY_SESSION.to_string(),
820            ToolErrorType::Timeout,
821            "command timed out".to_string(),
822        );
823        assert!(!structured.retryable);
824    }
825
826    #[test]
827    fn tool_call_context_marks_mutating_tools_as_partial_state_possible() {
828        let error = ToolExecutionError::new(
829            "write_file".to_string(),
830            ToolErrorType::ExecutionError,
831            "write failed".to_string(),
832        )
833        .with_tool_call_context(
834            crate::config::constants::tools::WRITE_FILE,
835            &serde_json::json!({"path": "note.txt", "content": "hello"}),
836        );
837
838        assert!(error.partial_state_possible);
839        assert!(!error.rollback_performed);
840    }
841
842    #[test]
843    fn tool_call_context_marks_apply_patch_failures_as_rolled_back() {
844        let source = Error::new(crate::tools::editing::PatchError::RolledBack {
845            original: Box::new(crate::tools::editing::PatchError::SegmentNotFound {
846                path: "src/lib.rs".to_string(),
847                snippet: "fn main()".to_string(),
848            }),
849        });
850        let error = ToolExecutionError::from_anyhow(
851            crate::config::constants::tools::APPLY_PATCH,
852            &source,
853            0,
854            false,
855            false,
856            None,
857        );
858
859        assert!(!error.partial_state_possible);
860        assert!(error.rollback_performed);
861    }
862
863    #[test]
864    fn user_message_includes_retry_summary_and_wait() {
865        let mut error = ToolExecutionError::new(
866            crate::config::constants::tools::READ_FILE.to_string(),
867            ToolErrorType::ExecutionError,
868            "read failed".to_string(),
869        )
870        .with_attempt(2);
871        error.retry_delay_ms = Some(1_500);
872
873        let message = error.user_message();
874
875        assert!(message.contains("Retried 1 time before failing."));
876        assert!(message.contains("Recommended wait: 1.5s."));
877    }
878}