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 recovery suggestions for this error category.
207    /// Returns static strings to avoid allocation.
208    #[must_use]
209    pub fn recovery_suggestions(&self) -> Vec<Cow<'static, str>> {
210        match self {
211            ErrorCategory::Network => vec![
212                Cow::Borrowed("Check network connectivity"),
213                Cow::Borrowed("Retry the operation after a brief delay"),
214                Cow::Borrowed("Verify external service availability"),
215            ],
216            ErrorCategory::Timeout => vec![
217                Cow::Borrowed("Increase timeout values if appropriate"),
218                Cow::Borrowed("Break large operations into smaller chunks"),
219                Cow::Borrowed("Check system resources and performance"),
220            ],
221            ErrorCategory::RateLimit => vec![
222                Cow::Borrowed("Wait before retrying the request"),
223                Cow::Borrowed("Reduce request frequency"),
224                Cow::Borrowed("Check provider rate limit documentation"),
225            ],
226            ErrorCategory::ServiceUnavailable => vec![
227                Cow::Borrowed("The service is temporarily unavailable"),
228                Cow::Borrowed("Retry after a brief delay"),
229                Cow::Borrowed("Check service status page if available"),
230            ],
231            ErrorCategory::CircuitOpen => vec![
232                Cow::Borrowed("This tool has been temporarily disabled due to repeated failures"),
233                Cow::Borrowed("Wait for the circuit breaker cooldown period"),
234                Cow::Borrowed("Try an alternative approach"),
235            ],
236            ErrorCategory::Authentication => vec![
237                Cow::Borrowed("Verify your API key or credentials"),
238                Cow::Borrowed("Check that your account is active and has sufficient permissions"),
239                Cow::Borrowed("Ensure environment variables for API keys are set correctly"),
240            ],
241            ErrorCategory::InvalidParameters => vec![
242                Cow::Borrowed("Check parameter names and types against the tool schema"),
243                Cow::Borrowed("Ensure required parameters are provided"),
244                Cow::Borrowed("Verify parameter values are within acceptable ranges"),
245            ],
246            ErrorCategory::ToolNotFound => vec![
247                Cow::Borrowed("Verify the tool name is spelled correctly"),
248                Cow::Borrowed("Check if the tool is available in the current context"),
249            ],
250            ErrorCategory::ResourceNotFound => vec![
251                Cow::Borrowed("Verify file paths and resource locations"),
252                Cow::Borrowed("Check if files exist and are accessible"),
253                Cow::Borrowed("Use list_dir to explore available resources"),
254            ],
255            ErrorCategory::PermissionDenied => vec![
256                Cow::Borrowed("Check file permissions and access rights"),
257                Cow::Borrowed("Ensure workspace boundaries are respected"),
258            ],
259            ErrorCategory::PolicyViolation => vec![
260                Cow::Borrowed("Review workspace policies and restrictions"),
261                Cow::Borrowed("Use alternative tools that comply with policies"),
262            ],
263            ErrorCategory::PlanningPolicyViolation => vec![
264                Cow::Borrowed("This operation is not allowed in the Planning workflow with read-only permissions"),
265                Cow::Borrowed("Exit the Planning workflow to perform mutating operations"),
266            ],
267            ErrorCategory::SandboxFailure => vec![
268                Cow::Borrowed("The sandbox denied this operation"),
269                Cow::Borrowed("Check sandbox configuration and permissions"),
270            ],
271            ErrorCategory::ResourceExhausted => vec![
272                Cow::Borrowed("Check your account usage limits and billing status"),
273                Cow::Borrowed("Review resource consumption and optimize if possible"),
274            ],
275            ErrorCategory::Cancelled => vec![Cow::Borrowed("The operation was cancelled")],
276            ErrorCategory::ExecutionError => vec![
277                Cow::Borrowed("Review error details for specific issues"),
278                Cow::Borrowed("Check tool documentation for known limitations"),
279            ],
280        }
281    }
282
283    /// Get a concise, user-friendly label for this error category.
284    #[must_use]
285    pub const fn user_label(&self) -> &'static str {
286        match self {
287            ErrorCategory::Network => "Network error",
288            ErrorCategory::Timeout => "Request timed out",
289            ErrorCategory::RateLimit => "Rate limit exceeded",
290            ErrorCategory::ServiceUnavailable => "Service temporarily unavailable",
291            ErrorCategory::CircuitOpen => "Tool temporarily disabled",
292            ErrorCategory::Authentication => "Authentication failed",
293            ErrorCategory::InvalidParameters => "Invalid parameters",
294            ErrorCategory::ToolNotFound => "Tool not found",
295            ErrorCategory::ResourceNotFound => "Resource not found",
296            ErrorCategory::PermissionDenied => "Permission denied",
297            ErrorCategory::PolicyViolation => "Blocked by policy",
298            ErrorCategory::PlanningPolicyViolation => "Not allowed in planning workflow",
299            ErrorCategory::SandboxFailure => "Sandbox denied",
300            ErrorCategory::ResourceExhausted => "Resource limit reached",
301            ErrorCategory::Cancelled => "Operation cancelled",
302            ErrorCategory::ExecutionError => "Execution failed",
303        }
304    }
305
306    /// Build actionable guidance for authentication errors.
307    ///
308    /// Returns a single combined line directing the user to `/secret` (API-key
309    /// providers) or `/login` (managed-auth providers). When the rejected
310    /// credential's source is known, the line names it: resolution precedence
311    /// is process environment, then workspace `.env`, then secure storage, so
312    /// a stale export defeats `/secret add` until it is fixed or unset —
313    /// sending the user to secure storage without that note loops forever.
314    ///
315    /// `has_credential` distinguishes "no key at all" (needs `/secret add`)
316    /// from "a credential exists but the API rejected it" (needs verification
317    /// at its source). `rejected_source` names that source when discovery
318    /// found it; `None` keeps the source-neutral wording.
319    #[must_use]
320    pub fn auth_recovery_guidance(
321        &self,
322        provider_label: &str,
323        provider_key: &str,
324        is_managed_auth: bool,
325        has_credential: bool,
326        rejected_source: Option<RejectedCredentialSource>,
327    ) -> Vec<String> {
328        if !matches!(self, ErrorCategory::Authentication) {
329            return vec![];
330        }
331
332        if is_managed_auth {
333            return vec![format!(
334                "Authentication failed for {provider_label}. Run /login {provider_key} to re-authenticate."
335            )];
336        }
337        if !has_credential {
338            return vec![format!(
339                "Authentication failed for {provider_label}. Run /secret add {provider_key} to store your API key in secure storage (OS keyring or encrypted file)."
340            )];
341        }
342        match rejected_source {
343            Some(RejectedCredentialSource::Environment { env_var }) => vec![format!(
344                "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.",
345                env_var.map_or_else(|| "a custom variable".to_string(), |name| format!("`{name}`"))
346            )],
347            Some(RejectedCredentialSource::WorkspaceDotEnv { env_var }) => vec![format!(
348                "Authentication failed for {provider_label}. The rejected key came from {} — check the value there.",
349                env_var.map_or_else(
350                    || "the workspace `.env` file".to_string(),
351                    |name| format!("`{name}` in the workspace `.env` file")
352                )
353            )],
354            Some(RejectedCredentialSource::SecureStorage) => vec![format!(
355                "Authentication failed for {provider_label}. The stored API key was rejected — run /secret add {provider_key} to replace it with a valid key."
356            )],
357            None => vec![format!(
358                "Authentication failed for {provider_label}. The configured credential was rejected — verify the value, or run /secret add {provider_key} to store a fresh key."
359            )],
360        }
361    }
362}
363
364impl fmt::Display for ErrorCategory {
365    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
366        f.write_str(self.user_label())
367    }
368}
369
370// ---------------------------------------------------------------------------
371// Classify from anyhow::Error (string-based fallback for erased types)
372// ---------------------------------------------------------------------------
373
374/// Classify an `anyhow::Error` into a canonical `ErrorCategory`.
375///
376/// This uses string matching as a last resort when the original error type has
377/// been erased through `anyhow` wrapping. Typed conversions (e.g., `From<LLMError>`)
378/// should be preferred where the original error type is available.
379///
380/// Recovery decisions are made by *type* when it survives the `anyhow`
381/// boundary. The outermost context layer is classified first (preserving the
382/// intentional wording of a deliberate `.context(...)`), but when that layer is
383/// uninformative we consult the typed root and then the remaining cause chain.
384/// Without this, a wrapping `.context("...")` message alone would hide the
385/// underlying category — e.g. an `LLMError::RateLimit` buried under
386/// `"compaction failed"` would fall through to `ExecutionError` and lose its
387/// retry/recovery policy.
388#[must_use]
389pub fn classify_anyhow_error(err: &anyhow::Error) -> ErrorCategory {
390    // Fast path: the outermost message is usually the most specific context and
391    // matches the historical behavior exactly.
392    let outer = classify_error_message(&err.to_string());
393    if outer != ErrorCategory::ExecutionError {
394        return outer;
395    }
396
397    // The outer context was uninformative (or absent). Prefer the typed source
398    // of truth when it survived the boundary, then fall back to the deeper
399    // cause chain (`innermost` markers such as `connection reset`).
400    if let Some(llm_error) = err.downcast_ref::<crate::llm::LLMError>() {
401        return ErrorCategory::from(llm_error);
402    }
403
404    for cause in err.chain().skip(1) {
405        let category = classify_error_message(&cause.to_string());
406        if category != ErrorCategory::ExecutionError {
407            return category;
408        }
409    }
410
411    ErrorCategory::ExecutionError
412}
413
414/// Return whether an error explicitly reports that the provider rejected the
415/// request because its input context is too large.
416///
417/// Context-capacity failures are intentionally kept separate from
418/// [`ErrorCategory::InvalidParameters`]: they are not model argument mistakes
419/// and a bounded history compaction can make the same request valid. The
420/// marker set is deliberately specific so ordinary validation messages that
421/// merely mention a context field do not enter recovery.
422#[must_use]
423pub fn is_context_capacity_error(err: &anyhow::Error) -> bool {
424    err.chain().any(|cause| is_context_capacity_message(&cause.to_string()))
425}
426
427/// Return whether a provider error message identifies an input-context limit.
428#[must_use]
429pub fn is_context_capacity_message(message: &str) -> bool {
430    let message = message.to_ascii_lowercase();
431    contains_any(
432        &message,
433        &[
434            "context_length_exceeded",
435            "context length exceeded",
436            "maximum context length",
437            "maximum context window",
438            "context window exceeded",
439            "context window is too small",
440            "exceeds the model's maximum context",
441            "exceeds model context",
442            "exceeds the maximum context",
443            "prompt is too long",
444            "input is too long",
445            "input token count exceeds",
446            "exceeds the maximum number of tokens",
447            "maximum input tokens",
448            "too many tokens in the prompt",
449            "request exceeds the context",
450            // Merge-gateway / Anthropic / OpenAI variants observed on
451            // near-budget follow-ups (e.g. ~956k prompt on a 1M budget) that
452            // previously fell through to generic `ExecutionError` and missed
453            // the compacting tool-enabled recovery path.
454            "context limit exceeded",
455            "context size exceeded",
456            "exceeds context",
457            "input tokens exceed",
458            "prompt tokens exceed",
459            "prompt token count exceeds",
460            "token limit exceeded",
461            "input too large",
462            "prompt too large",
463        ],
464    )
465}
466
467/// Classify an error message string into an `ErrorCategory`.
468///
469/// Marker groups are checked in priority order to handle overlapping patterns
470/// (e.g., "tool permission denied by policy" → `PolicyViolation`, not `PermissionDenied`).
471#[inline]
472#[must_use]
473pub fn classify_error_message(msg: &str) -> ErrorCategory {
474    let msg = if msg.as_bytes().iter().any(|b| b.is_ascii_uppercase()) {
475        Cow::Owned(msg.to_ascii_lowercase())
476    } else {
477        Cow::Borrowed(msg)
478    };
479
480    // --- Priority 1: Policy violations (before permission checks) ---
481    if contains_any(
482        &msg,
483        &[
484            "policy violation",
485            "denied by policy",
486            "tool permission denied",
487            "safety validation failed",
488            "not allowed in planning workflow",
489            "only available when planning workflow is active",
490            "workspace boundary",
491            "blocked by policy",
492        ],
493    ) {
494        return ErrorCategory::PolicyViolation;
495    }
496
497    // --- Priority 2: Planning workflow violations ---
498    if contains_any(
499        &msg,
500        &[
501            "planning workflow",
502            "read-only permissions",
503            concat!("read-only ", "mode"),
504            "planning_policy_violation",
505        ],
506    ) {
507        return ErrorCategory::PlanningPolicyViolation;
508    }
509
510    // --- Priority 3: Authentication / Authorization ---
511    if contains_any(
512        &msg,
513        &[
514            "invalid api key",
515            "authentication failed",
516            "unauthorized",
517            "401",
518            "invalid credentials",
519        ],
520    ) {
521        return ErrorCategory::Authentication;
522    }
523
524    // --- Priority 4: Non-retryable resource exhaustion (billing, quotas) ---
525    if contains_any(
526        &msg,
527        &[
528            "weekly usage limit",
529            "daily usage limit",
530            "monthly spending limit",
531            "insufficient credits",
532            "quota exceeded",
533            "billing",
534            "payment required",
535        ],
536    ) {
537        return ErrorCategory::ResourceExhausted;
538    }
539
540    // --- Priority 5: Invalid parameters ---
541    if contains_any(
542        &msg,
543        &[
544            "invalid argument",
545            "invalid parameters",
546            "invalid type",
547            "malformed",
548            "failed to parse arguments",
549            "failed to parse argument",
550            "missing required",
551            "at least one item is required",
552            "is required for",
553            "schema validation",
554            "argument validation failed",
555            "unknown field",
556            "unknown variant",
557            "expected struct",
558            "expected enum",
559            "type mismatch",
560            "must be an absolute path",
561            "not parseable",
562            "parseable as",
563            // Patch format errors — these are LLM argument mistakes (the model
564            // sent a malformed patch), not execution failures. Classifying them
565            // as InvalidParameters ensures they don't trip the circuit breaker
566            // (is_llm_mistake() == true) and get parameter-focused recovery
567            // suggestions. See checkpoint turn_615 for the failure this
568            // prevents: a unified-diff patch was classified as ExecutionError
569            // and got generic "check tool documentation" suggestions.
570            "invalid patch format",
571            "invalid patch hunk",
572            "invalid patch operation",
573            "cannot parse empty patch",
574            "patch does not contain",
575            "semantic patch anchor",
576        ],
577    ) {
578        return ErrorCategory::InvalidParameters;
579    }
580
581    // --- Priority 6: Tool not found ---
582    if contains_any(&msg, &["tool not found", "unknown tool", "unsupported tool", "no such tool"]) {
583        return ErrorCategory::ToolNotFound;
584    }
585
586    // --- Priority 7: Resource not found ---
587    if contains_any(
588        &msg,
589        &[
590            "no such file",
591            "no such directory",
592            "file not found",
593            "directory not found",
594            "resource not found",
595            "path not found",
596            "does not exist",
597            "enoent",
598        ],
599    ) {
600        return ErrorCategory::ResourceNotFound;
601    }
602
603    // --- Priority 8: Permission denied (OS-level) ---
604    if contains_any(
605        &msg,
606        &[
607            "permission denied",
608            "access denied",
609            "operation not permitted",
610            "eacces",
611            "eperm",
612            "forbidden",
613            "403",
614        ],
615    ) {
616        return ErrorCategory::PermissionDenied;
617    }
618
619    // --- Priority 9: Cancellation ---
620    if contains_any(&msg, &["cancelled", "interrupted", "canceled"]) {
621        return ErrorCategory::Cancelled;
622    }
623
624    // --- Priority 10: Circuit breaker ---
625    if contains_any(&msg, &["circuit breaker", "circuit open"]) {
626        return ErrorCategory::CircuitOpen;
627    }
628
629    // --- Priority 11: Sandbox ---
630    if contains_any(&msg, &["sandbox denied", "sandbox failure"]) {
631        return ErrorCategory::SandboxFailure;
632    }
633
634    // --- Priority 12: Rate limiting (before general network) ---
635    if contains_any(&msg, &["rate limit", "too many requests", "429", "throttl"]) {
636        return ErrorCategory::RateLimit;
637    }
638
639    // --- Priority 13: Timeout ---
640    if contains_any(&msg, &["timeout", "timed out", "deadline exceeded"]) {
641        return ErrorCategory::Timeout;
642    }
643
644    // --- Priority 14: Provider transient response-shape failures ---
645    if contains_any(
646        &msg,
647        &[
648            "invalid response format: missing choices",
649            "invalid response format: missing message",
650            "missing choices in response",
651            "missing message in choice",
652            "no choices in response",
653            "invalid response from ",
654            "empty response body",
655            "response did not contain",
656            "unexpected response format",
657            "failed to parse response",
658            // Post-tool follow-up streaming failures surface here when the
659            // provider drops the SSE/event stream mid-response. Without these
660            // markers the follow-up is misclassified as generic
661            // `ExecutionError` (non-retryable) and the turn ends instead of
662            // scheduling the bounded tool-free retry.
663            "stream disconnected",
664            "stream closed unexpectedly",
665            "incomplete stream",
666            "unexpected end of stream",
667            "truncated response",
668            "failed to decode stream",
669            "stream terminated",
670        ],
671    ) {
672        return ErrorCategory::ServiceUnavailable;
673    }
674
675    // --- Priority 15: Fail-closed stream bounds (non-retryable) ---
676    // The SSE tail overflow names its bound ("without an event boundary")
677    // and embeds the retained byte count, whose digits can contain status
678    // substrings ("500") — classification must not depend on the count. A
679    // peer that withholds event boundaries reproduces the failure on
680    // retry, so fail fast instead of scheduling bounded request retries.
681    if contains_any(&msg, &["without an event boundary"]) {
682        return ErrorCategory::ExecutionError;
683    }
684
685    // --- Priority 16: Service unavailable (HTTP 5xx and related) ---
686    if contains_any(
687        &msg,
688        &[
689            "service unavailable",
690            "temporarily unavailable",
691            "internal server error",
692            "bad gateway",
693            "gateway timeout",
694            "overloaded",
695            "500",
696            "502",
697            "503",
698            "504",
699        ],
700    ) {
701        return ErrorCategory::ServiceUnavailable;
702    }
703
704    // --- Priority 17: Network (connectivity, DNS, transport) ---
705    if contains_any(
706        &msg,
707        &[
708            "network",
709            "connection reset",
710            "connection refused",
711            "broken pipe",
712            "dns",
713            "name resolution",
714            "try again",
715            "retry later",
716            "upstream connect error",
717            "tls handshake",
718            "socket hang up",
719            "econnreset",
720            "etimedout",
721            // reqwest surfaces truncated/aborted response streams as a body
722            // decode failure; Ollama (cloud) emits this on transient drops.
723            // It is a transport error, not a payload problem — retryable.
724            "error decoding response body",
725            // Transport-level stream teardown during a follow-up request.
726            // Distinct from response-shape markers above: the connection
727            // itself failed, not the payload. `stream error` stays specific
728            // (`received`) so `downstream error` prose does not match.
729            "connection closed before",
730            "stream reset",
731            "stream error received",
732        ],
733    ) {
734        return ErrorCategory::Network;
735    }
736
737    // --- Priority 18: Resource exhausted (memory, disk) ---
738    if contains_any(&msg, &["out of memory", "disk full", "no space left"]) {
739        return ErrorCategory::ResourceExhausted;
740    }
741
742    // --- Fallback ---
743    ErrorCategory::ExecutionError
744}
745
746/// Check if an LLM error message is retryable (used by the LLM request retry loop).
747///
748/// This is a focused classifier for LLM provider errors, combining
749/// non-retryable and retryable marker checks for the request retry path.
750#[inline]
751#[must_use]
752pub fn is_retryable_llm_error_message(msg: &str) -> bool {
753    let category = classify_error_message(msg);
754    category.is_retryable()
755}
756
757#[inline]
758fn contains_any(message: &str, markers: &[&str]) -> bool {
759    markers.iter().any(|marker| message.contains(marker))
760}
761
762// ---------------------------------------------------------------------------
763// Typed conversions from known error types
764// ---------------------------------------------------------------------------
765
766impl From<&crate::llm::LLMError> for ErrorCategory {
767    fn from(err: &crate::llm::LLMError) -> Self {
768        match err {
769            crate::llm::LLMError::Authentication { .. } => ErrorCategory::Authentication,
770            crate::llm::LLMError::RateLimit { metadata } => {
771                classify_llm_metadata(metadata.as_deref(), ErrorCategory::RateLimit)
772            }
773            crate::llm::LLMError::InvalidRequest { .. } => ErrorCategory::InvalidParameters,
774            crate::llm::LLMError::Network { .. } => ErrorCategory::Network,
775            crate::llm::LLMError::Provider { message, metadata } => {
776                let metadata_category = classify_llm_metadata(metadata.as_deref(), ErrorCategory::ExecutionError);
777                if metadata_category != ErrorCategory::ExecutionError {
778                    return metadata_category;
779                }
780
781                // Check metadata status code first for precise classification
782                if let Some(meta) = metadata
783                    && let Some(status) = meta.status
784                {
785                    return match status {
786                        401 => ErrorCategory::Authentication,
787                        403 => ErrorCategory::PermissionDenied,
788                        404 => ErrorCategory::ResourceNotFound,
789                        429 => ErrorCategory::RateLimit,
790                        400 => ErrorCategory::InvalidParameters,
791                        500 | 502 | 503 | 504 | 529 => ErrorCategory::ServiceUnavailable,
792                        408 => ErrorCategory::Timeout,
793                        _ => classify_error_message(message),
794                    };
795                }
796                // Fall back to message-based classification
797                classify_error_message(message)
798            }
799        }
800    }
801}
802
803fn classify_llm_metadata(metadata: Option<&crate::llm::LLMErrorMetadata>, fallback: ErrorCategory) -> ErrorCategory {
804    let Some(metadata) = metadata else {
805        return fallback;
806    };
807
808    let mut hint = String::new();
809    if let Some(code) = &metadata.code {
810        hint.push_str(code);
811        hint.push(' ');
812    }
813    if let Some(message) = &metadata.message {
814        hint.push_str(message);
815        hint.push(' ');
816    }
817    if let Some(status) = metadata.status {
818        let _ = write!(&mut hint, "{status}");
819    }
820
821    let classified = classify_error_message(&hint);
822    if classified == ErrorCategory::ExecutionError {
823        fallback
824    } else {
825        classified
826    }
827}
828
829#[cfg(test)]
830mod tests;