eclipse-core 0.15.1

Core library for eclipse: providers, tools, sessions, config, runtime
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
use crate::router::{Hop, RouteStop};
use std::path::PathBuf;

pub type Result<T> = std::result::Result<T, Error>;

#[derive(Debug, thiserror::Error)]
pub enum Error {
    #[error("config error: {0}")]
    Config(String),
    #[error("failed to read {path}: {source}")]
    Io {
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },
    #[error("failed to parse {path}: {message}")]
    Parse { path: PathBuf, message: String },
    #[error("provider error: {0}")]
    Provider(ProviderFailure),
    #[error("session error: {0}")]
    Session(String),
    #[error("agent stopped after {0} iterations without a final answer")]
    MaxIterations(usize),
    #[error("cancelled")]
    Cancelled,
    /// A hook ended the run. Distinct from cancellation because nobody pressed anything: the
    /// reason is the point, and a caller that retries a cancelled run should not retry this.
    #[error("stopped by a hook: {0}")]
    Stopped(String),
    /// The turn was not started because it could not carry its pictures (`#346`). The sentence is
    /// the refusal itself — what cannot be done and what to change — because every surface prints
    /// it as it is, and two surfaces wording it differently is how a bug gets reported twice.
    #[error("{0}")]
    Vision(String),
    /// The run stopped on an approval nobody has answered: the calls are recorded, the turn is
    /// not, and any later process can answer them. Not a cancellation — nothing was stopped on
    /// purpose — and not a denial, which would be a decision made on the user's behalf.
    #[error("{}", .0.hint())]
    AwaitingApproval(crate::approvals::Waiting),
    /// The model answered, and the answer was not the shape the caller asked for — twice: once
    /// as it came, and once after a retry that carried the parse error back to it. The reply is
    /// kept because the failure is about what it wrote, and a caller that only gets "invalid
    /// JSON" has to re-run the whole thing to find out what.
    #[error("the reply did not match the requested schema: {error}")]
    Unparsed { error: String, reply: String },
}

/// A database failure is a failure to store a session — the one thing the caller was
/// trying to do — so it reports as a session error rather than a new variant callers would
/// have to match on.
impl From<rusqlite::Error> for Error {
    fn from(e: rusqlite::Error) -> Self {
        Error::Session(e.to_string())
    }
}

impl Error {
    pub fn io(path: impl Into<PathBuf>, source: std::io::Error) -> Self {
        Error::Io {
            path: path.into(),
            source,
        }
    }

    /// A provider failure with nothing but an explanation, for call sites that have no more
    /// structure to offer than a message.
    pub fn provider(message: impl Into<String>) -> Self {
        Error::Provider(ProviderFailure::other(message))
    }

    /// The provider failure inside this error, when it is one. A caller that cares about the
    /// status or the retry policy asks here instead of matching the variant itself.
    pub fn provider_failure(&self) -> Option<&ProviderFailure> {
        match self {
            Error::Provider(f) => Some(f),
            _ => None,
        }
    }
}

/// Which way talking to the model server failed.
///
/// Kept as structure rather than a formatted string because two callers need to ask
/// questions about it: the retry loop wants `is_retryable()`, and the operator wants the
/// status, the body the server actually sent and the id to quote at support.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum ProviderFailure {
    /// No answer at all: DNS, connection refused or reset, TLS, timeout.
    ///
    /// `sent` says whether the request had already gone out when this happened, because that is the
    /// difference between a free retry and a billed one: a connect-stage failure never reached the
    /// server, while a reset after the body was written may have been read, charged, or half-run.
    #[error("could not reach {url}: {message}")]
    Transport {
        url: String,
        message: String,
        sent: bool,
    },

    /// 401 or 403: the key is missing, wrong, or not allowed to use this model.
    #[error("unauthorized: {0}")]
    Unauthorized(HttpFailure),

    /// 400, 404, 405, 422: the request is wrong for this server or this model — an option
    /// it does not know, a model name it does not serve, a tool schema it cannot parse.
    #[error("invalid request: {0}")]
    InvalidRequest(HttpFailure),

    /// Any other non-2xx answer.
    #[error("{0}")]
    Http(HttpFailure),

    /// The stream ended before the model said it was done. Retryable, but see
    /// [`ProviderFailure::is_retryable`] and the rule the provider applies: only when
    /// nothing has been shown to the reader yet, because replaying text they already read
    /// is worse than failing.
    #[error("the reply was cut off before it finished: {message}")]
    Truncated {
        message: String,
        /// How much text had arrived before the cut, for the message.
        streamed_chars: usize,
    },

    /// A successful-looking answer that is not a chat completion we can read.
    #[error("unexpected response: {message}")]
    Response {
        message: String,
        body: Option<String>,
    },

    /// A failure that came out of a [`Router`](crate::router::Router), carrying the route it
    /// happened on and the hops taken before it. Every question a caller asks about a failure
    /// is answered by `cause`; this wrapper only adds *where*.
    #[error("{}", describe_routed(route, trail, *stop, cause))]
    Routed {
        /// The route that was being tried when the run stopped.
        route: String,
        /// The hops made before this failure, oldest first.
        trail: Vec<Hop>,
        stop: RouteStop,
        /// Named `cause`, not `source`, so thiserror does not treat it as the error source.
        cause: Box<ProviderFailure>,
    },
}

/// The parts of a non-2xx answer worth keeping.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct HttpFailure {
    pub status: u16,
    /// The server's own words, clipped. Usually a JSON error object; sometimes an HTML
    /// page from a proxy, which is itself the diagnosis.
    pub body: String,
    /// `x-request-id` (or `request-id`) if the server sent one — the thing support asks for.
    pub request_id: Option<String>,
    /// `Retry-After` in seconds, when the server said how long to wait.
    pub retry_after_secs: Option<u64>,
    /// What to do about it, when we can tell. Names the option and the model, because
    /// "HTTP 400: unknown field" is not something a person can act on.
    pub hint: Option<String>,
}

impl std::fmt::Display for HttpFailure {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "HTTP {}", self.status)?;
        if !self.body.is_empty() {
            write!(f, ": {}", self.body)?;
        }
        if let Some(id) = &self.request_id {
            write!(f, " [request id {id}]")?;
        }
        if let Some(hint) = &self.hint {
            write!(f, " — {hint}")?;
        }
        Ok(())
    }
}

/// [`ProviderFailure`] without its payload, for callers that match on the shape of the
/// failure rather than its contents.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ProviderFailureKind {
    Transport,
    Unauthorized,
    InvalidRequest,
    Http,
    Truncated,
    Response,
}

impl ProviderFailureKind {
    pub fn as_str(self) -> &'static str {
        match self {
            ProviderFailureKind::Transport => "transport",
            ProviderFailureKind::Unauthorized => "unauthorized",
            ProviderFailureKind::InvalidRequest => "invalid_request",
            ProviderFailureKind::Http => "http",
            ProviderFailureKind::Truncated => "truncated",
            ProviderFailureKind::Response => "response",
        }
    }
}

impl std::fmt::Display for ProviderFailureKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

impl ProviderFailure {
    /// A failure with nothing but an explanation: a reply we could not read, a test double,
    /// an error the server put inside a stream.
    pub fn other(message: impl Into<String>) -> Self {
        ProviderFailure::Response {
            message: message.into(),
            body: None,
        }
    }

    pub fn kind(&self) -> ProviderFailureKind {
        match self {
            ProviderFailure::Transport { .. } => ProviderFailureKind::Transport,
            ProviderFailure::Unauthorized(_) => ProviderFailureKind::Unauthorized,
            ProviderFailure::InvalidRequest(_) => ProviderFailureKind::InvalidRequest,
            ProviderFailure::Http(_) => ProviderFailureKind::Http,
            ProviderFailure::Truncated { .. } => ProviderFailureKind::Truncated,
            ProviderFailure::Response { .. } => ProviderFailureKind::Response,
            ProviderFailure::Routed { cause, .. } => cause.kind(),
        }
    }

    /// A few words for a readout: `timeout`, `HTTP 503`, `stream cut`. The full text is the
    /// failure's `Display`; this is what fits after an arrow.
    pub fn short_reason(&self) -> String {
        match self {
            ProviderFailure::Transport { message, .. } if message.contains("timed out") => {
                "timeout".into()
            }
            ProviderFailure::Transport { message, .. }
                if message.contains("could not be established") =>
            {
                "unreachable".into()
            }
            ProviderFailure::Transport { .. } => "connection error".into(),
            ProviderFailure::Unauthorized(h)
            | ProviderFailure::InvalidRequest(h)
            | ProviderFailure::Http(h) => format!("HTTP {}", h.status),
            ProviderFailure::Truncated { .. } => "stream cut".into(),
            ProviderFailure::Response { .. } => "unreadable reply".into(),
            ProviderFailure::Routed { cause, .. } => cause.short_reason(),
        }
    }

    /// Whether the request had already been written to the socket when this failure happened.
    ///
    /// `/chat/completions` is not idempotent and it is billed, so a drop after the body went out may
    /// cost a whole generation that repeating will pay for again. A connect-stage failure costs
    /// nothing to repeat. Everything that is not a transport failure answers `false`: it has its own
    /// retry rule.
    pub fn after_send(&self) -> bool {
        match self {
            ProviderFailure::Transport { sent, .. } => *sent,
            ProviderFailure::Routed { cause, .. } => cause.after_send(),
            _ => false,
        }
    }

    /// Whether repeating the request could plausibly work. Deliberately conservative: a
    /// wrong key or a rejected option will fail the same way every time, and retrying it
    /// only wastes the operator's morning.
    pub fn is_retryable(&self) -> bool {
        match self {
            // Both stages are *trouble*, which is what this answers: whether another route is worth
            // trying. Whether the same request may be repeated is a narrower question, and the
            // provider answers it with [`Self::after_send`] because only it knows whether repeating
            // has been allowed.
            ProviderFailure::Transport { .. } => true,
            ProviderFailure::Truncated { .. } => true,
            ProviderFailure::Http(h) => is_retryable_status(h.status),
            ProviderFailure::Unauthorized(_) | ProviderFailure::InvalidRequest(_) => false,
            ProviderFailure::Response { .. } => false,
            ProviderFailure::Routed { cause, .. } => cause.is_retryable(),
        }
    }

    pub fn status(&self) -> Option<u16> {
        match self {
            ProviderFailure::Unauthorized(h)
            | ProviderFailure::InvalidRequest(h)
            | ProviderFailure::Http(h) => Some(h.status),
            ProviderFailure::Routed { cause, .. } => cause.status(),
            _ => None,
        }
    }

    /// The server's own words, when there were any.
    pub fn body(&self) -> Option<&str> {
        match self {
            ProviderFailure::Unauthorized(h)
            | ProviderFailure::InvalidRequest(h)
            | ProviderFailure::Http(h) => Some(&h.body),
            ProviderFailure::Response { body, .. } => body.as_deref(),
            ProviderFailure::Routed { cause, .. } => cause.body(),
            _ => None,
        }
    }

    pub fn request_id(&self) -> Option<&str> {
        match self {
            ProviderFailure::Unauthorized(h)
            | ProviderFailure::InvalidRequest(h)
            | ProviderFailure::Http(h) => h.request_id.as_deref(),
            ProviderFailure::Routed { cause, .. } => cause.request_id(),
            _ => None,
        }
    }

    /// How long the server asked us to wait, in seconds.
    pub fn retry_after_secs(&self) -> Option<u64> {
        match self {
            ProviderFailure::Unauthorized(h)
            | ProviderFailure::InvalidRequest(h)
            | ProviderFailure::Http(h) => h.retry_after_secs,
            ProviderFailure::Routed { cause, .. } => cause.retry_after_secs(),
            _ => None,
        }
    }

    /// What the operator should do next, when we can say.
    pub fn hint(&self) -> Option<&str> {
        match self {
            ProviderFailure::Unauthorized(h)
            | ProviderFailure::InvalidRequest(h)
            | ProviderFailure::Http(h) => h.hint.as_deref(),
            ProviderFailure::Routed { cause, .. } => cause.hint(),
            _ => None,
        }
    }
}

fn describe_routed(route: &str, trail: &[Hop], stop: RouteStop, cause: &ProviderFailure) -> String {
    let hopped = |trail: &[Hop]| {
        trail
            .iter()
            .map(|h| format!("{}: {}", h.from, h.reason))
            .collect::<Vec<_>>()
            .join("; ")
    };
    match stop {
        RouteStop::Failed if trail.is_empty() => format!("route `{route}` failed: {cause}"),
        RouteStop::Failed => format!(
            "route `{route}` failed: {cause} (earlier: {})",
            hopped(trail)
        ),
        RouteStop::Exhausted => format!(
            "every route failed ({}; {route}: {}); the last said: {cause}",
            hopped(trail),
            cause.short_reason()
        ),
        RouteStop::AfterText => format!(
            "route `{route}` failed after it had started answering: {cause}. The text was \
             already shown, so the turn was not replayed on the next route"
        ),
    }
}

/// 429 and 5xx are the server's own transient trouble; 408 is a timeout it admits to.
/// Everything else in 4xx is a mistake in the request that repeating will not fix.
pub fn is_retryable_status(status: u16) -> bool {
    status == 408 || status == 429 || (500..600).contains(&status)
}

/// Keep a string-to-failure conversion available so a plain message is never a compile
/// error in a hurry — but prefer a real variant where one exists.
impl From<&str> for ProviderFailure {
    fn from(s: &str) -> Self {
        ProviderFailure::other(s)
    }
}

impl From<String> for ProviderFailure {
    fn from(s: String) -> Self {
        ProviderFailure::other(s)
    }
}

impl From<ProviderFailure> for Error {
    fn from(f: ProviderFailure) -> Self {
        Error::Provider(f)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn http(status: u16) -> HttpFailure {
        HttpFailure {
            status,
            body: "{\"error\":\"nope\"}".into(),
            request_id: Some("req-7".into()),
            retry_after_secs: None,
            hint: None,
        }
    }

    #[test]
    fn the_retry_policy_is_the_servers_transient_trouble_and_nothing_else() {
        assert!(is_retryable_status(408));
        assert!(is_retryable_status(429));
        assert!(is_retryable_status(500));
        assert!(is_retryable_status(503));
        assert!(is_retryable_status(599));
        assert!(!is_retryable_status(400));
        assert!(!is_retryable_status(401));
        assert!(!is_retryable_status(404));
        assert!(!is_retryable_status(422));
        assert!(!is_retryable_status(200));
    }

    #[test]
    fn each_variant_answers_the_questions_a_caller_asks() {
        let transport = ProviderFailure::Transport {
            url: "http://127.0.0.1:9/v1".into(),
            message: "connection reset by peer".into(),
            sent: true,
        };
        assert_eq!(transport.kind(), ProviderFailureKind::Transport);
        assert_eq!(transport.kind().as_str(), "transport");
        assert!(
            transport.is_retryable(),
            "an unanswered request is safe to repeat"
        );
        assert_eq!(transport.status(), None);
        assert_eq!(transport.body(), None);

        let auth = ProviderFailure::Unauthorized(http(401));
        assert_eq!(auth.kind(), ProviderFailureKind::Unauthorized);
        assert!(
            !auth.is_retryable(),
            "a wrong key fails the same way every time"
        );
        assert_eq!(auth.status(), Some(401));
        assert_eq!(auth.body(), Some("{\"error\":\"nope\"}"));
        assert_eq!(auth.request_id(), Some("req-7"));

        let bad = ProviderFailure::InvalidRequest(http(400));
        assert!(!bad.is_retryable());
        assert_eq!(bad.kind(), ProviderFailureKind::InvalidRequest);

        assert!(ProviderFailure::Http(http(503)).is_retryable());
        assert!(ProviderFailure::Http(http(429)).is_retryable());
        assert!(!ProviderFailure::Http(http(404)).is_retryable());

        let cut = ProviderFailure::Truncated {
            message: "stream ended".into(),
            streamed_chars: 12,
        };
        assert!(cut.is_retryable());
        assert_eq!(cut.kind(), ProviderFailureKind::Truncated);
        assert_eq!(cut.status(), None);

        let odd = ProviderFailure::other("no choices");
        assert!(
            !odd.is_retryable(),
            "a reply we cannot read will read the same twice"
        );
        assert_eq!(odd.kind(), ProviderFailureKind::Response);
    }

    #[test]
    fn an_http_failure_displays_the_things_worth_quoting() {
        let mut f = http(500);
        f.body = "upstream exploded".into();
        let rendered = ProviderFailure::Http(f).to_string();
        assert!(rendered.contains("HTTP 500"), "{rendered}");
        assert!(rendered.contains("upstream exploded"), "{rendered}");
        assert!(rendered.contains("req-7"), "{rendered}");

        let hinted = ProviderFailure::InvalidRequest(HttpFailure {
            status: 400,
            body: "unknown field".into(),
            request_id: None,
            retry_after_secs: None,
            hint: Some("provider.top_p is not supported by model m".into()),
        })
        .to_string();
        assert!(hinted.contains("provider.top_p"), "{hinted}");
    }

    #[test]
    fn a_plain_message_still_becomes_a_provider_error() {
        let e = Error::provider("script exhausted");
        assert_eq!(
            e.to_string(),
            "provider error: unexpected response: script exhausted"
        );
        let from_string: Error = Error::Provider("boom".to_string().into());
        assert_eq!(
            from_string.to_string(),
            "provider error: unexpected response: boom"
        );
    }
}