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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
//! Model routes: a [`ChatProvider`] that tries a chain of providers in order.
//!
//! It is a provider rather than a feature of the loop so the loop stays untouched: the runtime
//! still holds one `&dyn ChatProvider` per run and asks it for a reply. It lives in its own
//! module because it knows nothing about HTTP; `provider.rs` is about one server, this is about
//! the policy for moving between servers, and each is easier to read without the other.
//!
//! The policy, in one place:
//!
//! - One attempt per route, in chain order. A route that failed is never tried again in the same
//!   run, and a route that answered is kept for the turns after it.
//! - A hop happens only when the failure says the server was the problem and the request was
//!   fine: [`ProviderFailure::is_retryable`] (no answer, 408/429/5xx, a cut stream). A wrong
//!   key, a refused option or a 400 fails the run and names the route, because moving on would
//!   hide a config error behind a slower success.
//! - Each route keeps its own retry budget (`max_retries`, with backoff) before the router moves
//!   on. `max_retries = 0` on a route makes it hop at once.
//! - Streaming: once any text of a turn has reached the caller, a transient failure does not hop.
//!   Replaying the turn on another route would print its beginning twice, so the run fails and
//!   says why. This is the same rule M10 applies to one route's cut stream, applied one level up.
//! - Every hop is recorded with its reason and can be read back with [`Router::hops`].

use crate::error::{Error, ProviderFailure, Result};
use crate::hooks::RequestPatch;
use crate::message::Message;
use crate::provider::ChatProvider;
use crate::stream::DeltaFn;
use crate::tools::ToolSpec;
use crate::usage::TurnUsage;
use async_trait::async_trait;
use std::fmt;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, MutexGuard};

/// One move from a route that failed to the next one, and why.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Hop {
    pub from: String,
    pub to: String,
    /// A few words: `timeout`, `unreachable`, `HTTP 503`, `stream cut`.
    pub reason: String,
}

impl fmt::Display for Hop {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} \u{2192} {}: {}", self.from, self.to, self.reason)
    }
}

/// Render hops as one readout line: `route: local → big (timeout)`, or
/// `route: local → big → cloud (timeout; HTTP 503)` when it hopped twice. Empty when nothing
/// hopped, because silence is the normal case.
pub fn describe_hops(hops: &[Hop]) -> Option<String> {
    let first = hops.first()?;
    let mut chain = first.from.clone();
    for h in hops {
        chain.push_str(" \u{2192} ");
        chain.push_str(&h.to);
    }
    let reasons: Vec<&str> = hops.iter().map(|h| h.reason.as_str()).collect();
    Some(format!("route: {chain} ({})", reasons.join("; ")))
}

/// Why a [`ProviderFailure::Routed`] ended the run.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RouteStop {
    /// The failure was not transient (or there was no route left but this one): the run fails
    /// here and names the route.
    Failed,
    /// Every route in the chain failed transiently.
    Exhausted,
    /// The failure was transient but text had already reached the caller, so the turn was not
    /// replayed on the next route.
    AfterText,
}

/// What a readout needs to say about one route: its name and what it serves.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RouteInfo {
    pub name: String,
    pub model: String,
    pub endpoint: String,
}

/// The jobs the agent does on its own behalf that can be sent to a route of their own.
///
/// Only roles with a consumer are listed. `summary` is the summary of trimmed turns
/// (`[provider] aux`); `delegate` is the child agent a `delegate` call starts
/// (`[provider] delegate`). There is no `title` role: nothing generates a session title (a
/// title is a `rename`, typed by the user), so a `title` row would be a config key with no
/// consumer.
pub const ROLES: &[&str] = &["judgement", "delegate"];

/// Which route one role uses, and whether the config said so.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RoleRoute {
    pub role: &'static str,
    pub route: String,
    /// `false` when the role's own key is unset, or when a pin has overruled it, and the role
    /// uses the route the run is on.
    pub set: bool,
    /// `true` when `--route` / `ECLIPSE_ROUTE` sent this role to the pinned route whatever the
    /// config says: a pin is a statement about where the text may go, so it wins.
    pub pinned: bool,
}

impl RoleRoute {
    /// The `[provider]` key that sets this role's route.
    pub fn key(&self) -> &'static str {
        match self.role {
            "delegate" => "delegate",
            _ => "aux",
        }
    }
}

impl fmt::Display for RoleRoute {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} \u{2192} {}", self.role, self.route)?;
        if self.pinned {
            write!(f, " (pinned)")?;
        } else if !self.set {
            write!(f, " (no {} route set)", self.key())?;
        }
        Ok(())
    }
}

/// Which route each role uses. The one answer to the question: `eclipse config show`, `/status`
/// and the startup panel all print this, so they cannot disagree. `aux` is `[provider] aux` and
/// `delegate` is `[provider] delegate`; `selected` is the first route of the chain, which is
/// where a role with no route of its own goes.
///
/// `pinned` collapses every role onto `selected`: `--route` / `ECLIPSE_ROUTE` says where this
/// run's text may go, and a role route that ignored it would quietly send a summary or a child
/// somewhere the caller ruled out.
pub fn role_table(
    aux: Option<&str>,
    delegate: Option<&str>,
    selected: &str,
    pinned: bool,
) -> Vec<RoleRoute> {
    ROLES
        .iter()
        .map(|role| {
            let own = match *role {
                "delegate" => delegate,
                _ => aux,
            };
            RoleRoute {
                role,
                route: if pinned {
                    selected.to_string()
                } else {
                    own.unwrap_or(selected).to_string()
                },
                set: !pinned && own.is_some(),
                pinned,
            }
        })
        .collect()
}

/// One link of the chain: a name and the provider that talks to it.
pub struct RouterEntry {
    pub name: String,
    pub provider: Arc<dyn ChatProvider>,
}

struct State {
    /// The route the next turn starts on. Only ever moves forward.
    next: usize,
    hops: Vec<Hop>,
    usage: Option<TurnUsage>,
}

/// A chain of providers behind the [`ChatProvider`] interface. Build one per run: its state is
/// the run's record of which routes have already failed.
pub struct Router {
    entries: Vec<RouterEntry>,
    state: Mutex<State>,
}

/// The three ways the loop asks for a reply; the router forwards each unchanged.
enum Call<'a> {
    Chat,
    Stream(DeltaFn<'a>),
    Patched(DeltaFn<'a>, &'a RequestPatch),
}

impl Router {
    /// A router over `entries`, tried in order. An empty chain is refused: there would be
    /// nothing to answer, and the caller has a config error to report.
    pub fn new(entries: Vec<RouterEntry>) -> Result<Self> {
        if entries.is_empty() {
            return Err(Error::Config(
                "a router needs at least one route to try".into(),
            ));
        }
        Ok(Self {
            entries,
            state: Mutex::new(State {
                next: 0,
                hops: Vec::new(),
                usage: None,
            }),
        })
    }

    fn state(&self) -> MutexGuard<'_, State> {
        self.state.lock().unwrap_or_else(|e| e.into_inner())
    }

    /// The hops made so far in this run, oldest first.
    pub fn hops(&self) -> Vec<Hop> {
        self.state().hops.clone()
    }

    /// The route the next turn will start on: the one that answered last.
    pub fn current(&self) -> &str {
        let idx = self.state().next;
        self.entries.get(idx).map(|e| e.name.as_str()).unwrap_or("")
    }

    async fn dispatch(
        &self,
        messages: &[Message],
        tools: &[ToolSpec],
        call: Call<'_>,
    ) -> Result<Message> {
        let mut idx = self.state().next;
        loop {
            let Some(entry) = self.entries.get(idx) else {
                return Err(Error::provider("the route chain ran out of routes"));
            };
            // Counted per turn: a hop is only unsafe when the reader has already seen text.
            let shown = AtomicUsize::new(0);
            let result = match &call {
                Call::Chat => entry.provider.chat(messages, tools).await,
                Call::Stream(on_delta) => {
                    let counted = |d: crate::stream::Delta| {
                        if let crate::stream::Delta::Text(t) = &d {
                            shown.fetch_add(t.len(), Ordering::Relaxed);
                        }
                        on_delta(d);
                    };
                    entry.provider.chat_stream(messages, tools, &counted).await
                }
                Call::Patched(on_delta, patch) => {
                    let counted = |d: crate::stream::Delta| {
                        if let crate::stream::Delta::Text(t) = &d {
                            shown.fetch_add(t.len(), Ordering::Relaxed);
                        }
                        on_delta(d);
                    };
                    entry
                        .provider
                        .chat_stream_patched(messages, tools, &counted, patch)
                        .await
                }
            };
            let err = match result {
                Ok(reply) => {
                    let mut st = self.state();
                    st.next = idx;
                    st.usage = entry.provider.take_usage();
                    return Ok(reply);
                }
                Err(e) => e,
            };
            let Error::Provider(failure) = err else {
                return Err(err);
            };
            let trail = self.state().hops.clone();
            let next_name = self.entries.get(idx + 1).map(|e| e.name.clone());
            let has_next = next_name.is_some();
            let stop = if !failure.is_retryable() {
                Some(RouteStop::Failed)
            } else if !has_next {
                Some(if trail.is_empty() {
                    RouteStop::Failed
                } else {
                    RouteStop::Exhausted
                })
            } else if shown.load(Ordering::Relaxed) > 0 {
                Some(RouteStop::AfterText)
            } else {
                None
            };
            if let Some(stop) = stop {
                return Err(Error::Provider(ProviderFailure::Routed {
                    route: entry.name.clone(),
                    trail,
                    stop,
                    cause: Box::new(failure),
                }));
            }
            let mut st = self.state();
            st.hops.push(Hop {
                from: entry.name.clone(),
                to: next_name.unwrap_or_default(),
                reason: failure.short_reason(),
            });
            idx += 1;
            st.next = idx;
        }
    }
}

#[async_trait]
impl ChatProvider for Router {
    async fn chat(&self, messages: &[Message], tools: &[ToolSpec]) -> Result<Message> {
        self.dispatch(messages, tools, Call::Chat).await
    }

    async fn chat_stream(
        &self,
        messages: &[Message],
        tools: &[ToolSpec],
        on_delta: DeltaFn<'_>,
    ) -> Result<Message> {
        self.dispatch(messages, tools, Call::Stream(on_delta)).await
    }

    async fn chat_stream_patched(
        &self,
        messages: &[Message],
        tools: &[ToolSpec],
        on_delta: DeltaFn<'_>,
        patch: &RequestPatch,
    ) -> Result<Message> {
        self.dispatch(messages, tools, Call::Patched(on_delta, patch))
            .await
    }

    fn take_usage(&self) -> Option<TurnUsage> {
        self.state().usage.take()
    }

    /// What the route the next turn starts on declares (`#361`).
    ///
    /// The default says `false`, which would refuse a picture on every chain — the router is the
    /// provider a chained run holds, so this is the only place the answer can come from. The state
    /// lock is taken and released before asking, because a provider's `can_see` is its own.
    fn can_see(&self) -> bool {
        let next = {
            let state = self.state();
            state.next
        };
        self.entries
            .get(next)
            .map(|entry| entry.provider.can_see())
            .unwrap_or(false)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::error::HttpFailure;
    use std::collections::VecDeque;

    /// A provider that plays back a script, emitting some text first when asked to.
    struct Scripted {
        replies: Mutex<VecDeque<Result<Message>>>,
        text_first: Option<&'static str>,
        calls: AtomicUsize,
        patch_seen: Mutex<Option<bool>>,
        usage: Option<TurnUsage>,
    }

    impl Scripted {
        fn new(replies: Vec<Result<Message>>) -> Arc<Self> {
            Arc::new(Self {
                replies: Mutex::new(replies.into()),
                text_first: None,
                calls: AtomicUsize::new(0),
                patch_seen: Mutex::new(None),
                usage: None,
            })
        }

        fn streaming_then(text: &'static str, reply: Result<Message>) -> Arc<Self> {
            Arc::new(Self {
                replies: Mutex::new(vec![reply].into()),
                text_first: Some(text),
                calls: AtomicUsize::new(0),
                patch_seen: Mutex::new(None),
                usage: None,
            })
        }

        fn with_usage(replies: Vec<Result<Message>>, usage: TurnUsage) -> Arc<Self> {
            Arc::new(Self {
                replies: Mutex::new(replies.into()),
                text_first: None,
                calls: AtomicUsize::new(0),
                patch_seen: Mutex::new(None),
                usage: Some(usage),
            })
        }

        fn calls(&self) -> usize {
            self.calls.load(Ordering::SeqCst)
        }

        fn next(&self) -> Result<Message> {
            self.calls.fetch_add(1, Ordering::SeqCst);
            self.replies
                .lock()
                .unwrap_or_else(|e| e.into_inner())
                .pop_front()
                .unwrap_or_else(|| Err(Error::provider("script exhausted")))
        }
    }

    #[async_trait]
    impl ChatProvider for Scripted {
        async fn chat(&self, _: &[Message], _: &[ToolSpec]) -> Result<Message> {
            self.next()
        }

        async fn chat_stream(
            &self,
            _: &[Message],
            _: &[ToolSpec],
            on_delta: DeltaFn<'_>,
        ) -> Result<Message> {
            if let Some(t) = self.text_first {
                on_delta(crate::stream::Delta::Text(t.into()));
            }
            self.next()
        }

        async fn chat_stream_patched(
            &self,
            m: &[Message],
            t: &[ToolSpec],
            on_delta: DeltaFn<'_>,
            patch: &RequestPatch,
        ) -> Result<Message> {
            *self.patch_seen.lock().unwrap_or_else(|e| e.into_inner()) = Some(!patch.is_empty());
            self.chat_stream(m, t, on_delta).await
        }

        fn take_usage(&self) -> Option<TurnUsage> {
            self.usage.clone()
        }
    }

    fn reply(text: &str) -> Result<Message> {
        Ok(Message::assistant(text))
    }

    fn down() -> Result<Message> {
        Err(Error::Provider(ProviderFailure::Transport {
            url: "http://x/v1".into(),
            message: "the connection could not be established: refused".into(),
            sent: false,
        }))
    }

    fn timeout() -> Result<Message> {
        Err(Error::Provider(ProviderFailure::Transport {
            url: "http://x/v1".into(),
            message: "the request timed out: deadline".into(),
            sent: true,
        }))
    }

    fn http(status: u16) -> HttpFailure {
        HttpFailure {
            status,
            body: "nope".into(),
            ..HttpFailure::default()
        }
    }

    fn status(code: u16) -> Result<Message> {
        Err(Error::Provider(match code {
            401 => ProviderFailure::Unauthorized(http(code)),
            400 => ProviderFailure::InvalidRequest(http(code)),
            _ => ProviderFailure::Http(http(code)),
        }))
    }

    fn router(chain: &[(&str, &Arc<Scripted>)]) -> Router {
        let entries = chain
            .iter()
            .map(|(name, p)| RouterEntry {
                name: (*name).to_string(),
                provider: Arc::clone(*p) as Arc<dyn ChatProvider>,
            })
            .collect();
        Router::new(entries).unwrap()
    }

    fn text(m: &Message) -> &str {
        m.content.as_deref().unwrap_or("")
    }

    fn routed(e: Error) -> (String, Vec<Hop>, RouteStop, ProviderFailure) {
        match e {
            Error::Provider(ProviderFailure::Routed {
                route,
                trail,
                stop,
                cause,
            }) => (route, trail, stop, *cause),
            other => panic!("not a routed failure: {other}"),
        }
    }

    #[tokio::test]
    async fn a_router_with_nothing_to_try_is_refused() {
        assert!(Router::new(Vec::new()).is_err());
    }

    #[tokio::test]
    async fn the_first_route_answers_and_nothing_hops() {
        let a = Scripted::new(vec![reply("from a")]);
        let b = Scripted::new(vec![reply("from b")]);
        let r = router(&[("a", &a), ("b", &b)]);
        let got = r.chat(&[Message::user("hi")], &[]).await.unwrap();
        assert_eq!(text(&got), "from a");
        assert!(r.hops().is_empty());
        assert_eq!(b.calls(), 0);
        assert_eq!(describe_hops(&r.hops()), None);
    }

    #[tokio::test]
    async fn the_chain_is_tried_in_order_and_each_route_at_most_once() {
        let a = Scripted::new(vec![timeout(), reply("a again")]);
        let b = Scripted::new(vec![status(503), reply("b again")]);
        let c = Scripted::new(vec![reply("from c"), reply("c again")]);
        let r = router(&[("a", &a), ("b", &b), ("c", &c)]);
        let got = r.chat(&[Message::user("hi")], &[]).await.unwrap();
        assert_eq!(text(&got), "from c");
        assert_eq!((a.calls(), b.calls(), c.calls()), (1, 1, 1));
        // The next turn starts where the last one ended: a and b are not tried again.
        let again = r.chat(&[Message::user("more")], &[]).await.unwrap();
        assert_eq!(text(&again), "c again");
        assert_eq!((a.calls(), b.calls(), c.calls()), (1, 1, 2));
        assert_eq!(r.current(), "c");
    }

    #[tokio::test]
    async fn a_route_that_failed_is_not_tried_again_when_a_later_one_fails() {
        let a = Scripted::new(vec![down(), reply("never")]);
        let b = Scripted::new(vec![reply("one"), down()]);
        let c = Scripted::new(vec![reply("two")]);
        let r = router(&[("a", &a), ("b", &b), ("c", &c)]);
        assert_eq!(text(&r.chat(&[], &[]).await.unwrap()), "one");
        assert_eq!(text(&r.chat(&[], &[]).await.unwrap()), "two");
        assert_eq!(a.calls(), 1, "a failed in this run and stays failed");
    }

    #[tokio::test]
    async fn every_hop_is_recorded_with_why_it_happened() {
        let a = Scripted::new(vec![timeout()]);
        let b = Scripted::new(vec![status(503)]);
        let c = Scripted::new(vec![reply("ok")]);
        let r = router(&[("local", &a), ("big", &b), ("cloud", &c)]);
        r.chat(&[], &[]).await.unwrap();
        let hops = r.hops();
        assert_eq!(hops.len(), 2);
        assert_eq!(hops[0].to_string(), "local \u{2192} big: timeout");
        assert_eq!(hops[1].to_string(), "big \u{2192} cloud: HTTP 503");
        assert_eq!(
            describe_hops(&hops).as_deref(),
            Some("route: local \u{2192} big \u{2192} cloud (timeout; HTTP 503)")
        );
    }

    #[tokio::test]
    async fn a_refused_connection_hops_and_says_unreachable() {
        let a = Scripted::new(vec![down()]);
        let b = Scripted::new(vec![reply("ok")]);
        let r = router(&[("local", &a), ("big", &b)]);
        r.chat(&[], &[]).await.unwrap();
        assert_eq!(r.hops()[0].reason, "unreachable");
    }

    #[tokio::test]
    async fn a_401_on_the_first_route_does_not_hop_and_names_the_route() {
        let a = Scripted::new(vec![status(401)]);
        let b = Scripted::new(vec![reply("never asked")]);
        let r = router(&[("local", &a), ("big", &b)]);
        let (route, trail, stop, cause) = routed(r.chat(&[], &[]).await.unwrap_err());
        assert_eq!(route, "local");
        assert!(trail.is_empty());
        assert_eq!(stop, RouteStop::Failed);
        assert_eq!(cause.status(), Some(401));
        assert_eq!(b.calls(), 0, "a wrong key is not a transport hiccup");
        assert!(r.hops().is_empty());
    }

    #[tokio::test]
    async fn a_400_fails_the_run_instead_of_hiding_a_config_error() {
        let a = Scripted::new(vec![status(400)]);
        let b = Scripted::new(vec![reply("never asked")]);
        let r = router(&[("local", &a), ("big", &b)]);
        let err = r.chat(&[], &[]).await.unwrap_err();
        assert!(err.to_string().contains("route `local` failed"), "{err}");
        assert_eq!(b.calls(), 0);
    }

    #[tokio::test]
    async fn a_failure_after_a_hop_names_the_route_it_failed_on_and_the_earlier_hop() {
        let a = Scripted::new(vec![timeout()]);
        let b = Scripted::new(vec![status(401)]);
        let r = router(&[("local", &a), ("big", &b)]);
        let err = r.chat(&[], &[]).await.unwrap_err();
        let text = err.to_string();
        assert!(text.contains("route `big` failed"), "{text}");
        assert!(text.contains("local: timeout"), "{text}");
    }

    #[tokio::test]
    async fn an_exhausted_chain_lists_every_route_and_why_each_failed() {
        let a = Scripted::new(vec![timeout()]);
        let b = Scripted::new(vec![status(503)]);
        let r = router(&[("local", &a), ("big", &b)]);
        let err = r.chat(&[], &[]).await.unwrap_err();
        let shown = err.to_string();
        assert!(shown.contains("every route failed"), "{shown}");
        assert!(shown.contains("local: timeout"), "{shown}");
        assert!(shown.contains("big: HTTP 503"), "{shown}");
        let (route, trail, stop, _) = routed(err);
        assert_eq!(
            (route.as_str(), trail.len(), stop),
            ("big", 1, RouteStop::Exhausted)
        );
    }

    #[tokio::test]
    async fn a_single_route_that_fails_is_a_plain_failure_naming_it() {
        let a = Scripted::new(vec![timeout()]);
        let r = router(&[("local", &a)]);
        let (route, _, stop, cause) = routed(r.chat(&[], &[]).await.unwrap_err());
        assert_eq!((route.as_str(), stop), ("local", RouteStop::Failed));
        assert!(cause.is_retryable());
    }

    #[tokio::test]
    async fn a_stream_cut_before_any_text_hops_to_the_next_route() {
        let a = Scripted::new(vec![Err(Error::Provider(ProviderFailure::Truncated {
            message: "eof".into(),
            streamed_chars: 0,
        }))]);
        let b = Scripted::new(vec![reply("whole")]);
        let r = router(&[("a", &a), ("b", &b)]);
        let seen = Mutex::new(String::new());
        let got = r
            .chat_stream(&[], &[], &|d| {
                if let crate::stream::Delta::Text(t) = d {
                    seen.lock().unwrap().push_str(&t);
                }
            })
            .await
            .unwrap();
        assert_eq!(text(&got), "whole");
        assert_eq!(r.hops()[0].reason, "stream cut");
    }

    #[tokio::test]
    async fn a_stream_cut_after_text_is_not_replayed_on_the_next_route() {
        let a = Scripted::streaming_then(
            "half an ans",
            Err(Error::Provider(ProviderFailure::Truncated {
                message: "eof".into(),
                streamed_chars: 11,
            })),
        );
        let b = Scripted::new(vec![reply("the whole answer")]);
        let r = router(&[("a", &a), ("b", &b)]);
        let seen = Mutex::new(String::new());
        let err = r
            .chat_stream(&[], &[], &|d| {
                if let crate::stream::Delta::Text(t) = d {
                    seen.lock().unwrap().push_str(&t);
                }
            })
            .await
            .unwrap_err();
        assert_eq!(b.calls(), 0, "the reader already has the start of a reply");
        assert_eq!(&*seen.lock().unwrap(), "half an ans");
        let shown = err.to_string();
        assert!(shown.contains("already shown"), "{shown}");
        assert!(shown.contains("route `a`"), "{shown}");
        assert!(r.hops().is_empty());
        assert_eq!(routed(err).2, RouteStop::AfterText);
    }

    #[tokio::test]
    async fn the_last_route_cut_after_text_is_a_plain_failure_not_a_claim_of_replay() {
        let a = Scripted::new(vec![timeout()]);
        let b = Scripted::streaming_then(
            "partial",
            Err(Error::Provider(ProviderFailure::Truncated {
                message: "eof".into(),
                streamed_chars: 7,
            })),
        );
        let r = router(&[("a", &a), ("b", &b)]);
        let err = r.chat_stream(&[], &[], &|_| {}).await.unwrap_err();
        assert_eq!(routed(err).2, RouteStop::Exhausted);
    }

    #[tokio::test]
    async fn streaming_text_reaches_the_caller_once_when_the_answer_comes_from_a_later_route() {
        let a = Scripted::new(vec![down()]);
        let b = Scripted::streaming_then("hello", reply("hello"));
        let r = router(&[("a", &a), ("b", &b)]);
        let seen = Mutex::new(String::new());
        r.chat_stream(&[], &[], &|d| {
            if let crate::stream::Delta::Text(t) = d {
                seen.lock().unwrap().push_str(&t);
            }
        })
        .await
        .unwrap();
        assert_eq!(&*seen.lock().unwrap(), "hello");
    }

    #[tokio::test]
    async fn the_patch_reaches_the_route_that_answers() {
        let a = Scripted::new(vec![down()]);
        let b = Scripted::new(vec![reply("ok")]);
        let r = router(&[("a", &a), ("b", &b)]);
        let patch = RequestPatch {
            tool_choice: Some(crate::hooks::ToolChoice::None),
            ..RequestPatch::default()
        };
        r.chat_stream_patched(&[], &[], &|_| {}, &patch)
            .await
            .unwrap();
        assert_eq!(*b.patch_seen.lock().unwrap(), Some(true));
    }

    #[tokio::test]
    async fn usage_is_the_answering_routes_not_the_failed_ones() {
        let usage = TurnUsage {
            prompt_tokens: Some(7),
            completion_tokens: Some(3),
            ..TurnUsage::default()
        };
        let a = Scripted::new(vec![down()]);
        let b = Scripted::with_usage(vec![reply("ok")], usage.clone());
        let r = router(&[("a", &a), ("b", &b)]);
        r.chat(&[], &[]).await.unwrap();
        assert_eq!(r.take_usage(), Some(usage));
        assert_eq!(r.take_usage(), None, "taken, not borrowed");
    }

    #[test]
    fn a_routed_failure_answers_a_callers_questions_as_its_cause_does() {
        let f = ProviderFailure::Routed {
            route: "local".into(),
            trail: Vec::new(),
            stop: RouteStop::Failed,
            cause: Box::new(ProviderFailure::Unauthorized(http(401))),
        };
        assert_eq!(f.status(), Some(401));
        assert!(!f.is_retryable());
        assert_eq!(f.short_reason(), "HTTP 401");
        assert_eq!(f.body(), Some("nope"));
    }
}