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 { .. }
261                | PatchError::OverlappingChunks { .. }
262                | PatchError::TargetAlreadyExists { .. }
263                | PatchError::NotAFile { .. }
264                | PatchError::DestinationExists { .. } => ErrorCategory::InvalidParameters,
265                PatchError::Io { source, .. } if source.kind() == std::io::ErrorKind::PermissionDenied => {
266                    ErrorCategory::PermissionDenied
267                }
268                _ => ErrorCategory::ExecutionError,
269            };
270            let mut structured = Self::from_category(tool_name.clone(), category, patch_error.to_string());
271            structured.original_error =
272                Some(vtcode_commons::formatting::head_tail_truncate(&format!("{error:#}"), 640, " ... ").0);
273            structured.patch_failure =
274                Some(match (patch_error.redacted_context_path(), patch_error.context_mismatch()) {
275                    (Some(path), _) => PatchFailure::RedactedContext { path: path.to_string() },
276                    (_, Some((path, evidence))) => PatchFailure::ContextMismatch {
277                        path: path.to_string(),
278                        evidence: vtcode_commons::formatting::head_tail_truncate(evidence, 320, " ... ").0,
279                    },
280                    _ => PatchFailure::Other,
281                });
282            if patch_error.redacted_context_path().is_some() {
283                structured.recovery_suggestions = vec![Cow::Borrowed(
284                    "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.",
285                )];
286            } else if let Some(path) = structured.patch_context_mismatch_path() {
287                structured.message = format!(
288                    "Patch context mismatch in '{path}': use complete current lines and preserve internal whitespace."
289                );
290                structured.recovery_suggestions = vec![Cow::Borrowed(
291                    "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.",
292                )];
293            } else if category == ErrorCategory::InvalidParameters {
294                structured.recovery_suggestions = vec![Cow::Borrowed(
295                    crate::tools::apply_patch::APPLY_PATCH_ARGUMENT_CORRECTION,
296                )];
297            } else {
298                structured.recovery_suggestions = vec![Cow::Borrowed(
299                    "Resolve the reported patch target or filesystem error before retrying; retain permission and workspace boundaries.",
300                )];
301            }
302            structured.retryable = false;
303            structured.is_recoverable =
304                !matches!(category, ErrorCategory::PolicyViolation | ErrorCategory::PermissionDenied);
305            structured.circuit_breaker_impact = false;
306            structured = apply_explicit_error_state(structured, tool_name.as_str(), error);
307            if let Some(surface) = surface {
308                structured = structured.with_surface(surface);
309            }
310            return structured;
311        }
312        let category = vtcode_commons::classify_anyhow_error(error);
313        let mut structured = Self::from_category(tool_name.clone(), category, error.to_string());
314        structured.original_error = Some(format!("{error:#}"));
315        structured =
316            RetryPolicy::default().apply_to_tool_execution_error(structured, attempt_index, Some(tool_name.as_str()));
317        structured.partial_state_possible = partial_state_possible;
318        structured.rollback_performed = rollback_performed;
319        structured = apply_explicit_error_state(structured, tool_name.as_str(), error);
320        if let Some(surface) = surface {
321            structured = structured.with_surface(surface);
322        }
323        structured
324    }
325
326    /// Recovery path for typed patch or literal mismatches; never infer from source text.
327    #[must_use]
328    pub fn patch_context_mismatch_path(&self) -> Option<&str> {
329        match &self.patch_failure {
330            Some(PatchFailure::ContextMismatch { path, .. }) => Some(path),
331            _ => self.edit_failure.as_ref().map(|failure| failure.path.as_str()),
332        }
333    }
334
335    /// Whether a patch failed because its source view was redacted.
336    #[must_use]
337    pub fn is_redacted_patch_context(&self) -> bool {
338        matches!(self.patch_failure, Some(PatchFailure::RedactedContext { .. }))
339    }
340
341    /// Whether a typed runtime lookup failed, independent of quoted text.
342    #[must_use]
343    pub fn is_exec_session_not_found(&self) -> bool {
344        self.category == ErrorCategory::ResourceNotFound
345            && self.debug_context.as_ref().is_some_and(|context| {
346                context
347                    .metadata
348                    .iter()
349                    .any(|(key, value)| key == "failure_code" && value == EXEC_SESSION_NOT_FOUND_CODE)
350            })
351    }
352
353    #[must_use]
354    pub fn policy_violation(tool_name: impl Into<String>, message: impl Into<String>) -> Self {
355        Self::new(tool_name, ToolErrorType::PolicyViolation, message)
356    }
357
358    #[must_use]
359    pub fn with_retry_decision(mut self, decision: RetryDecision) -> Self {
360        self.category = decision.category;
361        // Keep the derived view in lockstep with the authoritative category.
362        // `ToolErrorType::from` is the identity on every ToolErrorType ->
363        // ErrorCategory -> ToolErrorType round trip, so this only changes
364        // `error_type` when the decision actually recategorized the error.
365        self.error_type = ToolErrorType::from(decision.category);
366        self.retryable = decision.retryable;
367        self.retry_delay_ms = decision.delay.map(|delay| delay.as_millis() as u64);
368        self.retry_after_ms = decision.retry_after.map(|delay| delay.as_millis() as u64);
369        self.circuit_breaker_impact = decision.category.should_trip_circuit_breaker();
370        self
371    }
372
373    #[must_use]
374    pub fn with_partial_state(mut self, partial_state_possible: bool, rollback_performed: bool) -> Self {
375        self.partial_state_possible = partial_state_possible;
376        self.rollback_performed = rollback_performed;
377        self
378    }
379
380    #[must_use]
381    pub fn with_surface(mut self, surface: impl Into<String>) -> Self {
382        let debug = self.debug_context.get_or_insert_with(ToolErrorDebugContext::default);
383        debug.surface = Some(surface.into());
384        self
385    }
386
387    #[must_use]
388    pub fn with_attempt(mut self, attempt: u32) -> Self {
389        let debug = self.debug_context.get_or_insert_with(ToolErrorDebugContext::default);
390        debug.attempt = Some(attempt);
391        self
392    }
393
394    #[must_use]
395    pub fn with_invocation_id(mut self, invocation_id: impl Into<String>) -> Self {
396        let debug = self.debug_context.get_or_insert_with(ToolErrorDebugContext::default);
397        debug.invocation_id = Some(invocation_id.into());
398        self
399    }
400
401    #[must_use]
402    pub fn with_debug_metadata(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
403        let debug = self.debug_context.get_or_insert_with(ToolErrorDebugContext::default);
404        debug.metadata.push((key.into(), value.into()));
405        self
406    }
407
408    #[must_use]
409    pub fn with_tool_call_context(mut self, tool_name: &str, args: &Value) -> Self {
410        self.tool_name = tool_name.to_string();
411
412        if self.inspection_failure.is_some() || self.edit_failure.is_some() {
413            self.partial_state_possible = false;
414            return self;
415        }
416        if tool_name == crate::config::constants::tools::APPLY_PATCH {
417            return self;
418        }
419
420        let intent = crate::tools::tool_intent::classify_tool_intent(tool_name, args);
421        if intent.mutating || is_command_tool(tool_name) {
422            self.partial_state_possible = true;
423        }
424
425        self
426    }
427
428    #[must_use]
429    pub fn attempts_made(&self) -> Option<u32> {
430        self.debug_context.as_ref().and_then(|context| context.attempt)
431    }
432
433    #[must_use]
434    pub fn retry_summary(&self) -> Option<String> {
435        let retry_count = self.attempts_made().map(|attempts| attempts.saturating_sub(1)).unwrap_or(0);
436
437        let mut summary = if matches!(self.category, ErrorCategory::CircuitOpen) {
438            Some("The service is pausing new calls after repeated transient failures.".to_string())
439        } else if retry_count > 0 {
440            let suffix = if retry_count == 1 { "" } else { "s" };
441            Some(format!("Retried {retry_count} time{suffix} before failing."))
442        } else {
443            None
444        };
445
446        if let Some(delay_ms) = self.retry_after_ms.or(self.retry_delay_ms) {
447            let delay = format_retry_delay(delay_ms);
448            match summary.as_mut() {
449                Some(existing) => {
450                    existing.push(' ');
451                    existing.push_str("Recommended wait: ");
452                    existing.push_str(&delay);
453                    existing.push('.');
454                }
455                None => {
456                    summary = Some(format!("Recommended wait: {delay}."));
457                }
458            }
459        }
460
461        summary
462    }
463
464    #[must_use]
465    pub fn user_message(&self) -> String {
466        let mut message = format!("[{}] {}", self.category.user_label(), self.message);
467
468        if self.rollback_performed {
469            message.push_str(" Any partial changes were rolled back.");
470        } else if self.partial_state_possible {
471            message.push_str(" Partial changes may still exist.");
472        }
473
474        if let Some(retry_summary) = self.retry_summary() {
475            message.push(' ');
476            message.push_str(&retry_summary);
477        }
478
479        if let Some(next_action) = self.recovery_suggestions.first() {
480            message.push_str(" Next: ");
481            message.push_str(next_action.as_ref());
482        }
483
484        message
485    }
486
487    #[must_use]
488    pub fn retry_delay(&self) -> Option<std::time::Duration> {
489        self.retry_delay_ms.map(std::time::Duration::from_millis)
490    }
491
492    #[must_use]
493    pub fn retry_after(&self) -> Option<std::time::Duration> {
494        self.retry_after_ms.map(std::time::Duration::from_millis)
495    }
496
497    #[must_use]
498    pub fn from_tool_output(output: &Value) -> Option<Self> {
499        let error_payload = output.get("error")?;
500        let mut error = Self::from_error_payload(error_payload)?;
501        if let Some(status) = output.get("http_status").and_then(Value::as_u64) {
502            error.category = if status == 429 {
503                ErrorCategory::RateLimit
504            } else {
505                ErrorCategory::Network
506            };
507            error.error_type = ToolErrorType::NetworkError;
508            error.retryable = status == 429 || (500..600).contains(&status);
509            let context = error.debug_context.get_or_insert_with(ToolErrorDebugContext::default);
510            context.metadata.push(("http_status".to_owned(), status.to_string()));
511        }
512        if output.get("error_type").and_then(Value::as_str) == Some("policy_blocked") {
513            error.error_type = ToolErrorType::PolicyViolation;
514            error.category = ErrorCategory::PermissionDenied;
515            error.retryable = false;
516        }
517        if let Some(action) = output.get("next_action").and_then(Value::as_str) {
518            error.recovery_suggestions = vec![Cow::Owned(action.to_owned())];
519        }
520        if let Some(delay) = output.get("retry_after_ms").and_then(Value::as_u64) {
521            error.retry_after_ms = Some(delay);
522        }
523        Some(error)
524    }
525
526    #[must_use]
527    pub fn from_error_payload(error_payload: &Value) -> Option<Self> {
528        if let Some(inner) = error_payload.get("error") {
529            return Self::from_error_payload(inner);
530        }
531
532        if error_payload.is_object() && error_payload.get("message").is_some() {
533            // Single source of truth: deserialize via serde. The previous
534            // implementation hand-built the error struct from individual
535            // fields, which silently dropped any new field that was added to
536            // `ToolExecutionError` (it would fall through to `Self::new`'s
537            // default for that field, which could be subtly wrong).
538            //
539            // `serde_json::from_value` honors every `#[serde(default)]` on
540            // the struct, so a partial payload still reconstructs safely.
541            if let Ok(structured) = serde_json::from_value::<Self>(error_payload.clone()) {
542                return Some(structured);
543            }
544
545            // Last-resort fallback: pull out the minimum fields needed to
546            // construct a usable error. This branch only fires when the
547            // payload is malformed (e.g. wrong type for `category`).
548            let tool_name = error_payload.get("tool_name").and_then(Value::as_str).unwrap_or("tool");
549            let message = error_payload
550                .get("message")
551                .and_then(Value::as_str)
552                .unwrap_or("Unknown tool execution error");
553            let category = error_payload
554                .get("category")
555                .and_then(|value| serde_json::from_value(value.clone()).ok())
556                .unwrap_or_else(|| vtcode_commons::classify_error_message(message));
557            let error_type = error_payload
558                .get("error_type")
559                .and_then(Value::as_str)
560                .map(parse_error_type)
561                .unwrap_or_else(|| ToolErrorType::from(category));
562            let mut structured = Self::new(tool_name.to_string(), error_type, message.to_string());
563            structured.category = category;
564            structured.original_error = error_payload
565                .get("original_error")
566                .and_then(Value::as_str)
567                .map(ToOwned::to_owned);
568            return Some(structured);
569        }
570
571        error_payload.as_str().map(|message| {
572            let category = vtcode_commons::classify_error_message(message);
573            Self::new("tool".to_string(), ToolErrorType::from(category), message.to_string())
574        })
575    }
576
577    #[must_use]
578    pub fn to_json_value(&self) -> Value {
579        let mut output = json!({
580            "error": {
581                "tool_name": self.tool_name,
582                "error_type": self.error_type.as_str(),
583                "category": self.category,
584                "message": self.message,
585                "retryable": self.retryable,
586                "is_recoverable": self.is_recoverable,
587                "recovery_suggestions": self.recovery_suggestions,
588                "retry_delay_ms": self.retry_delay_ms,
589                "retry_after_ms": self.retry_after_ms,
590                "circuit_breaker_impact": self.circuit_breaker_impact,
591                "partial_state_possible": self.partial_state_possible,
592                "rollback_performed": self.rollback_performed,
593                "debug_context": self.debug_context,
594                "original_error": self.original_error,
595                "patch_failure": self.patch_failure,
596                "inspection_failure": self.inspection_failure,
597                "edit_failure": self.edit_failure,
598            }
599        });
600        if let Some(context) = &self.debug_context
601            && let Some((_, status)) = context.metadata.iter().find(|(key, _)| key == "http_status")
602            && let Ok(status) = status.parse::<u16>()
603        {
604            output["error"]["http_status"] = json!(status);
605        }
606        output
607    }
608}
609
610impl std::fmt::Display for ToolExecutionError {
611    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
612        f.write_str(&self.message)
613    }
614}
615
616impl std::error::Error for ToolExecutionError {}
617
618// Use static string slices to avoid allocations for recovery suggestions.
619// Delegates to the shared `ErrorCategory` recovery suggestions where possible.
620#[inline]
621fn generate_recovery_info(
622    tool_name: &str,
623    category: ErrorCategory,
624    error_type: ToolErrorType,
625) -> (bool, bool, Vec<Cow<'static, str>>) {
626    let is_recoverable = category.is_retryable()
627        || matches!(
628            error_type,
629            ToolErrorType::InvalidParameters | ToolErrorType::PermissionDenied | ToolErrorType::ResourceNotFound
630        );
631    let retryable =
632        category.is_retryable() && !crate::retry::is_non_retryable_command_timeout(category, Some(tool_name));
633    (retryable, is_recoverable, category.recovery_suggestions())
634}
635
636fn parse_error_type(raw: &str) -> ToolErrorType {
637    match raw {
638        "InvalidParameters" => ToolErrorType::InvalidParameters,
639        "ToolNotFound" => ToolErrorType::ToolNotFound,
640        "PermissionDenied" => ToolErrorType::PermissionDenied,
641        "ResourceNotFound" => ToolErrorType::ResourceNotFound,
642        "NetworkError" => ToolErrorType::NetworkError,
643        "Timeout" => ToolErrorType::Timeout,
644        "ExecutionError" => ToolErrorType::ExecutionError,
645        "PolicyViolation" => ToolErrorType::PolicyViolation,
646        _ => ToolErrorType::ExecutionError,
647    }
648}
649
650fn format_retry_delay(delay_ms: u64) -> String {
651    if delay_ms >= 1_000 {
652        format!("{:.1}s", delay_ms as f64 / 1_000.0)
653    } else {
654        format!("{delay_ms}ms")
655    }
656}
657
658fn apply_explicit_error_state(mut error: ToolExecutionError, tool_name: &str, source: &Error) -> ToolExecutionError {
659    if tool_name != crate::config::constants::tools::APPLY_PATCH {
660        return error;
661    }
662
663    if let Some(patch_error) = source.downcast_ref::<crate::tools::editing::PatchError>() {
664        match patch_error {
665            crate::tools::editing::PatchError::RolledBack { .. } => {
666                error = error.with_partial_state(false, true);
667            }
668            crate::tools::editing::PatchError::Recovery { .. } => {
669                error = error.with_partial_state(true, false);
670            }
671            _ => {}
672        }
673    }
674
675    error
676}
677
678// === Bridge conversions between ErrorCategory and ToolErrorType ===
679
680impl From<ErrorCategory> for ToolErrorType {
681    fn from(cat: ErrorCategory) -> Self {
682        match cat {
683            ErrorCategory::InvalidParameters => ToolErrorType::InvalidParameters,
684            ErrorCategory::ToolNotFound => ToolErrorType::ToolNotFound,
685            ErrorCategory::ResourceNotFound => ToolErrorType::ResourceNotFound,
686            ErrorCategory::PermissionDenied => ToolErrorType::PermissionDenied,
687            ErrorCategory::Network | ErrorCategory::ServiceUnavailable => ToolErrorType::NetworkError,
688            ErrorCategory::Timeout => ToolErrorType::Timeout,
689            ErrorCategory::PolicyViolation | ErrorCategory::PlanningPolicyViolation => ToolErrorType::PolicyViolation,
690            ErrorCategory::RateLimit => ToolErrorType::NetworkError,
691            ErrorCategory::CircuitOpen => ToolErrorType::ExecutionError,
692            ErrorCategory::Authentication => ToolErrorType::PermissionDenied,
693            ErrorCategory::SandboxFailure => ToolErrorType::PolicyViolation,
694            ErrorCategory::ResourceExhausted => ToolErrorType::ExecutionError,
695            ErrorCategory::Cancelled => ToolErrorType::ExecutionError,
696            ErrorCategory::ExecutionError => ToolErrorType::ExecutionError,
697        }
698    }
699}
700
701impl From<ToolErrorType> for ErrorCategory {
702    fn from(t: ToolErrorType) -> Self {
703        match t {
704            ToolErrorType::InvalidParameters => ErrorCategory::InvalidParameters,
705            ToolErrorType::ToolNotFound => ErrorCategory::ToolNotFound,
706            ToolErrorType::ResourceNotFound => ErrorCategory::ResourceNotFound,
707            ToolErrorType::PermissionDenied => ErrorCategory::PermissionDenied,
708            ToolErrorType::NetworkError => ErrorCategory::Network,
709            ToolErrorType::Timeout => ErrorCategory::Timeout,
710            ToolErrorType::PolicyViolation => ErrorCategory::PolicyViolation,
711            ToolErrorType::ExecutionError => ErrorCategory::ExecutionError,
712        }
713    }
714}
715
716#[cfg(test)]
717mod tests;