Skip to main content

eclipse_core/
router.rs

1//! Model routes: a [`ChatProvider`] that tries a chain of providers in order.
2//!
3//! It is a provider rather than a feature of the loop so the loop stays untouched: the runtime
4//! still holds one `&dyn ChatProvider` per run and asks it for a reply. It lives in its own
5//! module because it knows nothing about HTTP; `provider.rs` is about one server, this is about
6//! the policy for moving between servers, and each is easier to read without the other.
7//!
8//! The policy, in one place:
9//!
10//! - One attempt per route, in chain order. A route that failed is never tried again in the same
11//!   run, and a route that answered is kept for the turns after it.
12//! - A hop happens only when the failure says the server was the problem and the request was
13//!   fine: [`ProviderFailure::is_retryable`] (no answer, 408/429/5xx, a cut stream). A wrong
14//!   key, a refused option or a 400 fails the run and names the route, because moving on would
15//!   hide a config error behind a slower success.
16//! - Each route keeps its own retry budget (`max_retries`, with backoff) before the router moves
17//!   on. `max_retries = 0` on a route makes it hop at once.
18//! - Streaming: once any text of a turn has reached the caller, a transient failure does not hop.
19//!   Replaying the turn on another route would print its beginning twice, so the run fails and
20//!   says why. This is the same rule M10 applies to one route's cut stream, applied one level up.
21//! - Every hop is recorded with its reason and can be read back with [`Router::hops`].
22
23use crate::error::{Error, ProviderFailure, Result};
24use crate::hooks::RequestPatch;
25use crate::message::Message;
26use crate::provider::ChatProvider;
27use crate::stream::DeltaFn;
28use crate::tools::ToolSpec;
29use crate::usage::TurnUsage;
30use async_trait::async_trait;
31use std::fmt;
32use std::sync::atomic::{AtomicUsize, Ordering};
33use std::sync::{Arc, Mutex, MutexGuard};
34
35/// One move from a route that failed to the next one, and why.
36#[derive(Debug, Clone, PartialEq, Eq)]
37pub struct Hop {
38    pub from: String,
39    pub to: String,
40    /// A few words: `timeout`, `unreachable`, `HTTP 503`, `stream cut`.
41    pub reason: String,
42}
43
44impl fmt::Display for Hop {
45    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
46        write!(f, "{} \u{2192} {}: {}", self.from, self.to, self.reason)
47    }
48}
49
50/// Render hops as one readout line: `route: local → big (timeout)`, or
51/// `route: local → big → cloud (timeout; HTTP 503)` when it hopped twice. Empty when nothing
52/// hopped, because silence is the normal case.
53pub fn describe_hops(hops: &[Hop]) -> Option<String> {
54    let first = hops.first()?;
55    let mut chain = first.from.clone();
56    for h in hops {
57        chain.push_str(" \u{2192} ");
58        chain.push_str(&h.to);
59    }
60    let reasons: Vec<&str> = hops.iter().map(|h| h.reason.as_str()).collect();
61    Some(format!("route: {chain} ({})", reasons.join("; ")))
62}
63
64/// Why a [`ProviderFailure::Routed`] ended the run.
65#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66pub enum RouteStop {
67    /// The failure was not transient (or there was no route left but this one): the run fails
68    /// here and names the route.
69    Failed,
70    /// Every route in the chain failed transiently.
71    Exhausted,
72    /// The failure was transient but text had already reached the caller, so the turn was not
73    /// replayed on the next route.
74    AfterText,
75}
76
77/// What a readout needs to say about one route: its name and what it serves.
78#[derive(Debug, Clone, PartialEq, Eq)]
79pub struct RouteInfo {
80    pub name: String,
81    pub model: String,
82    pub endpoint: String,
83}
84
85/// The jobs the agent does on its own behalf that can be sent to a route of their own.
86///
87/// Only roles with a consumer are listed. `summary` is the summary of trimmed turns
88/// (`[provider] aux`); `delegate` is the child agent a `delegate` call starts
89/// (`[provider] delegate`). There is no `title` role: nothing generates a session title (a
90/// title is a `rename`, typed by the user), so a `title` row would be a config key with no
91/// consumer.
92pub const ROLES: &[&str] = &["judgement", "delegate"];
93
94/// Which route one role uses, and whether the config said so.
95#[derive(Debug, Clone, PartialEq, Eq)]
96pub struct RoleRoute {
97    pub role: &'static str,
98    pub route: String,
99    /// `false` when the role's own key is unset, or when a pin has overruled it, and the role
100    /// uses the route the run is on.
101    pub set: bool,
102    /// `true` when `--route` / `ECLIPSE_ROUTE` sent this role to the pinned route whatever the
103    /// config says: a pin is a statement about where the text may go, so it wins.
104    pub pinned: bool,
105}
106
107impl RoleRoute {
108    /// The `[provider]` key that sets this role's route.
109    pub fn key(&self) -> &'static str {
110        match self.role {
111            "delegate" => "delegate",
112            _ => "aux",
113        }
114    }
115}
116
117impl fmt::Display for RoleRoute {
118    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
119        write!(f, "{} \u{2192} {}", self.role, self.route)?;
120        if self.pinned {
121            write!(f, " (pinned)")?;
122        } else if !self.set {
123            write!(f, " (no {} route set)", self.key())?;
124        }
125        Ok(())
126    }
127}
128
129/// Which route each role uses. The one answer to the question: `eclipse config show`, `/status`
130/// and the startup panel all print this, so they cannot disagree. `aux` is `[provider] aux` and
131/// `delegate` is `[provider] delegate`; `selected` is the first route of the chain, which is
132/// where a role with no route of its own goes.
133///
134/// `pinned` collapses every role onto `selected`: `--route` / `ECLIPSE_ROUTE` says where this
135/// run's text may go, and a role route that ignored it would quietly send a summary or a child
136/// somewhere the caller ruled out.
137pub fn role_table(
138    aux: Option<&str>,
139    delegate: Option<&str>,
140    selected: &str,
141    pinned: bool,
142) -> Vec<RoleRoute> {
143    ROLES
144        .iter()
145        .map(|role| {
146            let own = match *role {
147                "delegate" => delegate,
148                _ => aux,
149            };
150            RoleRoute {
151                role,
152                route: if pinned {
153                    selected.to_string()
154                } else {
155                    own.unwrap_or(selected).to_string()
156                },
157                set: !pinned && own.is_some(),
158                pinned,
159            }
160        })
161        .collect()
162}
163
164/// One link of the chain: a name and the provider that talks to it.
165pub struct RouterEntry {
166    pub name: String,
167    pub provider: Arc<dyn ChatProvider>,
168}
169
170struct State {
171    /// The route the next turn starts on. Only ever moves forward.
172    next: usize,
173    hops: Vec<Hop>,
174    usage: Option<TurnUsage>,
175}
176
177/// A chain of providers behind the [`ChatProvider`] interface. Build one per run: its state is
178/// the run's record of which routes have already failed.
179pub struct Router {
180    entries: Vec<RouterEntry>,
181    state: Mutex<State>,
182}
183
184/// The three ways the loop asks for a reply; the router forwards each unchanged.
185enum Call<'a> {
186    Chat,
187    Stream(DeltaFn<'a>),
188    Patched(DeltaFn<'a>, &'a RequestPatch),
189}
190
191impl Router {
192    /// A router over `entries`, tried in order. An empty chain is refused: there would be
193    /// nothing to answer, and the caller has a config error to report.
194    pub fn new(entries: Vec<RouterEntry>) -> Result<Self> {
195        if entries.is_empty() {
196            return Err(Error::Config(
197                "a router needs at least one route to try".into(),
198            ));
199        }
200        Ok(Self {
201            entries,
202            state: Mutex::new(State {
203                next: 0,
204                hops: Vec::new(),
205                usage: None,
206            }),
207        })
208    }
209
210    fn state(&self) -> MutexGuard<'_, State> {
211        self.state.lock().unwrap_or_else(|e| e.into_inner())
212    }
213
214    /// The hops made so far in this run, oldest first.
215    pub fn hops(&self) -> Vec<Hop> {
216        self.state().hops.clone()
217    }
218
219    /// The route the next turn will start on: the one that answered last.
220    pub fn current(&self) -> &str {
221        let idx = self.state().next;
222        self.entries.get(idx).map(|e| e.name.as_str()).unwrap_or("")
223    }
224
225    async fn dispatch(
226        &self,
227        messages: &[Message],
228        tools: &[ToolSpec],
229        call: Call<'_>,
230    ) -> Result<Message> {
231        let mut idx = self.state().next;
232        loop {
233            let Some(entry) = self.entries.get(idx) else {
234                return Err(Error::provider("the route chain ran out of routes"));
235            };
236            // Counted per turn: a hop is only unsafe when the reader has already seen text.
237            let shown = AtomicUsize::new(0);
238            let result = match &call {
239                Call::Chat => entry.provider.chat(messages, tools).await,
240                Call::Stream(on_delta) => {
241                    let counted = |d: crate::stream::Delta| {
242                        if let crate::stream::Delta::Text(t) = &d {
243                            shown.fetch_add(t.len(), Ordering::Relaxed);
244                        }
245                        on_delta(d);
246                    };
247                    entry.provider.chat_stream(messages, tools, &counted).await
248                }
249                Call::Patched(on_delta, patch) => {
250                    let counted = |d: crate::stream::Delta| {
251                        if let crate::stream::Delta::Text(t) = &d {
252                            shown.fetch_add(t.len(), Ordering::Relaxed);
253                        }
254                        on_delta(d);
255                    };
256                    entry
257                        .provider
258                        .chat_stream_patched(messages, tools, &counted, patch)
259                        .await
260                }
261            };
262            let err = match result {
263                Ok(reply) => {
264                    let mut st = self.state();
265                    st.next = idx;
266                    st.usage = entry.provider.take_usage();
267                    return Ok(reply);
268                }
269                Err(e) => e,
270            };
271            let Error::Provider(failure) = err else {
272                return Err(err);
273            };
274            let trail = self.state().hops.clone();
275            let next_name = self.entries.get(idx + 1).map(|e| e.name.clone());
276            let has_next = next_name.is_some();
277            let stop = if !failure.is_retryable() {
278                Some(RouteStop::Failed)
279            } else if !has_next {
280                Some(if trail.is_empty() {
281                    RouteStop::Failed
282                } else {
283                    RouteStop::Exhausted
284                })
285            } else if shown.load(Ordering::Relaxed) > 0 {
286                Some(RouteStop::AfterText)
287            } else {
288                None
289            };
290            if let Some(stop) = stop {
291                return Err(Error::Provider(ProviderFailure::Routed {
292                    route: entry.name.clone(),
293                    trail,
294                    stop,
295                    cause: Box::new(failure),
296                }));
297            }
298            let mut st = self.state();
299            st.hops.push(Hop {
300                from: entry.name.clone(),
301                to: next_name.unwrap_or_default(),
302                reason: failure.short_reason(),
303            });
304            idx += 1;
305            st.next = idx;
306        }
307    }
308}
309
310#[async_trait]
311impl ChatProvider for Router {
312    async fn chat(&self, messages: &[Message], tools: &[ToolSpec]) -> Result<Message> {
313        self.dispatch(messages, tools, Call::Chat).await
314    }
315
316    async fn chat_stream(
317        &self,
318        messages: &[Message],
319        tools: &[ToolSpec],
320        on_delta: DeltaFn<'_>,
321    ) -> Result<Message> {
322        self.dispatch(messages, tools, Call::Stream(on_delta)).await
323    }
324
325    async fn chat_stream_patched(
326        &self,
327        messages: &[Message],
328        tools: &[ToolSpec],
329        on_delta: DeltaFn<'_>,
330        patch: &RequestPatch,
331    ) -> Result<Message> {
332        self.dispatch(messages, tools, Call::Patched(on_delta, patch))
333            .await
334    }
335
336    fn take_usage(&self) -> Option<TurnUsage> {
337        self.state().usage.take()
338    }
339
340    /// What the route the next turn starts on declares (`#361`).
341    ///
342    /// The default says `false`, which would refuse a picture on every chain — the router is the
343    /// provider a chained run holds, so this is the only place the answer can come from. The state
344    /// lock is taken and released before asking, because a provider's `can_see` is its own.
345    fn can_see(&self) -> bool {
346        let next = {
347            let state = self.state();
348            state.next
349        };
350        self.entries
351            .get(next)
352            .map(|entry| entry.provider.can_see())
353            .unwrap_or(false)
354    }
355}
356
357#[cfg(test)]
358mod tests {
359    use super::*;
360    use crate::error::HttpFailure;
361    use std::collections::VecDeque;
362
363    /// A provider that plays back a script, emitting some text first when asked to.
364    struct Scripted {
365        replies: Mutex<VecDeque<Result<Message>>>,
366        text_first: Option<&'static str>,
367        calls: AtomicUsize,
368        patch_seen: Mutex<Option<bool>>,
369        usage: Option<TurnUsage>,
370    }
371
372    impl Scripted {
373        fn new(replies: Vec<Result<Message>>) -> Arc<Self> {
374            Arc::new(Self {
375                replies: Mutex::new(replies.into()),
376                text_first: None,
377                calls: AtomicUsize::new(0),
378                patch_seen: Mutex::new(None),
379                usage: None,
380            })
381        }
382
383        fn streaming_then(text: &'static str, reply: Result<Message>) -> Arc<Self> {
384            Arc::new(Self {
385                replies: Mutex::new(vec![reply].into()),
386                text_first: Some(text),
387                calls: AtomicUsize::new(0),
388                patch_seen: Mutex::new(None),
389                usage: None,
390            })
391        }
392
393        fn with_usage(replies: Vec<Result<Message>>, usage: TurnUsage) -> Arc<Self> {
394            Arc::new(Self {
395                replies: Mutex::new(replies.into()),
396                text_first: None,
397                calls: AtomicUsize::new(0),
398                patch_seen: Mutex::new(None),
399                usage: Some(usage),
400            })
401        }
402
403        fn calls(&self) -> usize {
404            self.calls.load(Ordering::SeqCst)
405        }
406
407        fn next(&self) -> Result<Message> {
408            self.calls.fetch_add(1, Ordering::SeqCst);
409            self.replies
410                .lock()
411                .unwrap_or_else(|e| e.into_inner())
412                .pop_front()
413                .unwrap_or_else(|| Err(Error::provider("script exhausted")))
414        }
415    }
416
417    #[async_trait]
418    impl ChatProvider for Scripted {
419        async fn chat(&self, _: &[Message], _: &[ToolSpec]) -> Result<Message> {
420            self.next()
421        }
422
423        async fn chat_stream(
424            &self,
425            _: &[Message],
426            _: &[ToolSpec],
427            on_delta: DeltaFn<'_>,
428        ) -> Result<Message> {
429            if let Some(t) = self.text_first {
430                on_delta(crate::stream::Delta::Text(t.into()));
431            }
432            self.next()
433        }
434
435        async fn chat_stream_patched(
436            &self,
437            m: &[Message],
438            t: &[ToolSpec],
439            on_delta: DeltaFn<'_>,
440            patch: &RequestPatch,
441        ) -> Result<Message> {
442            *self.patch_seen.lock().unwrap_or_else(|e| e.into_inner()) = Some(!patch.is_empty());
443            self.chat_stream(m, t, on_delta).await
444        }
445
446        fn take_usage(&self) -> Option<TurnUsage> {
447            self.usage.clone()
448        }
449    }
450
451    fn reply(text: &str) -> Result<Message> {
452        Ok(Message::assistant(text))
453    }
454
455    fn down() -> Result<Message> {
456        Err(Error::Provider(ProviderFailure::Transport {
457            url: "http://x/v1".into(),
458            message: "the connection could not be established: refused".into(),
459            sent: false,
460        }))
461    }
462
463    fn timeout() -> Result<Message> {
464        Err(Error::Provider(ProviderFailure::Transport {
465            url: "http://x/v1".into(),
466            message: "the request timed out: deadline".into(),
467            sent: true,
468        }))
469    }
470
471    fn http(status: u16) -> HttpFailure {
472        HttpFailure {
473            status,
474            body: "nope".into(),
475            ..HttpFailure::default()
476        }
477    }
478
479    fn status(code: u16) -> Result<Message> {
480        Err(Error::Provider(match code {
481            401 => ProviderFailure::Unauthorized(http(code)),
482            400 => ProviderFailure::InvalidRequest(http(code)),
483            _ => ProviderFailure::Http(http(code)),
484        }))
485    }
486
487    fn router(chain: &[(&str, &Arc<Scripted>)]) -> Router {
488        let entries = chain
489            .iter()
490            .map(|(name, p)| RouterEntry {
491                name: (*name).to_string(),
492                provider: Arc::clone(*p) as Arc<dyn ChatProvider>,
493            })
494            .collect();
495        Router::new(entries).unwrap()
496    }
497
498    fn text(m: &Message) -> &str {
499        m.content.as_deref().unwrap_or("")
500    }
501
502    fn routed(e: Error) -> (String, Vec<Hop>, RouteStop, ProviderFailure) {
503        match e {
504            Error::Provider(ProviderFailure::Routed {
505                route,
506                trail,
507                stop,
508                cause,
509            }) => (route, trail, stop, *cause),
510            other => panic!("not a routed failure: {other}"),
511        }
512    }
513
514    #[tokio::test]
515    async fn a_router_with_nothing_to_try_is_refused() {
516        assert!(Router::new(Vec::new()).is_err());
517    }
518
519    #[tokio::test]
520    async fn the_first_route_answers_and_nothing_hops() {
521        let a = Scripted::new(vec![reply("from a")]);
522        let b = Scripted::new(vec![reply("from b")]);
523        let r = router(&[("a", &a), ("b", &b)]);
524        let got = r.chat(&[Message::user("hi")], &[]).await.unwrap();
525        assert_eq!(text(&got), "from a");
526        assert!(r.hops().is_empty());
527        assert_eq!(b.calls(), 0);
528        assert_eq!(describe_hops(&r.hops()), None);
529    }
530
531    #[tokio::test]
532    async fn the_chain_is_tried_in_order_and_each_route_at_most_once() {
533        let a = Scripted::new(vec![timeout(), reply("a again")]);
534        let b = Scripted::new(vec![status(503), reply("b again")]);
535        let c = Scripted::new(vec![reply("from c"), reply("c again")]);
536        let r = router(&[("a", &a), ("b", &b), ("c", &c)]);
537        let got = r.chat(&[Message::user("hi")], &[]).await.unwrap();
538        assert_eq!(text(&got), "from c");
539        assert_eq!((a.calls(), b.calls(), c.calls()), (1, 1, 1));
540        // The next turn starts where the last one ended: a and b are not tried again.
541        let again = r.chat(&[Message::user("more")], &[]).await.unwrap();
542        assert_eq!(text(&again), "c again");
543        assert_eq!((a.calls(), b.calls(), c.calls()), (1, 1, 2));
544        assert_eq!(r.current(), "c");
545    }
546
547    #[tokio::test]
548    async fn a_route_that_failed_is_not_tried_again_when_a_later_one_fails() {
549        let a = Scripted::new(vec![down(), reply("never")]);
550        let b = Scripted::new(vec![reply("one"), down()]);
551        let c = Scripted::new(vec![reply("two")]);
552        let r = router(&[("a", &a), ("b", &b), ("c", &c)]);
553        assert_eq!(text(&r.chat(&[], &[]).await.unwrap()), "one");
554        assert_eq!(text(&r.chat(&[], &[]).await.unwrap()), "two");
555        assert_eq!(a.calls(), 1, "a failed in this run and stays failed");
556    }
557
558    #[tokio::test]
559    async fn every_hop_is_recorded_with_why_it_happened() {
560        let a = Scripted::new(vec![timeout()]);
561        let b = Scripted::new(vec![status(503)]);
562        let c = Scripted::new(vec![reply("ok")]);
563        let r = router(&[("local", &a), ("big", &b), ("cloud", &c)]);
564        r.chat(&[], &[]).await.unwrap();
565        let hops = r.hops();
566        assert_eq!(hops.len(), 2);
567        assert_eq!(hops[0].to_string(), "local \u{2192} big: timeout");
568        assert_eq!(hops[1].to_string(), "big \u{2192} cloud: HTTP 503");
569        assert_eq!(
570            describe_hops(&hops).as_deref(),
571            Some("route: local \u{2192} big \u{2192} cloud (timeout; HTTP 503)")
572        );
573    }
574
575    #[tokio::test]
576    async fn a_refused_connection_hops_and_says_unreachable() {
577        let a = Scripted::new(vec![down()]);
578        let b = Scripted::new(vec![reply("ok")]);
579        let r = router(&[("local", &a), ("big", &b)]);
580        r.chat(&[], &[]).await.unwrap();
581        assert_eq!(r.hops()[0].reason, "unreachable");
582    }
583
584    #[tokio::test]
585    async fn a_401_on_the_first_route_does_not_hop_and_names_the_route() {
586        let a = Scripted::new(vec![status(401)]);
587        let b = Scripted::new(vec![reply("never asked")]);
588        let r = router(&[("local", &a), ("big", &b)]);
589        let (route, trail, stop, cause) = routed(r.chat(&[], &[]).await.unwrap_err());
590        assert_eq!(route, "local");
591        assert!(trail.is_empty());
592        assert_eq!(stop, RouteStop::Failed);
593        assert_eq!(cause.status(), Some(401));
594        assert_eq!(b.calls(), 0, "a wrong key is not a transport hiccup");
595        assert!(r.hops().is_empty());
596    }
597
598    #[tokio::test]
599    async fn a_400_fails_the_run_instead_of_hiding_a_config_error() {
600        let a = Scripted::new(vec![status(400)]);
601        let b = Scripted::new(vec![reply("never asked")]);
602        let r = router(&[("local", &a), ("big", &b)]);
603        let err = r.chat(&[], &[]).await.unwrap_err();
604        assert!(err.to_string().contains("route `local` failed"), "{err}");
605        assert_eq!(b.calls(), 0);
606    }
607
608    #[tokio::test]
609    async fn a_failure_after_a_hop_names_the_route_it_failed_on_and_the_earlier_hop() {
610        let a = Scripted::new(vec![timeout()]);
611        let b = Scripted::new(vec![status(401)]);
612        let r = router(&[("local", &a), ("big", &b)]);
613        let err = r.chat(&[], &[]).await.unwrap_err();
614        let text = err.to_string();
615        assert!(text.contains("route `big` failed"), "{text}");
616        assert!(text.contains("local: timeout"), "{text}");
617    }
618
619    #[tokio::test]
620    async fn an_exhausted_chain_lists_every_route_and_why_each_failed() {
621        let a = Scripted::new(vec![timeout()]);
622        let b = Scripted::new(vec![status(503)]);
623        let r = router(&[("local", &a), ("big", &b)]);
624        let err = r.chat(&[], &[]).await.unwrap_err();
625        let shown = err.to_string();
626        assert!(shown.contains("every route failed"), "{shown}");
627        assert!(shown.contains("local: timeout"), "{shown}");
628        assert!(shown.contains("big: HTTP 503"), "{shown}");
629        let (route, trail, stop, _) = routed(err);
630        assert_eq!(
631            (route.as_str(), trail.len(), stop),
632            ("big", 1, RouteStop::Exhausted)
633        );
634    }
635
636    #[tokio::test]
637    async fn a_single_route_that_fails_is_a_plain_failure_naming_it() {
638        let a = Scripted::new(vec![timeout()]);
639        let r = router(&[("local", &a)]);
640        let (route, _, stop, cause) = routed(r.chat(&[], &[]).await.unwrap_err());
641        assert_eq!((route.as_str(), stop), ("local", RouteStop::Failed));
642        assert!(cause.is_retryable());
643    }
644
645    #[tokio::test]
646    async fn a_stream_cut_before_any_text_hops_to_the_next_route() {
647        let a = Scripted::new(vec![Err(Error::Provider(ProviderFailure::Truncated {
648            message: "eof".into(),
649            streamed_chars: 0,
650        }))]);
651        let b = Scripted::new(vec![reply("whole")]);
652        let r = router(&[("a", &a), ("b", &b)]);
653        let seen = Mutex::new(String::new());
654        let got = r
655            .chat_stream(&[], &[], &|d| {
656                if let crate::stream::Delta::Text(t) = d {
657                    seen.lock().unwrap().push_str(&t);
658                }
659            })
660            .await
661            .unwrap();
662        assert_eq!(text(&got), "whole");
663        assert_eq!(r.hops()[0].reason, "stream cut");
664    }
665
666    #[tokio::test]
667    async fn a_stream_cut_after_text_is_not_replayed_on_the_next_route() {
668        let a = Scripted::streaming_then(
669            "half an ans",
670            Err(Error::Provider(ProviderFailure::Truncated {
671                message: "eof".into(),
672                streamed_chars: 11,
673            })),
674        );
675        let b = Scripted::new(vec![reply("the whole answer")]);
676        let r = router(&[("a", &a), ("b", &b)]);
677        let seen = Mutex::new(String::new());
678        let err = r
679            .chat_stream(&[], &[], &|d| {
680                if let crate::stream::Delta::Text(t) = d {
681                    seen.lock().unwrap().push_str(&t);
682                }
683            })
684            .await
685            .unwrap_err();
686        assert_eq!(b.calls(), 0, "the reader already has the start of a reply");
687        assert_eq!(&*seen.lock().unwrap(), "half an ans");
688        let shown = err.to_string();
689        assert!(shown.contains("already shown"), "{shown}");
690        assert!(shown.contains("route `a`"), "{shown}");
691        assert!(r.hops().is_empty());
692        assert_eq!(routed(err).2, RouteStop::AfterText);
693    }
694
695    #[tokio::test]
696    async fn the_last_route_cut_after_text_is_a_plain_failure_not_a_claim_of_replay() {
697        let a = Scripted::new(vec![timeout()]);
698        let b = Scripted::streaming_then(
699            "partial",
700            Err(Error::Provider(ProviderFailure::Truncated {
701                message: "eof".into(),
702                streamed_chars: 7,
703            })),
704        );
705        let r = router(&[("a", &a), ("b", &b)]);
706        let err = r.chat_stream(&[], &[], &|_| {}).await.unwrap_err();
707        assert_eq!(routed(err).2, RouteStop::Exhausted);
708    }
709
710    #[tokio::test]
711    async fn streaming_text_reaches_the_caller_once_when_the_answer_comes_from_a_later_route() {
712        let a = Scripted::new(vec![down()]);
713        let b = Scripted::streaming_then("hello", reply("hello"));
714        let r = router(&[("a", &a), ("b", &b)]);
715        let seen = Mutex::new(String::new());
716        r.chat_stream(&[], &[], &|d| {
717            if let crate::stream::Delta::Text(t) = d {
718                seen.lock().unwrap().push_str(&t);
719            }
720        })
721        .await
722        .unwrap();
723        assert_eq!(&*seen.lock().unwrap(), "hello");
724    }
725
726    #[tokio::test]
727    async fn the_patch_reaches_the_route_that_answers() {
728        let a = Scripted::new(vec![down()]);
729        let b = Scripted::new(vec![reply("ok")]);
730        let r = router(&[("a", &a), ("b", &b)]);
731        let patch = RequestPatch {
732            tool_choice: Some(crate::hooks::ToolChoice::None),
733            ..RequestPatch::default()
734        };
735        r.chat_stream_patched(&[], &[], &|_| {}, &patch)
736            .await
737            .unwrap();
738        assert_eq!(*b.patch_seen.lock().unwrap(), Some(true));
739    }
740
741    #[tokio::test]
742    async fn usage_is_the_answering_routes_not_the_failed_ones() {
743        let usage = TurnUsage {
744            prompt_tokens: Some(7),
745            completion_tokens: Some(3),
746            ..TurnUsage::default()
747        };
748        let a = Scripted::new(vec![down()]);
749        let b = Scripted::with_usage(vec![reply("ok")], usage.clone());
750        let r = router(&[("a", &a), ("b", &b)]);
751        r.chat(&[], &[]).await.unwrap();
752        assert_eq!(r.take_usage(), Some(usage));
753        assert_eq!(r.take_usage(), None, "taken, not borrowed");
754    }
755
756    #[test]
757    fn a_routed_failure_answers_a_callers_questions_as_its_cause_does() {
758        let f = ProviderFailure::Routed {
759            route: "local".into(),
760            trail: Vec::new(),
761            stop: RouteStop::Failed,
762            cause: Box::new(ProviderFailure::Unauthorized(http(401))),
763        };
764        assert_eq!(f.status(), Some(401));
765        assert!(!f.is_retryable());
766        assert_eq!(f.short_reason(), "HTTP 401");
767        assert_eq!(f.body(), Some("nope"));
768    }
769}