Skip to main content

mutil_ai/
error.rs

1use std::fmt;
2use std::time::Duration;
3
4use thiserror::Error;
5
6use crate::retry::RetrySource;
7
8/// Convenience alias for results returned by this crate.
9pub type Result<T> = std::result::Result<T, Error>;
10
11/// Stable high-level classification for SDK errors.
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
13pub enum ErrorKind {
14    /// No API key was configured, or the provider rejected it (HTTP 401).
15    Authentication,
16    /// The credentials are valid but lack access to the resource (HTTP 403).
17    PermissionDenied,
18    /// The requested resource does not exist (HTTP 404).
19    NotFound,
20    /// The provider rejected the request as malformed (HTTP 400-class).
21    InvalidRequest,
22    /// The prompt or output exceeds the model's context window.
23    ContextLengthExceeded,
24    /// The request or output was blocked by a safety or content policy.
25    ContentFiltered,
26    /// The provider is rate limiting the account (HTTP 429).
27    RateLimited,
28    /// The provider is temporarily overloaded (e.g. HTTP 425 or 529).
29    Overloaded,
30    /// The request timed out.
31    Timeout,
32    /// A network-level failure prevented reaching the provider.
33    Connection,
34    /// The request was cancelled by the caller.
35    Cancelled,
36    /// A response body could not be decoded.
37    Decode,
38    /// The provider emitted a malformed or unexpected stream event.
39    StreamProtocol,
40    /// The provider itself reported an internal error (HTTP 5xx).
41    ProviderInternal,
42    /// The selected provider does not support the requested operation.
43    Unsupported,
44    /// The SDK or provider client was misconfigured.
45    Configuration,
46    /// Request normalization failed.
47    Normalization,
48    /// A tool invocation failed or referenced an unknown tool.
49    Tool,
50    /// The agent loop exhausted its step budget.
51    MaxSteps,
52    /// The error could not be classified.
53    Unknown,
54}
55
56impl ErrorKind {
57    /// Stable snake_case identifier for this kind, suitable for logs and
58    /// metrics.
59    pub const fn as_str(self) -> &'static str {
60        match self {
61            Self::Authentication => "authentication",
62            Self::PermissionDenied => "permission_denied",
63            Self::NotFound => "not_found",
64            Self::InvalidRequest => "invalid_request",
65            Self::ContextLengthExceeded => "context_length_exceeded",
66            Self::ContentFiltered => "content_filtered",
67            Self::RateLimited => "rate_limited",
68            Self::Overloaded => "overloaded",
69            Self::Timeout => "timeout",
70            Self::Connection => "connection",
71            Self::Cancelled => "cancelled",
72            Self::Decode => "decode",
73            Self::StreamProtocol => "stream_protocol",
74            Self::ProviderInternal => "provider_internal",
75            Self::Unsupported => "unsupported",
76            Self::Configuration => "configuration",
77            Self::Normalization => "normalization",
78            Self::Tool => "tool",
79            Self::MaxSteps => "max_steps",
80            Self::Unknown => "unknown",
81        }
82    }
83
84    /// Whether errors of this kind are normally safe to retry.
85    pub const fn is_retryable(self) -> bool {
86        matches!(
87            self,
88            Self::RateLimited
89                | Self::Overloaded
90                | Self::Timeout
91                | Self::Connection
92                | Self::ProviderInternal
93        )
94    }
95}
96
97/// Safe, provider-neutral summary of a structured error response.
98///
99/// The provider message itself is never retained. Only its byte length is
100/// exposed, while code/type/status tokens are sanitized and length-limited.
101#[derive(Debug, Clone, Default, PartialEq, Eq)]
102pub struct ProviderErrorInfo {
103    /// Machine-readable provider code, such as `context_length_exceeded`.
104    pub code: Option<String>,
105    /// Provider error type/category, such as `invalid_request_error`.
106    pub error_type: Option<String>,
107    /// Provider status token, such as `INVALID_ARGUMENT`.
108    pub status: Option<String>,
109    /// Byte length of the provider's human-readable message, if present.
110    pub message_bytes: Option<usize>,
111    /// Number of structured `details` entries, when the provider returns them.
112    pub details_count: usize,
113}
114
115/// The error type returned by this crate's public API.
116///
117/// Its [`Display`](std::fmt::Display) output is safe to log: the `Api`
118/// variant never embeds the raw provider response body, and the `Debug`
119/// output redacts it. Use [`Error::kind`] for stable classification and
120/// [`Error::raw_body`] when you explicitly need the provider body.
121#[derive(Error)]
122pub enum Error {
123    /// No API key was configured for the provider.
124    #[error("missing API key: {0}")]
125    MissingApiKey(String),
126
127    /// The HTTP request to the provider failed at the transport level.
128    #[error("HTTP request failed")]
129    Http(#[source] reqwest::Error),
130
131    /// The request was cancelled before it completed.
132    #[error("request cancelled")]
133    Cancelled,
134
135    /// The request exceeded its configured timeout.
136    #[error("request timed out: {0}")]
137    Timeout(String),
138
139    /// A response body was not valid JSON.
140    #[error("invalid JSON: {0}")]
141    Json(#[from] serde_json::Error),
142
143    /// The provider's stream emitted a malformed or unexpected event.
144    #[error("stream protocol error: {0}")]
145    StreamProtocol(String),
146
147    /// The provider reported an error inside a stream.
148    #[error("provider stream error (raw payload redacted)")]
149    ProviderStream(String),
150
151    /// A decoded response exceeded its configured resource budget.
152    #[error("response exceeded {resource} limit of {limit}")]
153    ResponseLimit {
154        /// Name of the bounded resource, without provider content.
155        resource: &'static str,
156        /// Configured maximum.
157        limit: usize,
158    },
159
160    #[error("{provider} returned HTTP {status}")]
161    Api {
162        /// The provider identifier, such as `openai`.
163        provider: &'static str,
164        /// HTTP status code returned by the provider.
165        status: u16,
166        /// Raw response body. Excluded from log-safe output; see
167        /// [`Error::raw_body`].
168        body: String,
169        /// Parsed server-directed retry delay, when present.
170        retry_after: Option<Duration>,
171        /// Which header produced `retry_after`.
172        retry_source: Option<RetrySource>,
173        /// Provider request id copied from response metadata, when present.
174        request_id: Option<String>,
175    },
176
177    /// A provider was configured without a model.
178    #[error("provider `{0}` is not configured with a model")]
179    MissingModel(&'static str),
180
181    /// The request could not be built as specified.
182    #[error("invalid request: {0}")]
183    InvalidRequest(String),
184
185    /// The selected provider does not support the requested operation.
186    #[error("unsupported operation: {0}")]
187    Unsupported(String),
188
189    /// The model requested a tool that was never registered.
190    #[error("tool `{0}` was requested by the model but is not registered")]
191    ToolNotFound(String),
192
193    /// A registered tool returned an error while executing.
194    #[error("tool `{tool}` failed: {message}")]
195    ToolFailed {
196        /// Name of the tool that failed.
197        tool: String,
198        /// Error message reported by the tool.
199        message: String,
200    },
201
202    /// The agent loop exceeded its configured step budget.
203    #[error("agent exceeded max_steps={0}")]
204    MaxSteps(usize),
205
206    /// A request could not be normalized for the target protocol.
207    #[error("normalization error: {0}")]
208    Normalize(String),
209
210    /// A retry policy configuration was invalid.
211    #[error("invalid retry policy: {0}")]
212    InvalidRetryPolicy(String),
213
214    /// An HTTP header value was invalid.
215    #[error("invalid HTTP header value: {0}")]
216    HeaderValue(#[from] reqwest::header::InvalidHeaderValue),
217
218    /// An HTTP header name was invalid.
219    #[error("invalid HTTP header name: {0}")]
220    HeaderName(#[from] reqwest::header::InvalidHeaderName),
221
222    /// An attempt was made to override a header the SDK manages itself.
223    #[error("protected HTTP header cannot be overridden: {0}")]
224    ProtectedHeader(String),
225
226    /// A header value contained non-ASCII characters.
227    #[error("HTTP header `{name}` must be ASCII for interoperability")]
228    NonAsciiHeaderValue {
229        /// Name of the offending header.
230        name: String,
231    },
232
233    /// An extra body field collided with a canonical SDK field.
234    #[error("{protocol} extra body field `{field}` cannot override a canonical SDK field")]
235    ReservedExtraBodyField {
236        /// The provider protocol that rejected the field.
237        protocol: &'static str,
238        /// The reserved field name.
239        field: String,
240    },
241
242    /// An extra query parameter collided with an endpoint-reserved name.
243    #[error("{protocol} extra query parameter `{parameter}` is reserved by the endpoint")]
244    ReservedExtraQuery {
245        /// The provider protocol that rejected the parameter.
246        protocol: &'static str,
247        /// The reserved parameter name.
248        parameter: String,
249    },
250
251    /// A base URL or endpoint could not be parsed.
252    #[error("invalid endpoint: {0}")]
253    InvalidEndpoint(String),
254
255    /// A provider profile configuration was invalid.
256    #[error("invalid provider profile: {0}")]
257    InvalidProfile(String),
258}
259
260struct RedactedBody(usize);
261
262impl From<reqwest::Error> for Error {
263    fn from(error: reqwest::Error) -> Self {
264        Self::Http(error.without_url())
265    }
266}
267
268impl fmt::Debug for RedactedBody {
269    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
270        write!(formatter, "<redacted {} bytes>", self.0)
271    }
272}
273
274impl fmt::Debug for Error {
275    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
276        match self {
277            Self::MissingApiKey(value) => {
278                formatter.debug_tuple("MissingApiKey").field(value).finish()
279            }
280            Self::Http(error) => formatter
281                .debug_struct("Http")
282                .field("kind", &classify_reqwest_error(error))
283                .finish(),
284            Self::Cancelled => formatter.write_str("Cancelled"),
285            Self::Timeout(message) => formatter.debug_tuple("Timeout").field(message).finish(),
286            Self::Json(error) => formatter.debug_tuple("Json").field(error).finish(),
287            Self::StreamProtocol(value) => formatter
288                .debug_tuple("StreamProtocol")
289                .field(value)
290                .finish(),
291            Self::ProviderStream(value) => formatter
292                .debug_tuple("ProviderStream")
293                .field(&RedactedBody(value.len()))
294                .finish(),
295            Self::ResponseLimit { resource, limit } => formatter
296                .debug_struct("ResponseLimit")
297                .field("resource", resource)
298                .field("limit", limit)
299                .finish(),
300            Self::Api {
301                provider,
302                status,
303                body,
304                retry_after,
305                retry_source,
306                request_id,
307            } => formatter
308                .debug_struct("Api")
309                .field("provider", provider)
310                .field("status", status)
311                .field("body", &RedactedBody(body.len()))
312                .field("retry_after", retry_after)
313                .field("retry_source", retry_source)
314                .field("request_id", request_id)
315                .finish(),
316            Self::MissingModel(value) => {
317                formatter.debug_tuple("MissingModel").field(value).finish()
318            }
319            Self::InvalidRequest(value) => formatter
320                .debug_tuple("InvalidRequest")
321                .field(value)
322                .finish(),
323            Self::Unsupported(value) => formatter.debug_tuple("Unsupported").field(value).finish(),
324            Self::ToolNotFound(value) => {
325                formatter.debug_tuple("ToolNotFound").field(value).finish()
326            }
327            Self::ToolFailed { tool, message } => formatter
328                .debug_struct("ToolFailed")
329                .field("tool", tool)
330                .field("message", message)
331                .finish(),
332            Self::MaxSteps(value) => formatter.debug_tuple("MaxSteps").field(value).finish(),
333            Self::Normalize(value) => formatter.debug_tuple("Normalize").field(value).finish(),
334            Self::InvalidRetryPolicy(value) => formatter
335                .debug_tuple("InvalidRetryPolicy")
336                .field(value)
337                .finish(),
338            Self::HeaderValue(error) => formatter.debug_tuple("HeaderValue").field(error).finish(),
339            Self::HeaderName(error) => formatter.debug_tuple("HeaderName").field(error).finish(),
340            Self::ProtectedHeader(value) => formatter
341                .debug_tuple("ProtectedHeader")
342                .field(value)
343                .finish(),
344            Self::NonAsciiHeaderValue { name } => formatter
345                .debug_struct("NonAsciiHeaderValue")
346                .field("name", name)
347                .finish(),
348            Self::ReservedExtraBodyField { protocol, field } => formatter
349                .debug_struct("ReservedExtraBodyField")
350                .field("protocol", protocol)
351                .field("field", field)
352                .finish(),
353            Self::ReservedExtraQuery {
354                protocol,
355                parameter,
356            } => formatter
357                .debug_struct("ReservedExtraQuery")
358                .field("protocol", protocol)
359                .field("parameter", parameter)
360                .finish(),
361            Self::InvalidEndpoint(value) => formatter
362                .debug_tuple("InvalidEndpoint")
363                .field(value)
364                .finish(),
365            Self::InvalidProfile(value) => formatter
366                .debug_tuple("InvalidProfile")
367                .field(value)
368                .finish(),
369        }
370    }
371}
372
373impl Error {
374    /// Classify this error into a stable, provider-neutral [`ErrorKind`].
375    pub fn kind(&self) -> ErrorKind {
376        match self {
377            Self::MissingApiKey(_) => ErrorKind::Authentication,
378            Self::Http(error) => classify_reqwest_error(error),
379            Self::Cancelled => ErrorKind::Cancelled,
380            Self::Timeout(_) => ErrorKind::Timeout,
381            Self::Json(_) => ErrorKind::Decode,
382            Self::StreamProtocol(_) => ErrorKind::StreamProtocol,
383            Self::ProviderStream(value) => classify_provider_stream(value),
384            Self::ResponseLimit { .. } => ErrorKind::Decode,
385            Self::Api { status, body, .. } => classify_api_error(*status, body),
386            Self::MissingModel(_) => ErrorKind::Configuration,
387            Self::InvalidRequest(_) => ErrorKind::InvalidRequest,
388            Self::Unsupported(_) => ErrorKind::Unsupported,
389            Self::ToolNotFound(_) | Self::ToolFailed { .. } => ErrorKind::Tool,
390            Self::MaxSteps(_) => ErrorKind::MaxSteps,
391            Self::Normalize(_) => ErrorKind::Normalization,
392            Self::InvalidRetryPolicy(_)
393            | Self::HeaderValue(_)
394            | Self::HeaderName(_)
395            | Self::ProtectedHeader(_)
396            | Self::NonAsciiHeaderValue { .. }
397            | Self::ReservedExtraBodyField { .. }
398            | Self::ReservedExtraQuery { .. }
399            | Self::InvalidEndpoint(_)
400            | Self::InvalidProfile(_) => ErrorKind::Configuration,
401        }
402    }
403
404    /// Provider HTTP status, when this error came from an API response.
405    pub fn status(&self) -> Option<u16> {
406        match self {
407            Self::Api { status, .. } => Some(*status),
408            _ => None,
409        }
410    }
411
412    /// Provider name, when this error came from an API response.
413    pub fn provider(&self) -> Option<&str> {
414        match self {
415            Self::Api { provider, .. } => Some(provider),
416            _ => None,
417        }
418    }
419
420    /// Provider request id, when the response exposed one.
421    pub fn request_id(&self) -> Option<&str> {
422        match self {
423            Self::Api { request_id, .. } => request_id.as_deref(),
424            _ => None,
425        }
426    }
427
428    /// Return the raw provider error body.
429    ///
430    /// This is intentionally opt-in because provider errors can echo request
431    /// content, account data, or other sensitive values. Prefer
432    /// [`Self::body_bytes`], [`Self::status`], and [`Self::request_id`] for
433    /// logs and metrics.
434    pub fn raw_body(&self) -> Option<&str> {
435        match self {
436            Self::Api { body, .. } | Self::ProviderStream(body) => Some(body),
437            _ => None,
438        }
439    }
440
441    /// Decoded provider error-body size in bytes, without exposing the body.
442    pub fn body_bytes(&self) -> Option<usize> {
443        match self {
444            Self::Api { body, .. } | Self::ProviderStream(body) => Some(body.len()),
445            _ => None,
446        }
447    }
448
449    /// Parse a safe, provider-neutral summary of a structured API error.
450    ///
451    /// Provider messages are never included. Codes, types, and status tokens
452    /// are only returned when they are short, ASCII machine tokens.
453    pub fn provider_error(&self) -> Option<ProviderErrorInfo> {
454        match self {
455            Self::Api { body, .. } | Self::ProviderStream(body) => Some(parse_provider_error(body)),
456            _ => None,
457        }
458    }
459
460    /// Return the parsed `Retry-After` duration, if this error came from an
461    /// HTTP response that supplied one.
462    pub fn retry_after(&self) -> Option<Duration> {
463        match self {
464            Self::Api { retry_after, .. } => *retry_after,
465            _ => None,
466        }
467    }
468
469    /// Return which response header produced the retry delay.
470    pub fn retry_source(&self) -> Option<RetrySource> {
471        match self {
472            Self::Api { retry_source, .. } => *retry_source,
473            _ => None,
474        }
475    }
476
477    /// Whether this error is normally safe to retry.
478    ///
479    /// This is a conservative classification. Callers should still avoid
480    /// retrying non-idempotent operations unless they have an idempotency key.
481    pub fn is_retryable(&self) -> bool {
482        self.kind().is_retryable()
483    }
484}
485
486fn parse_provider_error(body: &str) -> ProviderErrorInfo {
487    let Ok(value) = serde_json::from_str::<serde_json::Value>(body) else {
488        return ProviderErrorInfo {
489            message_bytes: Some(body.len()),
490            ..ProviderErrorInfo::default()
491        };
492    };
493
494    let top = value.as_object();
495    let nested = top
496        .and_then(|object| object.get("error"))
497        .and_then(serde_json::Value::as_object);
498    let error_value = top.and_then(|object| object.get("error"));
499
500    let code = nested
501        .and_then(|object| object.get("code"))
502        .or_else(|| top.and_then(|object| object.get("error_code")))
503        .or_else(|| top.and_then(|object| object.get("code")))
504        .and_then(provider_token);
505    let error_type = nested
506        .and_then(|object| object.get("type"))
507        .or_else(|| top.and_then(|object| object.get("type")))
508        .and_then(provider_token);
509    let status = nested
510        .and_then(|object| object.get("status"))
511        .or_else(|| top.and_then(|object| object.get("status")))
512        .and_then(provider_token);
513    let message = nested
514        .and_then(|object| object.get("message"))
515        .or_else(|| top.and_then(|object| object.get("message")))
516        .or_else(|| top.and_then(|object| object.get("error_msg")))
517        .or_else(|| top.and_then(|object| object.get("error_description")))
518        .or(error_value);
519    let message_bytes = match message {
520        Some(serde_json::Value::String(message)) => Some(message.len()),
521        _ => None,
522    };
523    let details_count = nested
524        .and_then(|object| object.get("details"))
525        .or_else(|| top.and_then(|object| object.get("details")))
526        .and_then(serde_json::Value::as_array)
527        .map_or(0, Vec::len);
528
529    ProviderErrorInfo {
530        code,
531        error_type,
532        status,
533        message_bytes,
534        details_count,
535    }
536}
537
538fn provider_token(value: &serde_json::Value) -> Option<String> {
539    let token = match value {
540        serde_json::Value::String(token) => token.trim(),
541        serde_json::Value::Number(token) => return Some(token.to_string()),
542        _ => return None,
543    };
544    if token.is_empty() || token.len() > 96 {
545        return None;
546    }
547    if !token.bytes().all(|byte| {
548        byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-' | b'.' | b':' | b'/')
549    }) {
550        return None;
551    }
552    Some(token.to_string())
553}
554
555/// How much of a provider message is scanned before classification gives up.
556const MESSAGE_SCAN_LIMIT: usize = 8 * 1024;
557
558/// Message phrases that report a context-window rejection, collected across the
559/// public error shapes of mainstream chat APIs. Deliberately narrow: each
560/// phrase names the window or the token budget, so an unrelated malformed
561/// request cannot be mistaken for an overflow.
562const CONTEXT_LENGTH_MARKERS: &[&str] = &[
563    "context_length_exceeded",
564    "context length",
565    "context window",
566    "context limit",
567    "context too long",
568    "prompt is too long",
569    "too many tokens",
570    "reduce the length",
571    "input length",
572];
573
574/// Message phrases that report a safety or content-policy rejection.
575const CONTENT_FILTER_MARKERS: &[&str] = &[
576    "content_filter",
577    "content filter",
578    "content policy",
579    "content safety",
580    "safety policy",
581    "policy violation",
582    "filtered due to",
583];
584
585fn classify_api_error(status: u16, body: &str) -> ErrorKind {
586    let parsed = serde_json::from_str::<serde_json::Value>(body).ok();
587    // The token layer is not status-gated (unchanged from before): a provider
588    // that labels its failure always gets that label honoured.
589    if let Some(kind) = classify_error_tokens(parsed.as_ref()) {
590        return kind;
591    }
592    // Only the generic invalid-request band is refined from message text: a
593    // rate limit or a 5xx keeps its own kind whatever the body says.
594    if matches!(classify_status(status), ErrorKind::InvalidRequest)
595        && let Some(kind) = classify_error_message(parsed.as_ref(), body)
596    {
597        return kind;
598    }
599    classify_status(status)
600}
601
602/// Classify an in-band provider stream error payload, which carries no HTTP
603/// status to gate on. Falls back to the previous blanket
604/// [`ErrorKind::ProviderInternal`] when the payload says nothing more.
605fn classify_provider_stream(payload: &str) -> ErrorKind {
606    let parsed = serde_json::from_str::<serde_json::Value>(payload).ok();
607    classify_error_tokens(parsed.as_ref())
608        .or_else(|| classify_error_message(parsed.as_ref(), payload))
609        .unwrap_or(ErrorKind::ProviderInternal)
610}
611
612fn classify_error_tokens(parsed: Option<&serde_json::Value>) -> Option<ErrorKind> {
613    let value = parsed?;
614    error_tokens(value)
615        .iter()
616        .find_map(|token| classify_token(token))
617}
618
619/// Refine a kind from the provider's own wording. `parsed` is the payload once
620/// it has been read as JSON; a body that is not JSON at all (a gateway error
621/// page, a plain-text 400) is scanned as-is.
622fn classify_error_message(parsed: Option<&serde_json::Value>, payload: &str) -> Option<ErrorKind> {
623    let text = match parsed {
624        Some(value) => provider_message_text(value)?,
625        None => scan_prefix(payload),
626    };
627    let lower = text.to_ascii_lowercase();
628    // Context first: a rejection can quote both conditions, and shrinking the
629    // request is the actionable reading.
630    if CONTEXT_LENGTH_MARKERS
631        .iter()
632        .any(|marker| lower.contains(marker))
633    {
634        return Some(ErrorKind::ContextLengthExceeded);
635    }
636    if CONTENT_FILTER_MARKERS
637        .iter()
638        .any(|marker| lower.contains(marker))
639    {
640        return Some(ErrorKind::ContentFiltered);
641    }
642    None
643}
644
645fn classify_token(token: &str) -> Option<ErrorKind> {
646    match token.to_ascii_lowercase().as_str() {
647        "context_length_exceeded"
648        | "context_length_exceeded_error"
649        | "context_too_long"
650        | "prompt_too_long"
651        | "max_tokens_exceeded" => Some(ErrorKind::ContextLengthExceeded),
652        "content_filter"
653        | "content_filtered"
654        | "content_policy_violation"
655        | "safety"
656        | "safety_blocked" => Some(ErrorKind::ContentFiltered),
657        _ => None,
658    }
659}
660
661/// Machine-readable tokens from the error containers providers use: the top
662/// level, an `error` member, and the Responses `response.error` member.
663///
664/// `error_code` is read alongside `code` because that is the field name several
665/// compatible APIs use at the top level of an error body.
666fn error_tokens(value: &serde_json::Value) -> Vec<String> {
667    const FIELDS: [&str; 4] = ["code", "error_code", "type", "status"];
668    let mut tokens = Vec::new();
669    for node in error_nodes(value) {
670        for field in FIELDS {
671            if let Some(token) = node.get(field).and_then(provider_token) {
672                tokens.push(token);
673            }
674        }
675    }
676    tokens
677}
678
679/// Error-bearing objects in one payload, outermost first.
680fn error_nodes(value: &serde_json::Value) -> Vec<&serde_json::Value> {
681    let mut nodes = Vec::new();
682    if value.is_object() || value.is_string() {
683        nodes.push(value);
684    }
685    for path in [
686        ["error"].as_slice(),
687        ["error", "error"].as_slice(),
688        ["response", "error"].as_slice(),
689    ] {
690        let mut node = value;
691        for key in path {
692            node = match node.get(key) {
693                Some(next) => next,
694                None => break,
695            };
696        }
697        if (node.is_object() || node.is_string()) && !nodes.contains(&node) {
698            nodes.push(node);
699        }
700    }
701    nodes
702}
703
704/// The human-readable part of an error payload, capped so a large body cannot
705/// make classification expensive.
706///
707/// Only message-bearing fields are read; request content echoed under other
708/// keys cannot influence the classification.
709fn provider_message_text(value: &serde_json::Value) -> Option<String> {
710    for node in error_nodes(value) {
711        if let Some(text) = node.as_str() {
712            return Some(scan_prefix(text));
713        }
714        for field in [
715            "message",
716            "error_message",
717            "error_msg",
718            "error_description",
719            "reason",
720        ] {
721            if let Some(text) = node.get(field).and_then(serde_json::Value::as_str) {
722                return Some(scan_prefix(text));
723            }
724        }
725    }
726    None
727}
728
729/// First [`MESSAGE_SCAN_LIMIT`] bytes of `text`, truncated to a char boundary.
730fn scan_prefix(text: &str) -> String {
731    let mut end = text.len().min(MESSAGE_SCAN_LIMIT);
732    while !text.is_char_boundary(end) {
733        end -= 1;
734    }
735    text[..end].to_string()
736}
737
738fn classify_status(status: u16) -> ErrorKind {
739    match status {
740        401 => ErrorKind::Authentication,
741        403 => ErrorKind::PermissionDenied,
742        404 => ErrorKind::NotFound,
743        408 => ErrorKind::Timeout,
744        425 => ErrorKind::Overloaded,
745        429 => ErrorKind::RateLimited,
746        400 | 409 | 413 | 415 | 416 | 422 => ErrorKind::InvalidRequest,
747        500..=599 => ErrorKind::ProviderInternal,
748        _ => ErrorKind::Unknown,
749    }
750}
751
752fn classify_reqwest_error(error: &reqwest::Error) -> ErrorKind {
753    if error.is_timeout() {
754        ErrorKind::Timeout
755    } else if error.is_connect() || error.is_request() || error.is_body() {
756        ErrorKind::Connection
757    } else if error.is_decode() {
758        ErrorKind::Decode
759    } else if error.is_builder() {
760        ErrorKind::InvalidRequest
761    } else {
762        ErrorKind::Unknown
763    }
764}