Skip to main content

tilo_model_client/
failure.rs

1use serde_json::Value;
2use std::{fmt, time::Duration};
3
4/// How every failure that ran out of credit begins, so a status line or a
5/// panel can recognise it without parsing the rest.
6pub const OUT_OF_CREDITS: &str = "out of AI credits";
7
8#[derive(Clone, Copy, Debug, PartialEq, Eq)]
9pub enum Kind {
10    /// The machine's included credit cannot cover the request (HTTP 402).
11    OutOfCredits,
12    /// Metered AI needs an active subscription (HTTP 402).
13    SubscriptionRequired,
14    /// Too many requests; worth asking again after a pause (HTTP 429).
15    RateLimited,
16    /// The endpoint or its provider is briefly unavailable (408, 5xx, a
17    /// timeout or a refused connection); worth asking again.
18    Busy,
19    /// The endpoint cannot tell yet whether this request was answered and
20    /// billed (HTTP 409 `request_pending`). Asking again cannot help.
21    Pending,
22    /// The credential was refused (HTTP 401/403).
23    Unauthorized,
24    PermissionDenied,
25    ContextLimit,
26    TimedOut,
27    /// Connection failed before dispatch; unlike interrupted transport, safe to retry.
28    Connection,
29    Transport,
30    /// The endpoint is switched off or unconfigured.
31    Unavailable,
32    /// The request itself was refused (other 4xx).
33    Rejected,
34}
35
36/// A failed completion.
37#[derive(Clone, Debug, PartialEq, Eq)]
38pub struct Failure {
39    /// What it means.
40    pub kind: Kind,
41    /// The endpoint's own machine-readable code, if it gave one.
42    pub code: Option<String>,
43    /// A short explanation safe to show a person.
44    pub detail: String,
45    /// How long the endpoint asked to be left alone.
46    pub retry_after: Option<Duration>,
47}
48
49impl Failure {
50    /// Convert only typed classifications, never provider-controlled prose.
51    pub fn model_error(&self) -> agent_provider_config::protocol::ModelError {
52        use agent_provider_config::protocol::{ErrorKind, ModelError};
53        ModelError::new(match self.kind {
54            Kind::OutOfCredits | Kind::SubscriptionRequired => ErrorKind::CreditsExhausted,
55            Kind::Unauthorized => ErrorKind::Authentication,
56            Kind::PermissionDenied => ErrorKind::PermissionDenied,
57            Kind::ContextLimit => ErrorKind::ContextLimit,
58            Kind::TimedOut => ErrorKind::TimedOut,
59            Kind::Connection | Kind::Transport => ErrorKind::Transport,
60            Kind::RateLimited => ErrorKind::RateLimited,
61            Kind::Unavailable => ErrorKind::Unavailable,
62            Kind::Rejected => ErrorKind::InvalidRequest,
63            Kind::Busy | Kind::Pending => ErrorKind::Provider,
64        })
65    }
66
67    /// Whether asking again with the same idempotency key may succeed.
68    #[must_use]
69    pub const fn retryable(&self) -> bool {
70        matches!(
71            self.kind,
72            Kind::RateLimited | Kind::Busy | Kind::TimedOut | Kind::Connection
73        )
74    }
75
76    /// Whether HTTP refusal proves no inference was admitted: the provider
77    /// was rate-limited (429), overloaded (529) or unavailable for now (503,
78    /// which HTTP defines as a request not handled and names `Retry-After`
79    /// for). Billing failures never authorize replay, regardless of their
80    /// HTTP status, and neither does a provider that says it is switched off.
81    pub fn refused_unprocessed(&self, status: u16) -> bool {
82        matches!(status, 429 | 503 | 529) && matches!(self.kind, Kind::RateLimited | Kind::Busy)
83    }
84
85    /// A transport failure before any answer arrived.
86    #[must_use]
87    pub fn transport(timed_out: bool, connect: bool) -> Self {
88        Self {
89            kind: if timed_out {
90                Kind::TimedOut
91            } else if connect {
92                Kind::Connection
93            } else {
94                Kind::Transport
95            },
96            code: None,
97            detail: if timed_out {
98                "the model endpoint timed out".into()
99            } else {
100                "the model endpoint could not be reached".into()
101            },
102            retry_after: None,
103        }
104    }
105
106    /// Classify an unsuccessful HTTP answer. Only Tilo Cloud's own fixed
107    /// messages are repeated; a provider's free-text message can quote a
108    /// credential, so only its code is kept.
109    #[must_use]
110    pub fn from_http(status: u16, body: &str, retry_after: Option<&str>) -> Self {
111        let parsed: Value = serde_json::from_str(body).unwrap_or(Value::Null);
112        let error = parsed.get("error").unwrap_or(&parsed);
113        // Provider-controlled strings are never diagnostics, including "code".
114        // Keep only recognized, fixed machine codes.
115        let codes = [error.get("code"), error.get("type"), parsed.get("code")];
116        // Billing wins even if a provider also labels the envelope rate-limited.
117        let code = codes
118            .iter()
119            .filter_map(|value| value.and_then(Value::as_str))
120            .find(|code| billing_code(code))
121            .or_else(|| {
122                codes
123                    .iter()
124                    .filter_map(|value| value.and_then(Value::as_str))
125                    .find(|code| recognized_code(code))
126            })
127            .map(str::to_owned);
128        // Some compatible endpoints omit machine codes. Recognize only fixed
129        // billing/context phrases here, never repeat the provider's prose.
130        let message = error
131            .get("message")
132            .and_then(Value::as_str)
133            .unwrap_or_default()
134            .chars()
135            .take(4096)
136            .collect::<String>()
137            .to_ascii_lowercase();
138        let kind = match (status, code.as_deref()) {
139            _ if message.contains("credit balance is too low")
140                || message.contains("insufficient credits") =>
141            {
142                Kind::OutOfCredits
143            }
144            (_, Some("subscription_required")) => Kind::SubscriptionRequired,
145            (402, _) => Kind::OutOfCredits,
146            (_, Some(code)) if billing_code(code) => Kind::OutOfCredits,
147            (
148                _,
149                Some("context_length_exceeded" | "context_window_exceeded" | "prompt_too_long"),
150            )
151            | (413, _) => Kind::ContextLimit,
152            (_, Some("authentication_error" | "invalid_api_key")) => Kind::Unauthorized,
153            (_, Some("permission_error")) => Kind::PermissionDenied,
154            (_, Some("overloaded_error")) => Kind::Busy,
155            (409, Some("request_pending")) => Kind::Pending,
156            (_, Some("rate_limit_error" | "rate_limit_exceeded")) | (429, _) => Kind::RateLimited,
157            (401, _) => Kind::Unauthorized,
158            (403, _) => Kind::PermissionDenied,
159            (
160                503,
161                Some(
162                    "service_disabled"
163                    | "pricing_unavailable"
164                    | "pricing_disabled"
165                    | "provider_unavailable",
166                ),
167            ) => Kind::Unavailable,
168            _ if message.contains("prompt is too long")
169                || message.contains("maximum context length") =>
170            {
171                Kind::ContextLimit
172            }
173            (408 | 504, _) => Kind::TimedOut,
174            (500 | 502 | 503 | 529, _) => Kind::Busy,
175            _ => Kind::Rejected,
176        };
177        let detail = match kind {
178            Kind::OutOfCredits => format!(
179                "{OUT_OF_CREDITS}: this machine's included credit cannot cover the request. \
180                 Add credit or connect your own API key in AI & credits"
181            ),
182            Kind::SubscriptionRequired => {
183                "metered AI needs an active subscription for this machine".into()
184            }
185            Kind::Pending => "the model call's outcome is pending reconciliation; \
186                 it was not retried so it cannot be charged twice"
187                .into(),
188            _ => format!("the model endpoint answered HTTP {status}"),
189        };
190        Self {
191            kind,
192            code,
193            detail,
194            retry_after: retry_after
195                .and_then(|value| value.trim().parse::<f64>().ok())
196                .and_then(|seconds| Duration::try_from_secs_f64(seconds).ok()),
197        }
198    }
199}
200
201fn recognized_code(code: &str) -> bool {
202    matches!(
203        code,
204        "request_pending"
205            | "service_disabled"
206            | "pricing_unavailable"
207            | "pricing_disabled"
208            | "provider_unavailable"
209            | "context_length_exceeded"
210            | "context_window_exceeded"
211            | "invalid_api_key"
212            | "prompt_too_long"
213            | "authentication_error"
214            | "permission_error"
215            | "rate_limit_error"
216            | "rate_limit_exceeded"
217            | "overloaded_error"
218    )
219}
220
221fn billing_code(code: &str) -> bool {
222    matches!(
223        code,
224        "subscription_required"
225            | "insufficient_credit"
226            | "insufficient_credits"
227            | "credit_exhausted"
228            | "credits_exhausted"
229            | "insufficient_quota"
230            | "credit_balance_too_low"
231            | "billing_hard_limit_reached"
232    )
233}
234
235impl fmt::Display for Failure {
236    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
237        match &self.code {
238            Some(code) if !self.detail.contains(code.as_str()) => {
239                write!(formatter, "{} ({code})", self.detail)
240            }
241            _ => formatter.write_str(&self.detail),
242        }
243    }
244}