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    // A typed denial decides the category by type, whatever its wording and
314    // however many `.context(...)` layers wrap it.
315    if let Some(denial) = err.downcast_ref::<SafeguardDenial>() {
316        return denial.kind().category();
317    }
318    // Fast path: the outermost message is usually the most specific context and
319    // matches the historical behavior exactly.
320    let outer = classify_error_message(&err.to_string());
321    if outer != ErrorCategory::ExecutionError {
322        return outer;
323    }
324
325    // The outer context was uninformative (or absent). Prefer the typed source
326    // of truth when it survived the boundary, then fall back to the deeper
327    // cause chain (`innermost` markers such as `connection reset`).
328    if let Some(llm_error) = err.downcast_ref::<crate::llm::LLMError>() {
329        return ErrorCategory::from(llm_error);
330    }
331
332    for cause in err.chain().skip(1) {
333        let category = classify_error_message(&cause.to_string());
334        if category != ErrorCategory::ExecutionError {
335            return category;
336        }
337    }
338
339    ErrorCategory::ExecutionError
340}
341
342/// Return whether an error explicitly reports that the provider rejected the
343/// request because its input context is too large.
344///
345/// Context-capacity failures are intentionally kept separate from
346/// [`ErrorCategory::InvalidParameters`]: they are not model argument mistakes
347/// and a bounded history compaction can make the same request valid. The
348/// marker set is deliberately specific so ordinary validation messages that
349/// merely mention a context field do not enter recovery.
350#[must_use]
351pub fn is_context_capacity_error(err: &anyhow::Error) -> bool {
352    err.chain().any(|cause| is_context_capacity_message(&cause.to_string()))
353}
354
355/// Return whether a provider error message identifies an input-context limit.
356#[must_use]
357pub fn is_context_capacity_message(message: &str) -> bool {
358    let message = message.to_ascii_lowercase();
359    contains_any(
360        &message,
361        &[
362            "context_length_exceeded",
363            "context length exceeded",
364            "maximum context length",
365            "maximum context window",
366            "context window exceeded",
367            "context window is too small",
368            "exceeds the model's maximum context",
369            "exceeds model context",
370            "exceeds the maximum context",
371            "prompt is too long",
372            "input is too long",
373            "input token count exceeds",
374            "exceeds the maximum number of tokens",
375            "maximum input tokens",
376            "too many tokens in the prompt",
377            "request exceeds the context",
378            // Merge-gateway / Anthropic / OpenAI variants observed on
379            // near-budget follow-ups (e.g. ~956k prompt on a 1M budget) that
380            // previously fell through to generic `ExecutionError` and missed
381            // the compacting tool-enabled recovery path.
382            "context limit exceeded",
383            "context size exceeded",
384            "exceeds context",
385            "input tokens exceed",
386            "prompt tokens exceed",
387            "prompt token count exceeds",
388            "token limit exceeded",
389            "input too large",
390            "prompt too large",
391        ],
392    )
393}
394
395/// Classify an error message string into an `ErrorCategory`.
396///
397/// Marker groups are checked in priority order to handle overlapping patterns
398/// (e.g., "tool permission denied by policy" → `PolicyViolation`, not `PermissionDenied`).
399#[inline]
400#[must_use]
401pub fn classify_error_message(msg: &str) -> ErrorCategory {
402    let msg = if msg.as_bytes().iter().any(|b| b.is_ascii_uppercase()) {
403        Cow::Owned(msg.to_ascii_lowercase())
404    } else {
405        Cow::Borrowed(msg)
406    };
407
408    // --- Priority 1: Policy violations (before permission checks) ---
409    if contains_any(
410        &msg,
411        &[
412            "policy violation",
413            "denied by policy",
414            "tool permission denied",
415            "safety validation failed",
416            "not allowed in planning workflow",
417            "only available when planning workflow is active",
418            "workspace boundary",
419            "blocked by policy",
420        ],
421    ) {
422        return ErrorCategory::PolicyViolation;
423    }
424
425    // --- Priority 2: Planning workflow violations ---
426    if contains_any(
427        &msg,
428        &[
429            "planning workflow",
430            "read-only permissions",
431            concat!("read-only ", "mode"),
432            "planning_policy_violation",
433        ],
434    ) {
435        return ErrorCategory::PlanningPolicyViolation;
436    }
437
438    // --- Priority 3: Authentication / Authorization ---
439    if contains_any(
440        &msg,
441        &[
442            "invalid api key",
443            "authentication failed",
444            "unauthorized",
445            "401",
446            "invalid credentials",
447        ],
448    ) {
449        return ErrorCategory::Authentication;
450    }
451
452    // --- Priority 4: Non-retryable resource exhaustion (billing, quotas) ---
453    if contains_any(
454        &msg,
455        &[
456            "weekly usage limit",
457            "daily usage limit",
458            "monthly spending limit",
459            "insufficient credits",
460            "quota exceeded",
461            "billing",
462            "payment required",
463        ],
464    ) {
465        return ErrorCategory::ResourceExhausted;
466    }
467
468    // --- Priority 5: Invalid parameters ---
469    if contains_any(
470        &msg,
471        &[
472            "invalid argument",
473            "invalid parameters",
474            "invalid type",
475            "malformed",
476            "failed to parse arguments",
477            "failed to parse argument",
478            "missing required",
479            "at least one item is required",
480            "is required for",
481            "schema validation",
482            "argument validation failed",
483            "unknown field",
484            "unknown variant",
485            "expected struct",
486            "expected enum",
487            "type mismatch",
488            "must be an absolute path",
489            "not parseable",
490            "parseable as",
491            // Patch format errors — these are LLM argument mistakes (the model
492            // sent a malformed patch), not execution failures. Classifying them
493            // as InvalidParameters ensures they don't trip the circuit breaker
494            // (is_llm_mistake() == true) and get parameter-focused recovery
495            // suggestions. See checkpoint turn_615 for the failure this
496            // prevents: a unified-diff patch was classified as ExecutionError
497            // and got generic "check tool documentation" suggestions.
498            "invalid patch format",
499            "invalid patch hunk",
500            "invalid patch operation",
501            "cannot parse empty patch",
502            "patch does not contain",
503            "semantic patch anchor",
504        ],
505    ) {
506        return ErrorCategory::InvalidParameters;
507    }
508
509    // --- Priority 6: Tool not found ---
510    if contains_any(&msg, &["tool not found", "unknown tool", "unsupported tool", "no such tool"]) {
511        return ErrorCategory::ToolNotFound;
512    }
513
514    // --- Priority 7: Resource not found ---
515    if contains_any(
516        &msg,
517        &[
518            "no such file",
519            "no such directory",
520            "file not found",
521            "directory not found",
522            "resource not found",
523            "path not found",
524            "does not exist",
525            "enoent",
526        ],
527    ) {
528        return ErrorCategory::ResourceNotFound;
529    }
530
531    // --- Priority 8: Permission denied (OS-level) ---
532    if contains_any(
533        &msg,
534        &[
535            "permission denied",
536            "access denied",
537            "operation not permitted",
538            "eacces",
539            "eperm",
540            "forbidden",
541            "403",
542        ],
543    ) {
544        return ErrorCategory::PermissionDenied;
545    }
546
547    // --- Priority 9: Cancellation ---
548    if contains_any(&msg, &["cancelled", "interrupted", "canceled"]) {
549        return ErrorCategory::Cancelled;
550    }
551
552    // --- Priority 10: Circuit breaker ---
553    if contains_any(&msg, &["circuit breaker", "circuit open"]) {
554        return ErrorCategory::CircuitOpen;
555    }
556
557    // --- Priority 11: Sandbox ---
558    if contains_any(&msg, &["sandbox denied", "sandbox failure"]) {
559        return ErrorCategory::SandboxFailure;
560    }
561
562    // --- Priority 12: Rate limiting (before general network) ---
563    if contains_any(&msg, &["rate limit", "too many requests", "429", "throttl"]) {
564        return ErrorCategory::RateLimit;
565    }
566
567    // --- Priority 13: Timeout ---
568    if contains_any(&msg, &["timeout", "timed out", "deadline exceeded"]) {
569        return ErrorCategory::Timeout;
570    }
571
572    // --- Priority 14: Provider transient response-shape failures ---
573    if contains_any(
574        &msg,
575        &[
576            "invalid response format: missing choices",
577            "invalid response format: missing message",
578            "missing choices in response",
579            "missing message in choice",
580            "no choices in response",
581            "invalid response from ",
582            "empty response body",
583            "response did not contain",
584            "unexpected response format",
585            "failed to parse response",
586            // Post-tool follow-up streaming failures surface here when the
587            // provider drops the SSE/event stream mid-response. Without these
588            // markers the follow-up is misclassified as generic
589            // `ExecutionError` (non-retryable) and the turn ends instead of
590            // scheduling the bounded tool-free retry.
591            "stream disconnected",
592            "stream closed unexpectedly",
593            "incomplete stream",
594            "unexpected end of stream",
595            "truncated response",
596            "failed to decode stream",
597            "stream terminated",
598        ],
599    ) {
600        return ErrorCategory::ServiceUnavailable;
601    }
602
603    // --- Priority 15: Fail-closed stream bounds (non-retryable) ---
604    // The SSE tail overflow names its bound ("without an event boundary")
605    // and embeds the retained byte count, whose digits can contain status
606    // substrings ("500") — classification must not depend on the count. A
607    // peer that withholds event boundaries reproduces the failure on
608    // retry, so fail fast instead of scheduling bounded request retries.
609    if contains_any(&msg, &["without an event boundary"]) {
610        return ErrorCategory::ExecutionError;
611    }
612
613    // --- Priority 16: Service unavailable (HTTP 5xx and related) ---
614    if contains_any(
615        &msg,
616        &[
617            "service unavailable",
618            "temporarily unavailable",
619            "internal server error",
620            "bad gateway",
621            "gateway timeout",
622            "overloaded",
623            "500",
624            "502",
625            "503",
626            "504",
627        ],
628    ) {
629        return ErrorCategory::ServiceUnavailable;
630    }
631
632    // --- Priority 17: Network (connectivity, DNS, transport) ---
633    if contains_any(
634        &msg,
635        &[
636            "network",
637            "connection reset",
638            "connection refused",
639            "broken pipe",
640            "dns",
641            "name resolution",
642            "try again",
643            "retry later",
644            "upstream connect error",
645            "tls handshake",
646            "socket hang up",
647            "econnreset",
648            "etimedout",
649            // reqwest surfaces truncated/aborted response streams as a body
650            // decode failure; Ollama (cloud) emits this on transient drops.
651            // It is a transport error, not a payload problem — retryable.
652            "error decoding response body",
653            // Transport-level stream teardown during a follow-up request.
654            // Distinct from response-shape markers above: the connection
655            // itself failed, not the payload. `stream error` stays specific
656            // (`received`) so `downstream error` prose does not match.
657            "connection closed before",
658            "stream reset",
659            "stream error received",
660        ],
661    ) {
662        return ErrorCategory::Network;
663    }
664
665    // --- Priority 18: Resource exhausted (memory, disk) ---
666    if contains_any(&msg, &["out of memory", "disk full", "no space left"]) {
667        return ErrorCategory::ResourceExhausted;
668    }
669
670    // --- Fallback ---
671    ErrorCategory::ExecutionError
672}
673
674/// Check if an LLM error message is retryable (used by the LLM request retry loop).
675///
676/// This is a focused classifier for LLM provider errors, combining
677/// non-retryable and retryable marker checks for the request retry path.
678#[inline]
679#[must_use]
680pub fn is_retryable_llm_error_message(msg: &str) -> bool {
681    let category = classify_error_message(msg);
682    category.is_retryable()
683}
684
685#[inline]
686fn contains_any(message: &str, markers: &[&str]) -> bool {
687    markers.iter().any(|marker| message.contains(marker))
688}
689
690// ---------------------------------------------------------------------------
691// Typed conversions from known error types
692// ---------------------------------------------------------------------------
693
694impl From<&crate::llm::LLMError> for ErrorCategory {
695    fn from(err: &crate::llm::LLMError) -> Self {
696        match err {
697            crate::llm::LLMError::Authentication { .. } => ErrorCategory::Authentication,
698            crate::llm::LLMError::RateLimit { metadata } => {
699                classify_llm_metadata(metadata.as_deref(), ErrorCategory::RateLimit)
700            }
701            crate::llm::LLMError::InvalidRequest { .. } => ErrorCategory::InvalidParameters,
702            crate::llm::LLMError::Network { .. } => ErrorCategory::Network,
703            crate::llm::LLMError::Provider { message, metadata } => {
704                let metadata_category = classify_llm_metadata(metadata.as_deref(), ErrorCategory::ExecutionError);
705                if metadata_category != ErrorCategory::ExecutionError {
706                    return metadata_category;
707                }
708
709                // Check metadata status code first for precise classification
710                if let Some(meta) = metadata
711                    && let Some(status) = meta.status
712                {
713                    return match status {
714                        401 => ErrorCategory::Authentication,
715                        403 => ErrorCategory::PermissionDenied,
716                        404 => ErrorCategory::ResourceNotFound,
717                        429 => ErrorCategory::RateLimit,
718                        400 => ErrorCategory::InvalidParameters,
719                        500 | 502 | 503 | 504 | 529 => ErrorCategory::ServiceUnavailable,
720                        408 => ErrorCategory::Timeout,
721                        _ => classify_error_message(message),
722                    };
723                }
724                // Fall back to message-based classification
725                classify_error_message(message)
726            }
727        }
728    }
729}
730
731fn classify_llm_metadata(metadata: Option<&crate::llm::LLMErrorMetadata>, fallback: ErrorCategory) -> ErrorCategory {
732    let Some(metadata) = metadata else {
733        return fallback;
734    };
735
736    let mut hint = String::new();
737    if let Some(code) = &metadata.code {
738        hint.push_str(code);
739        hint.push(' ');
740    }
741    if let Some(message) = &metadata.message {
742        hint.push_str(message);
743        hint.push(' ');
744    }
745    if let Some(status) = metadata.status {
746        let _ = write!(&mut hint, "{status}");
747    }
748
749    let classified = classify_error_message(&hint);
750    if classified == ErrorCategory::ExecutionError {
751        fallback
752    } else {
753        classified
754    }
755}
756
757mod recovery;
758mod safeguard;
759pub use safeguard::{SafeguardDenial, SafeguardKind};
760#[cfg(test)]
761mod tests;