Skip to main content

vtcode_commons/error_category/
mod.rs

1#![expect(
2    clippy::let_underscore_must_use,
3    reason = "The category formatter intentionally ignores infallible formatting results."
4)]
5
6//! Unified error categorization system for consistent error classification across VT Code.
7//!
8//! This module provides a single canonical `ErrorCategory` enum that unifies the
9//! previously separate classification systems in `registry::error` (8-variant `ToolErrorType`)
10//! and `unified_error` (16-variant `UnifiedErrorKind`). Both systems now map through
11//! this shared taxonomy for consistent retry decisions and error handling.
12//!
13//! # Error Categories
14//!
15//! Errors are divided into **retryable** (transient) and **non-retryable** (permanent)
16//! categories, with sub-classifications for specific handling strategies.
17//!
18//! # Design Decisions
19//!
20//! - String-based fallback is preserved only for `anyhow::Error` chains where the
21//!   original type is erased. Typed `From` conversions are preferred.
22//! - Policy violations are explicitly separated from OS-level permission denials.
23//! - Rate limiting is a distinct category (not merged with network errors).
24//! - Circuit breaker open is categorized separately for recovery flow routing.
25
26use std::borrow::Cow;
27use std::fmt;
28use std::fmt::Write;
29use std::time::Duration;
30
31/// Where a rejected credential came from, for auth-failure guidance.
32/// Mirrors `vtcode_config::api_keys::CredentialSource` without the dependency
33/// (`vtcode-config` depends on this crate).
34#[derive(Debug, Clone, PartialEq, Eq)]
35pub enum RejectedCredentialSource {
36    /// Process environment variable; carries the variable name when known.
37    /// `None` (a fully custom variable) keeps the source-level wording
38    /// rather than guessing the provider default.
39    Environment { env_var: Option<String> },
40    /// Workspace `.env` file; carries the variable name when known.
41    WorkspaceDotEnv { env_var: Option<String> },
42    /// OS keyring / encrypted file storage.
43    SecureStorage,
44}
45
46/// Canonical error category used throughout VT Code for consistent
47/// retry decisions, user-facing messages, and error handling strategies.
48#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
49pub enum ErrorCategory {
50    // === Retryable (Transient) ===
51    /// Network connectivity issue (connection reset, DNS failure, etc.)
52    Network,
53    /// Request timed out or deadline exceeded
54    Timeout,
55    /// Rate limit exceeded (HTTP 429, provider throttling)
56    RateLimit,
57    /// External service temporarily unavailable (HTTP 5xx)
58    ServiceUnavailable,
59    /// Circuit breaker is open for this tool/service
60    CircuitOpen,
61
62    // === Non-Retryable (Permanent) ===
63    /// Authentication or authorization failure (invalid API key, expired token)
64    Authentication,
65    /// Invalid parameters, arguments, or schema validation failure
66    InvalidParameters,
67    /// Tool not found or unavailable
68    ToolNotFound,
69    /// Resource not found (file, directory, path does not exist)
70    ResourceNotFound,
71    /// OS-level permission denied (file permissions, EACCES, EPERM)
72    PermissionDenied,
73    /// Policy violation (workspace boundary, tool deny policy, safety gate)
74    PolicyViolation,
75    /// Planning workflow violation (mutating tool without read-only capabilities)
76    PlanningPolicyViolation,
77    /// Sandbox execution failure
78    SandboxFailure,
79    /// Resource exhausted (quota, billing, spending limit, disk, memory)
80    ResourceExhausted,
81    /// User cancelled the operation
82    Cancelled,
83    /// General execution error (catch-all for unclassified failures)
84    ExecutionError,
85}
86
87/// Describes whether and how an error can be retried.
88#[derive(Debug, Clone, PartialEq, Eq)]
89pub enum Retryability {
90    /// Error is transient and may succeed on retry.
91    Retryable {
92        /// Suggested maximum retry attempts.
93        max_attempts: u32,
94        /// Suggested backoff strategy.
95        backoff: BackoffStrategy,
96    },
97    /// Error is permanent and should NOT be retried.
98    NonRetryable,
99    /// Error requires human intervention before proceeding.
100    RequiresIntervention,
101}
102
103/// Backoff strategy for retryable errors.
104#[derive(Debug, Clone, PartialEq, Eq)]
105pub enum BackoffStrategy {
106    /// Exponential backoff with base delay and maximum cap.
107    Exponential { base: Duration, max: Duration },
108    /// Fixed delay between retries (e.g., for rate-limited APIs with Retry-After).
109    Fixed(Duration),
110}
111
112impl ErrorCategory {
113    /// Return the category as a `&'static str`, avoiding the temporary
114    /// `String` allocation that `to_string()` (via `Display`) would create.
115    /// Equivalent to `user_label()` but named to match the conventional
116    /// `as_str()` accessor used across the codebase.
117    #[inline]
118    #[must_use]
119    pub const fn as_str(&self) -> &'static str {
120        self.user_label()
121    }
122
123    /// Whether this error category is safe to retry.
124    #[inline]
125    #[must_use]
126    pub const fn is_retryable(&self) -> bool {
127        matches!(
128            self,
129            ErrorCategory::Network
130                | ErrorCategory::Timeout
131                | ErrorCategory::RateLimit
132                | ErrorCategory::ServiceUnavailable
133                | ErrorCategory::CircuitOpen
134        )
135    }
136
137    /// Whether this category should count toward circuit breaker transitions.
138    #[inline]
139    #[must_use]
140    pub const fn should_trip_circuit_breaker(&self) -> bool {
141        matches!(
142            self,
143            ErrorCategory::Network
144                | ErrorCategory::Timeout
145                | ErrorCategory::RateLimit
146                | ErrorCategory::ServiceUnavailable
147                | ErrorCategory::ExecutionError
148        )
149    }
150
151    /// Whether this error is an LLM argument mistake (should not count toward
152    /// circuit breaker thresholds).
153    #[inline]
154    #[must_use]
155    const fn is_llm_mistake(&self) -> bool {
156        matches!(self, ErrorCategory::InvalidParameters)
157    }
158
159    /// Whether this error represents a permanent, non-recoverable condition.
160    #[inline]
161    #[must_use]
162    pub const fn is_permanent(&self) -> bool {
163        matches!(
164            self,
165            ErrorCategory::Authentication
166                | ErrorCategory::PolicyViolation
167                | ErrorCategory::PlanningPolicyViolation
168                | ErrorCategory::ResourceExhausted
169        )
170    }
171
172    /// Get the recommended retryability for this error category.
173    #[must_use]
174    pub fn retryability(&self) -> Retryability {
175        match self {
176            ErrorCategory::Network | ErrorCategory::ServiceUnavailable => Retryability::Retryable {
177                max_attempts: 3,
178                backoff: BackoffStrategy::Exponential {
179                    base: Duration::from_millis(500),
180                    max: Duration::from_secs(10),
181                },
182            },
183            ErrorCategory::Timeout => Retryability::Retryable {
184                max_attempts: 2,
185                backoff: BackoffStrategy::Exponential {
186                    base: Duration::from_millis(1000),
187                    max: Duration::from_secs(15),
188                },
189            },
190            ErrorCategory::RateLimit => Retryability::Retryable {
191                max_attempts: 3,
192                backoff: BackoffStrategy::Exponential {
193                    base: Duration::from_secs(1),
194                    max: Duration::from_secs(30),
195                },
196            },
197            ErrorCategory::CircuitOpen => Retryability::Retryable {
198                max_attempts: 1,
199                backoff: BackoffStrategy::Fixed(Duration::from_secs(10)),
200            },
201            ErrorCategory::PermissionDenied => Retryability::RequiresIntervention,
202            _ => Retryability::NonRetryable,
203        }
204    }
205
206    /// Get a concise, user-friendly label for this error category.
207    #[must_use]
208    pub const fn user_label(&self) -> &'static str {
209        match self {
210            ErrorCategory::Network => "Network error",
211            ErrorCategory::Timeout => "Request timed out",
212            ErrorCategory::RateLimit => "Rate limit exceeded",
213            ErrorCategory::ServiceUnavailable => "Service temporarily unavailable",
214            ErrorCategory::CircuitOpen => "Tool temporarily disabled",
215            ErrorCategory::Authentication => "Authentication failed",
216            ErrorCategory::InvalidParameters => "Invalid parameters",
217            ErrorCategory::ToolNotFound => "Tool not found",
218            ErrorCategory::ResourceNotFound => "Resource not found",
219            ErrorCategory::PermissionDenied => "Permission denied",
220            ErrorCategory::PolicyViolation => "Blocked by policy",
221            ErrorCategory::PlanningPolicyViolation => "Not allowed in planning workflow",
222            ErrorCategory::SandboxFailure => "Sandbox denied",
223            ErrorCategory::ResourceExhausted => "Resource limit reached",
224            ErrorCategory::Cancelled => "Operation cancelled",
225            ErrorCategory::ExecutionError => "Execution failed",
226        }
227    }
228
229    /// Build actionable guidance for authentication errors.
230    ///
231    /// Returns a single combined line directing the user to `/secret` (API-key
232    /// providers) or `/login` (managed-auth providers). When the rejected
233    /// credential's source is known, the line names it: resolution precedence
234    /// is process environment, then workspace `.env`, then secure storage, so
235    /// a stale export defeats `/secret add` until it is fixed or unset —
236    /// sending the user to secure storage without that note loops forever.
237    ///
238    /// `has_credential` distinguishes "no key at all" (needs `/secret add`)
239    /// from "a credential exists but the API rejected it" (needs verification
240    /// at its source). `rejected_source` names that source when discovery
241    /// found it; `None` keeps the source-neutral wording.
242    #[must_use]
243    pub fn auth_recovery_guidance(
244        &self,
245        provider_label: &str,
246        provider_key: &str,
247        is_managed_auth: bool,
248        has_credential: bool,
249        rejected_source: Option<RejectedCredentialSource>,
250    ) -> Vec<String> {
251        if !matches!(self, ErrorCategory::Authentication) {
252            return vec![];
253        }
254
255        if is_managed_auth {
256            return vec![format!(
257                "Authentication failed for {provider_label}. Run /login {provider_key} to re-authenticate."
258            )];
259        }
260        if !has_credential {
261            return vec![format!(
262                "Authentication failed for {provider_label}. Run /secret add {provider_key} to store your API key in secure storage (OS keyring or encrypted file)."
263            )];
264        }
265        match rejected_source {
266            Some(RejectedCredentialSource::Environment { env_var }) => vec![format!(
267                "Authentication failed for {provider_label}. The rejected key came from {} in the process environment, which shadows the workspace `.env` file and secure storage — check the export, or unset it so the next source applies.",
268                env_var.map_or_else(|| "a custom variable".to_string(), |name| format!("`{name}`"))
269            )],
270            Some(RejectedCredentialSource::WorkspaceDotEnv { env_var }) => vec![format!(
271                "Authentication failed for {provider_label}. The rejected key came from {} — check the value there.",
272                env_var.map_or_else(
273                    || "the workspace `.env` file".to_string(),
274                    |name| format!("`{name}` in the workspace `.env` file")
275                )
276            )],
277            Some(RejectedCredentialSource::SecureStorage) => vec![format!(
278                "Authentication failed for {provider_label}. The stored API key was rejected — run /secret add {provider_key} to replace it with a valid key."
279            )],
280            None => vec![format!(
281                "Authentication failed for {provider_label}. The configured credential was rejected — verify the value, or run /secret add {provider_key} to store a fresh key."
282            )],
283        }
284    }
285}
286
287impl fmt::Display for ErrorCategory {
288    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
289        f.write_str(self.user_label())
290    }
291}
292
293// ---------------------------------------------------------------------------
294// Classify from anyhow::Error (string-based fallback for erased types)
295// ---------------------------------------------------------------------------
296
297/// Classify an `anyhow::Error` into a canonical `ErrorCategory`.
298///
299/// This uses string matching as a last resort when the original error type has
300/// been erased through `anyhow` wrapping. Typed conversions (e.g., `From<LLMError>`)
301/// should be preferred where the original error type is available.
302///
303/// Recovery decisions are made by *type* when it survives the `anyhow`
304/// boundary. The outermost context layer is classified first (preserving the
305/// intentional wording of a deliberate `.context(...)`), but when that layer is
306/// uninformative we consult the typed root and then the remaining cause chain.
307/// Without this, a wrapping `.context("...")` message alone would hide the
308/// underlying category — e.g. an `LLMError::RateLimit` buried under
309/// `"compaction failed"` would fall through to `ExecutionError` and lose its
310/// retry/recovery policy.
311#[must_use]
312pub fn classify_anyhow_error(err: &anyhow::Error) -> ErrorCategory {
313    // Fast path: the outermost message is usually the most specific context and
314    // matches the historical behavior exactly.
315    let outer = classify_error_message(&err.to_string());
316    if outer != ErrorCategory::ExecutionError {
317        return outer;
318    }
319
320    // The outer context was uninformative (or absent). Prefer the typed source
321    // of truth when it survived the boundary, then fall back to the deeper
322    // cause chain (`innermost` markers such as `connection reset`).
323    if let Some(llm_error) = err.downcast_ref::<crate::llm::LLMError>() {
324        return ErrorCategory::from(llm_error);
325    }
326
327    for cause in err.chain().skip(1) {
328        let category = classify_error_message(&cause.to_string());
329        if category != ErrorCategory::ExecutionError {
330            return category;
331        }
332    }
333
334    ErrorCategory::ExecutionError
335}
336
337/// Return whether an error explicitly reports that the provider rejected the
338/// request because its input context is too large.
339///
340/// Context-capacity failures are intentionally kept separate from
341/// [`ErrorCategory::InvalidParameters`]: they are not model argument mistakes
342/// and a bounded history compaction can make the same request valid. The
343/// marker set is deliberately specific so ordinary validation messages that
344/// merely mention a context field do not enter recovery.
345#[must_use]
346pub fn is_context_capacity_error(err: &anyhow::Error) -> bool {
347    err.chain().any(|cause| is_context_capacity_message(&cause.to_string()))
348}
349
350/// Return whether a provider error message identifies an input-context limit.
351#[must_use]
352pub fn is_context_capacity_message(message: &str) -> bool {
353    let message = message.to_ascii_lowercase();
354    contains_any(
355        &message,
356        &[
357            "context_length_exceeded",
358            "context length exceeded",
359            "maximum context length",
360            "maximum context window",
361            "context window exceeded",
362            "context window is too small",
363            "exceeds the model's maximum context",
364            "exceeds model context",
365            "exceeds the maximum context",
366            "prompt is too long",
367            "input is too long",
368            "input token count exceeds",
369            "exceeds the maximum number of tokens",
370            "maximum input tokens",
371            "too many tokens in the prompt",
372            "request exceeds the context",
373            // Merge-gateway / Anthropic / OpenAI variants observed on
374            // near-budget follow-ups (e.g. ~956k prompt on a 1M budget) that
375            // previously fell through to generic `ExecutionError` and missed
376            // the compacting tool-enabled recovery path.
377            "context limit exceeded",
378            "context size exceeded",
379            "exceeds context",
380            "input tokens exceed",
381            "prompt tokens exceed",
382            "prompt token count exceeds",
383            "token limit exceeded",
384            "input too large",
385            "prompt too large",
386        ],
387    )
388}
389
390/// Classify an error message string into an `ErrorCategory`.
391///
392/// Marker groups are checked in priority order to handle overlapping patterns
393/// (e.g., "tool permission denied by policy" → `PolicyViolation`, not `PermissionDenied`).
394#[inline]
395#[must_use]
396pub fn classify_error_message(msg: &str) -> ErrorCategory {
397    let msg = if msg.as_bytes().iter().any(|b| b.is_ascii_uppercase()) {
398        Cow::Owned(msg.to_ascii_lowercase())
399    } else {
400        Cow::Borrowed(msg)
401    };
402
403    // --- Priority 1: Policy violations (before permission checks) ---
404    if contains_any(
405        &msg,
406        &[
407            "policy violation",
408            "denied by policy",
409            "tool permission denied",
410            "safety validation failed",
411            "not allowed in planning workflow",
412            "only available when planning workflow is active",
413            "workspace boundary",
414            "blocked by policy",
415        ],
416    ) {
417        return ErrorCategory::PolicyViolation;
418    }
419
420    // --- Priority 2: Planning workflow violations ---
421    if contains_any(
422        &msg,
423        &[
424            "planning workflow",
425            "read-only permissions",
426            concat!("read-only ", "mode"),
427            "planning_policy_violation",
428        ],
429    ) {
430        return ErrorCategory::PlanningPolicyViolation;
431    }
432
433    // --- Priority 3: Authentication / Authorization ---
434    if contains_any(
435        &msg,
436        &[
437            "invalid api key",
438            "authentication failed",
439            "unauthorized",
440            "401",
441            "invalid credentials",
442        ],
443    ) {
444        return ErrorCategory::Authentication;
445    }
446
447    // --- Priority 4: Non-retryable resource exhaustion (billing, quotas) ---
448    if contains_any(
449        &msg,
450        &[
451            "weekly usage limit",
452            "daily usage limit",
453            "monthly spending limit",
454            "insufficient credits",
455            "quota exceeded",
456            "billing",
457            "payment required",
458        ],
459    ) {
460        return ErrorCategory::ResourceExhausted;
461    }
462
463    // --- Priority 5: Invalid parameters ---
464    if contains_any(
465        &msg,
466        &[
467            "invalid argument",
468            "invalid parameters",
469            "invalid type",
470            "malformed",
471            "failed to parse arguments",
472            "failed to parse argument",
473            "missing required",
474            "at least one item is required",
475            "is required for",
476            "schema validation",
477            "argument validation failed",
478            "unknown field",
479            "unknown variant",
480            "expected struct",
481            "expected enum",
482            "type mismatch",
483            "must be an absolute path",
484            "not parseable",
485            "parseable as",
486            // Patch format errors — these are LLM argument mistakes (the model
487            // sent a malformed patch), not execution failures. Classifying them
488            // as InvalidParameters ensures they don't trip the circuit breaker
489            // (is_llm_mistake() == true) and get parameter-focused recovery
490            // suggestions. See checkpoint turn_615 for the failure this
491            // prevents: a unified-diff patch was classified as ExecutionError
492            // and got generic "check tool documentation" suggestions.
493            "invalid patch format",
494            "invalid patch hunk",
495            "invalid patch operation",
496            "cannot parse empty patch",
497            "patch does not contain",
498            "semantic patch anchor",
499        ],
500    ) {
501        return ErrorCategory::InvalidParameters;
502    }
503
504    // --- Priority 6: Tool not found ---
505    if contains_any(&msg, &["tool not found", "unknown tool", "unsupported tool", "no such tool"]) {
506        return ErrorCategory::ToolNotFound;
507    }
508
509    // --- Priority 7: Resource not found ---
510    if contains_any(
511        &msg,
512        &[
513            "no such file",
514            "no such directory",
515            "file not found",
516            "directory not found",
517            "resource not found",
518            "path not found",
519            "does not exist",
520            "enoent",
521        ],
522    ) {
523        return ErrorCategory::ResourceNotFound;
524    }
525
526    // --- Priority 8: Permission denied (OS-level) ---
527    if contains_any(
528        &msg,
529        &[
530            "permission denied",
531            "access denied",
532            "operation not permitted",
533            "eacces",
534            "eperm",
535            "forbidden",
536            "403",
537        ],
538    ) {
539        return ErrorCategory::PermissionDenied;
540    }
541
542    // --- Priority 9: Cancellation ---
543    if contains_any(&msg, &["cancelled", "interrupted", "canceled"]) {
544        return ErrorCategory::Cancelled;
545    }
546
547    // --- Priority 10: Circuit breaker ---
548    if contains_any(&msg, &["circuit breaker", "circuit open"]) {
549        return ErrorCategory::CircuitOpen;
550    }
551
552    // --- Priority 11: Sandbox ---
553    if contains_any(&msg, &["sandbox denied", "sandbox failure"]) {
554        return ErrorCategory::SandboxFailure;
555    }
556
557    // --- Priority 12: Rate limiting (before general network) ---
558    if contains_any(&msg, &["rate limit", "too many requests", "429", "throttl"]) {
559        return ErrorCategory::RateLimit;
560    }
561
562    // --- Priority 13: Timeout ---
563    if contains_any(&msg, &["timeout", "timed out", "deadline exceeded"]) {
564        return ErrorCategory::Timeout;
565    }
566
567    // --- Priority 14: Provider transient response-shape failures ---
568    if contains_any(
569        &msg,
570        &[
571            "invalid response format: missing choices",
572            "invalid response format: missing message",
573            "missing choices in response",
574            "missing message in choice",
575            "no choices in response",
576            "invalid response from ",
577            "empty response body",
578            "response did not contain",
579            "unexpected response format",
580            "failed to parse response",
581            // Post-tool follow-up streaming failures surface here when the
582            // provider drops the SSE/event stream mid-response. Without these
583            // markers the follow-up is misclassified as generic
584            // `ExecutionError` (non-retryable) and the turn ends instead of
585            // scheduling the bounded tool-free retry.
586            "stream disconnected",
587            "stream closed unexpectedly",
588            "incomplete stream",
589            "unexpected end of stream",
590            "truncated response",
591            "failed to decode stream",
592            "stream terminated",
593        ],
594    ) {
595        return ErrorCategory::ServiceUnavailable;
596    }
597
598    // --- Priority 15: Fail-closed stream bounds (non-retryable) ---
599    // The SSE tail overflow names its bound ("without an event boundary")
600    // and embeds the retained byte count, whose digits can contain status
601    // substrings ("500") — classification must not depend on the count. A
602    // peer that withholds event boundaries reproduces the failure on
603    // retry, so fail fast instead of scheduling bounded request retries.
604    if contains_any(&msg, &["without an event boundary"]) {
605        return ErrorCategory::ExecutionError;
606    }
607
608    // --- Priority 16: Service unavailable (HTTP 5xx and related) ---
609    if contains_any(
610        &msg,
611        &[
612            "service unavailable",
613            "temporarily unavailable",
614            "internal server error",
615            "bad gateway",
616            "gateway timeout",
617            "overloaded",
618            "500",
619            "502",
620            "503",
621            "504",
622        ],
623    ) {
624        return ErrorCategory::ServiceUnavailable;
625    }
626
627    // --- Priority 17: Network (connectivity, DNS, transport) ---
628    if contains_any(
629        &msg,
630        &[
631            "network",
632            "connection reset",
633            "connection refused",
634            "broken pipe",
635            "dns",
636            "name resolution",
637            "try again",
638            "retry later",
639            "upstream connect error",
640            "tls handshake",
641            "socket hang up",
642            "econnreset",
643            "etimedout",
644            // reqwest surfaces truncated/aborted response streams as a body
645            // decode failure; Ollama (cloud) emits this on transient drops.
646            // It is a transport error, not a payload problem — retryable.
647            "error decoding response body",
648            // Transport-level stream teardown during a follow-up request.
649            // Distinct from response-shape markers above: the connection
650            // itself failed, not the payload. `stream error` stays specific
651            // (`received`) so `downstream error` prose does not match.
652            "connection closed before",
653            "stream reset",
654            "stream error received",
655        ],
656    ) {
657        return ErrorCategory::Network;
658    }
659
660    // --- Priority 18: Resource exhausted (memory, disk) ---
661    if contains_any(&msg, &["out of memory", "disk full", "no space left"]) {
662        return ErrorCategory::ResourceExhausted;
663    }
664
665    // --- Fallback ---
666    ErrorCategory::ExecutionError
667}
668
669/// Check if an LLM error message is retryable (used by the LLM request retry loop).
670///
671/// This is a focused classifier for LLM provider errors, combining
672/// non-retryable and retryable marker checks for the request retry path.
673#[inline]
674#[must_use]
675pub fn is_retryable_llm_error_message(msg: &str) -> bool {
676    let category = classify_error_message(msg);
677    category.is_retryable()
678}
679
680#[inline]
681fn contains_any(message: &str, markers: &[&str]) -> bool {
682    markers.iter().any(|marker| message.contains(marker))
683}
684
685// ---------------------------------------------------------------------------
686// Typed conversions from known error types
687// ---------------------------------------------------------------------------
688
689impl From<&crate::llm::LLMError> for ErrorCategory {
690    fn from(err: &crate::llm::LLMError) -> Self {
691        match err {
692            crate::llm::LLMError::Authentication { .. } => ErrorCategory::Authentication,
693            crate::llm::LLMError::RateLimit { metadata } => {
694                classify_llm_metadata(metadata.as_deref(), ErrorCategory::RateLimit)
695            }
696            crate::llm::LLMError::InvalidRequest { .. } => ErrorCategory::InvalidParameters,
697            crate::llm::LLMError::Network { .. } => ErrorCategory::Network,
698            crate::llm::LLMError::Provider { message, metadata } => {
699                let metadata_category = classify_llm_metadata(metadata.as_deref(), ErrorCategory::ExecutionError);
700                if metadata_category != ErrorCategory::ExecutionError {
701                    return metadata_category;
702                }
703
704                // Check metadata status code first for precise classification
705                if let Some(meta) = metadata
706                    && let Some(status) = meta.status
707                {
708                    return match status {
709                        401 => ErrorCategory::Authentication,
710                        403 => ErrorCategory::PermissionDenied,
711                        404 => ErrorCategory::ResourceNotFound,
712                        429 => ErrorCategory::RateLimit,
713                        400 => ErrorCategory::InvalidParameters,
714                        500 | 502 | 503 | 504 | 529 => ErrorCategory::ServiceUnavailable,
715                        408 => ErrorCategory::Timeout,
716                        _ => classify_error_message(message),
717                    };
718                }
719                // Fall back to message-based classification
720                classify_error_message(message)
721            }
722        }
723    }
724}
725
726fn classify_llm_metadata(metadata: Option<&crate::llm::LLMErrorMetadata>, fallback: ErrorCategory) -> ErrorCategory {
727    let Some(metadata) = metadata else {
728        return fallback;
729    };
730
731    let mut hint = String::new();
732    if let Some(code) = &metadata.code {
733        hint.push_str(code);
734        hint.push(' ');
735    }
736    if let Some(message) = &metadata.message {
737        hint.push_str(message);
738        hint.push(' ');
739    }
740    if let Some(status) = metadata.status {
741        let _ = write!(&mut hint, "{status}");
742    }
743
744    let classified = classify_error_message(&hint);
745    if classified == ErrorCategory::ExecutionError {
746        fallback
747    } else {
748        classified
749    }
750}
751
752mod recovery;
753#[cfg(test)]
754mod tests;