1use crate::router::{Hop, RouteStop};
2use std::path::PathBuf;
3
4pub type Result<T> = std::result::Result<T, Error>;
5
6#[derive(Debug, thiserror::Error)]
7pub enum Error {
8 #[error("config error: {0}")]
9 Config(String),
10 #[error("failed to read {path}: {source}")]
11 Io {
12 path: PathBuf,
13 #[source]
14 source: std::io::Error,
15 },
16 #[error("failed to parse {path}: {message}")]
17 Parse { path: PathBuf, message: String },
18 #[error("provider error: {0}")]
19 Provider(ProviderFailure),
20 #[error("session error: {0}")]
21 Session(String),
22 #[error("agent stopped after {0} iterations without a final answer")]
23 MaxIterations(usize),
24 #[error("cancelled")]
25 Cancelled,
26 #[error("stopped by a hook: {0}")]
29 Stopped(String),
30 #[error("{0}")]
34 Vision(String),
35 #[error("{}", .0.hint())]
39 AwaitingApproval(crate::approvals::Waiting),
40 #[error("the reply did not match the requested schema: {error}")]
45 Unparsed { error: String, reply: String },
46}
47
48impl From<rusqlite::Error> for Error {
52 fn from(e: rusqlite::Error) -> Self {
53 Error::Session(e.to_string())
54 }
55}
56
57impl Error {
58 pub fn io(path: impl Into<PathBuf>, source: std::io::Error) -> Self {
59 Error::Io {
60 path: path.into(),
61 source,
62 }
63 }
64
65 pub fn provider(message: impl Into<String>) -> Self {
68 Error::Provider(ProviderFailure::other(message))
69 }
70
71 pub fn provider_failure(&self) -> Option<&ProviderFailure> {
74 match self {
75 Error::Provider(f) => Some(f),
76 _ => None,
77 }
78 }
79}
80
81#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
87#[non_exhaustive]
88pub enum ProviderFailure {
89 #[error("could not reach {url}: {message}")]
95 Transport {
96 url: String,
97 message: String,
98 sent: bool,
99 },
100
101 #[error("unauthorized: {0}")]
103 Unauthorized(HttpFailure),
104
105 #[error("invalid request: {0}")]
108 InvalidRequest(HttpFailure),
109
110 #[error("{0}")]
112 Http(HttpFailure),
113
114 #[error("the reply was cut off before it finished: {message}")]
119 Truncated {
120 message: String,
121 streamed_chars: usize,
123 },
124
125 #[error("unexpected response: {message}")]
127 Response {
128 message: String,
129 body: Option<String>,
130 },
131
132 #[error("{}", describe_routed(route, trail, *stop, cause))]
136 Routed {
137 route: String,
139 trail: Vec<Hop>,
141 stop: RouteStop,
142 cause: Box<ProviderFailure>,
144 },
145}
146
147#[derive(Debug, Clone, PartialEq, Eq, Default)]
149pub struct HttpFailure {
150 pub status: u16,
151 pub body: String,
154 pub request_id: Option<String>,
156 pub retry_after_secs: Option<u64>,
158 pub hint: Option<String>,
161}
162
163impl std::fmt::Display for HttpFailure {
164 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
165 write!(f, "HTTP {}", self.status)?;
166 if !self.body.is_empty() {
167 write!(f, ": {}", self.body)?;
168 }
169 if let Some(id) = &self.request_id {
170 write!(f, " [request id {id}]")?;
171 }
172 if let Some(hint) = &self.hint {
173 write!(f, " — {hint}")?;
174 }
175 Ok(())
176 }
177}
178
179#[derive(Debug, Clone, Copy, PartialEq, Eq)]
182#[non_exhaustive]
183pub enum ProviderFailureKind {
184 Transport,
185 Unauthorized,
186 InvalidRequest,
187 Http,
188 Truncated,
189 Response,
190}
191
192impl ProviderFailureKind {
193 pub fn as_str(self) -> &'static str {
194 match self {
195 ProviderFailureKind::Transport => "transport",
196 ProviderFailureKind::Unauthorized => "unauthorized",
197 ProviderFailureKind::InvalidRequest => "invalid_request",
198 ProviderFailureKind::Http => "http",
199 ProviderFailureKind::Truncated => "truncated",
200 ProviderFailureKind::Response => "response",
201 }
202 }
203}
204
205impl std::fmt::Display for ProviderFailureKind {
206 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
207 f.write_str(self.as_str())
208 }
209}
210
211impl ProviderFailure {
212 pub fn other(message: impl Into<String>) -> Self {
215 ProviderFailure::Response {
216 message: message.into(),
217 body: None,
218 }
219 }
220
221 pub fn kind(&self) -> ProviderFailureKind {
222 match self {
223 ProviderFailure::Transport { .. } => ProviderFailureKind::Transport,
224 ProviderFailure::Unauthorized(_) => ProviderFailureKind::Unauthorized,
225 ProviderFailure::InvalidRequest(_) => ProviderFailureKind::InvalidRequest,
226 ProviderFailure::Http(_) => ProviderFailureKind::Http,
227 ProviderFailure::Truncated { .. } => ProviderFailureKind::Truncated,
228 ProviderFailure::Response { .. } => ProviderFailureKind::Response,
229 ProviderFailure::Routed { cause, .. } => cause.kind(),
230 }
231 }
232
233 pub fn short_reason(&self) -> String {
236 match self {
237 ProviderFailure::Transport { message, .. } if message.contains("timed out") => {
238 "timeout".into()
239 }
240 ProviderFailure::Transport { message, .. }
241 if message.contains("could not be established") =>
242 {
243 "unreachable".into()
244 }
245 ProviderFailure::Transport { .. } => "connection error".into(),
246 ProviderFailure::Unauthorized(h)
247 | ProviderFailure::InvalidRequest(h)
248 | ProviderFailure::Http(h) => format!("HTTP {}", h.status),
249 ProviderFailure::Truncated { .. } => "stream cut".into(),
250 ProviderFailure::Response { .. } => "unreadable reply".into(),
251 ProviderFailure::Routed { cause, .. } => cause.short_reason(),
252 }
253 }
254
255 pub fn after_send(&self) -> bool {
262 match self {
263 ProviderFailure::Transport { sent, .. } => *sent,
264 ProviderFailure::Routed { cause, .. } => cause.after_send(),
265 _ => false,
266 }
267 }
268
269 pub fn is_retryable(&self) -> bool {
273 match self {
274 ProviderFailure::Transport { .. } => true,
279 ProviderFailure::Truncated { .. } => true,
280 ProviderFailure::Http(h) => is_retryable_status(h.status),
281 ProviderFailure::Unauthorized(_) | ProviderFailure::InvalidRequest(_) => false,
282 ProviderFailure::Response { .. } => false,
283 ProviderFailure::Routed { cause, .. } => cause.is_retryable(),
284 }
285 }
286
287 pub fn status(&self) -> Option<u16> {
288 match self {
289 ProviderFailure::Unauthorized(h)
290 | ProviderFailure::InvalidRequest(h)
291 | ProviderFailure::Http(h) => Some(h.status),
292 ProviderFailure::Routed { cause, .. } => cause.status(),
293 _ => None,
294 }
295 }
296
297 pub fn body(&self) -> Option<&str> {
299 match self {
300 ProviderFailure::Unauthorized(h)
301 | ProviderFailure::InvalidRequest(h)
302 | ProviderFailure::Http(h) => Some(&h.body),
303 ProviderFailure::Response { body, .. } => body.as_deref(),
304 ProviderFailure::Routed { cause, .. } => cause.body(),
305 _ => None,
306 }
307 }
308
309 pub fn request_id(&self) -> Option<&str> {
310 match self {
311 ProviderFailure::Unauthorized(h)
312 | ProviderFailure::InvalidRequest(h)
313 | ProviderFailure::Http(h) => h.request_id.as_deref(),
314 ProviderFailure::Routed { cause, .. } => cause.request_id(),
315 _ => None,
316 }
317 }
318
319 pub fn retry_after_secs(&self) -> Option<u64> {
321 match self {
322 ProviderFailure::Unauthorized(h)
323 | ProviderFailure::InvalidRequest(h)
324 | ProviderFailure::Http(h) => h.retry_after_secs,
325 ProviderFailure::Routed { cause, .. } => cause.retry_after_secs(),
326 _ => None,
327 }
328 }
329
330 pub fn hint(&self) -> Option<&str> {
332 match self {
333 ProviderFailure::Unauthorized(h)
334 | ProviderFailure::InvalidRequest(h)
335 | ProviderFailure::Http(h) => h.hint.as_deref(),
336 ProviderFailure::Routed { cause, .. } => cause.hint(),
337 _ => None,
338 }
339 }
340}
341
342fn describe_routed(route: &str, trail: &[Hop], stop: RouteStop, cause: &ProviderFailure) -> String {
343 let hopped = |trail: &[Hop]| {
344 trail
345 .iter()
346 .map(|h| format!("{}: {}", h.from, h.reason))
347 .collect::<Vec<_>>()
348 .join("; ")
349 };
350 match stop {
351 RouteStop::Failed if trail.is_empty() => format!("route `{route}` failed: {cause}"),
352 RouteStop::Failed => format!(
353 "route `{route}` failed: {cause} (earlier: {})",
354 hopped(trail)
355 ),
356 RouteStop::Exhausted => format!(
357 "every route failed ({}; {route}: {}); the last said: {cause}",
358 hopped(trail),
359 cause.short_reason()
360 ),
361 RouteStop::AfterText => format!(
362 "route `{route}` failed after it had started answering: {cause}. The text was \
363 already shown, so the turn was not replayed on the next route"
364 ),
365 }
366}
367
368pub fn is_retryable_status(status: u16) -> bool {
371 status == 408 || status == 429 || (500..600).contains(&status)
372}
373
374impl From<&str> for ProviderFailure {
377 fn from(s: &str) -> Self {
378 ProviderFailure::other(s)
379 }
380}
381
382impl From<String> for ProviderFailure {
383 fn from(s: String) -> Self {
384 ProviderFailure::other(s)
385 }
386}
387
388impl From<ProviderFailure> for Error {
389 fn from(f: ProviderFailure) -> Self {
390 Error::Provider(f)
391 }
392}
393
394#[cfg(test)]
395mod tests {
396 use super::*;
397
398 fn http(status: u16) -> HttpFailure {
399 HttpFailure {
400 status,
401 body: "{\"error\":\"nope\"}".into(),
402 request_id: Some("req-7".into()),
403 retry_after_secs: None,
404 hint: None,
405 }
406 }
407
408 #[test]
409 fn the_retry_policy_is_the_servers_transient_trouble_and_nothing_else() {
410 assert!(is_retryable_status(408));
411 assert!(is_retryable_status(429));
412 assert!(is_retryable_status(500));
413 assert!(is_retryable_status(503));
414 assert!(is_retryable_status(599));
415 assert!(!is_retryable_status(400));
416 assert!(!is_retryable_status(401));
417 assert!(!is_retryable_status(404));
418 assert!(!is_retryable_status(422));
419 assert!(!is_retryable_status(200));
420 }
421
422 #[test]
423 fn each_variant_answers_the_questions_a_caller_asks() {
424 let transport = ProviderFailure::Transport {
425 url: "http://127.0.0.1:9/v1".into(),
426 message: "connection reset by peer".into(),
427 sent: true,
428 };
429 assert_eq!(transport.kind(), ProviderFailureKind::Transport);
430 assert_eq!(transport.kind().as_str(), "transport");
431 assert!(
432 transport.is_retryable(),
433 "an unanswered request is safe to repeat"
434 );
435 assert_eq!(transport.status(), None);
436 assert_eq!(transport.body(), None);
437
438 let auth = ProviderFailure::Unauthorized(http(401));
439 assert_eq!(auth.kind(), ProviderFailureKind::Unauthorized);
440 assert!(
441 !auth.is_retryable(),
442 "a wrong key fails the same way every time"
443 );
444 assert_eq!(auth.status(), Some(401));
445 assert_eq!(auth.body(), Some("{\"error\":\"nope\"}"));
446 assert_eq!(auth.request_id(), Some("req-7"));
447
448 let bad = ProviderFailure::InvalidRequest(http(400));
449 assert!(!bad.is_retryable());
450 assert_eq!(bad.kind(), ProviderFailureKind::InvalidRequest);
451
452 assert!(ProviderFailure::Http(http(503)).is_retryable());
453 assert!(ProviderFailure::Http(http(429)).is_retryable());
454 assert!(!ProviderFailure::Http(http(404)).is_retryable());
455
456 let cut = ProviderFailure::Truncated {
457 message: "stream ended".into(),
458 streamed_chars: 12,
459 };
460 assert!(cut.is_retryable());
461 assert_eq!(cut.kind(), ProviderFailureKind::Truncated);
462 assert_eq!(cut.status(), None);
463
464 let odd = ProviderFailure::other("no choices");
465 assert!(
466 !odd.is_retryable(),
467 "a reply we cannot read will read the same twice"
468 );
469 assert_eq!(odd.kind(), ProviderFailureKind::Response);
470 }
471
472 #[test]
473 fn an_http_failure_displays_the_things_worth_quoting() {
474 let mut f = http(500);
475 f.body = "upstream exploded".into();
476 let rendered = ProviderFailure::Http(f).to_string();
477 assert!(rendered.contains("HTTP 500"), "{rendered}");
478 assert!(rendered.contains("upstream exploded"), "{rendered}");
479 assert!(rendered.contains("req-7"), "{rendered}");
480
481 let hinted = ProviderFailure::InvalidRequest(HttpFailure {
482 status: 400,
483 body: "unknown field".into(),
484 request_id: None,
485 retry_after_secs: None,
486 hint: Some("provider.top_p is not supported by model m".into()),
487 })
488 .to_string();
489 assert!(hinted.contains("provider.top_p"), "{hinted}");
490 }
491
492 #[test]
493 fn a_plain_message_still_becomes_a_provider_error() {
494 let e = Error::provider("script exhausted");
495 assert_eq!(
496 e.to_string(),
497 "provider error: unexpected response: script exhausted"
498 );
499 let from_string: Error = Error::Provider("boom".to_string().into());
500 assert_eq!(
501 from_string.to_string(),
502 "provider error: unexpected response: boom"
503 );
504 }
505}