Skip to main content

strands/middleware/
types.rs

1//! Stage tokens, stage streams and the handler forms.
2
3use std::fmt;
4use std::future::Future;
5use std::pin::Pin;
6use std::sync::Arc;
7use std::task::{Context, Poll};
8
9use futures::future::BoxFuture;
10use futures::{FutureExt, Stream, StreamExt};
11
12use super::registry::{MiddlewareRegistry, StageRegistry};
13use crate::error::{BoxError, Error};
14use crate::hooks::AgentStreamEvent;
15use crate::interrupt::{Interrupt, InterruptError};
16use crate::models::BoxStream;
17
18pub(crate) mod private {
19    use super::{MiddlewareRegistry, StageRegistry};
20
21    /// Seals [`MiddlewareStage`](super::MiddlewareStage) to the SDK's stages and finds a stage's handlers.
22    pub trait Sealed: Sized + 'static {
23        #[doc(hidden)]
24        fn slot(registry: &MiddlewareRegistry) -> &StageRegistry<Self>
25        where
26            Self: super::MiddlewareStage;
27    }
28}
29
30/// A middleware interception point (`MiddlewareStage`), sealed to the SDK's stages:
31/// [`InvokeModelStage`](super::InvokeModelStage) and [`ExecuteToolStage`](super::ExecuteToolStage).
32pub trait MiddlewareStage: private::Sealed + Send + Sync {
33    /// What handlers receive and pass to `next`.
34    type Context: Send + 'static;
35    /// What the stage produces.
36    type Result: Send + 'static;
37    /// The stage name (`invokeModel`, `executeTool`).
38    const NAME: &'static str;
39}
40
41/// Why a stage did not produce a result.
42///
43/// Errors, interrupts and cancellation travel through the chain as values, so a Wrap handler can
44/// see them and decide; `?` converts an [`Error`], an [`Interrupt`] or an [`InterruptError`] into
45/// one.
46#[derive(Debug)]
47#[non_exhaustive]
48pub enum MiddlewareError {
49    /// The stage failed.
50    Error(Error),
51    /// A handler or the tool raised interrupts.
52    Interrupt(InterruptError),
53    /// The invocation was cancelled.
54    Cancelled,
55}
56
57impl fmt::Display for MiddlewareError {
58    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59        match self {
60            Self::Error(error) => error.fmt(f),
61            Self::Interrupt(interrupts) => interrupts.fmt(f),
62            Self::Cancelled => f.write_str("Agent invocation cancelled"),
63        }
64    }
65}
66
67impl std::error::Error for MiddlewareError {
68    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
69        match self {
70            Self::Error(error) => Some(error),
71            _ => None,
72        }
73    }
74}
75
76impl MiddlewareError {
77    /// Recovers the typed error behind a boxed one, so a handler can `?` errors that only
78    /// convert into a [`BoxError`]: an [`InterruptError`] stays an interrupt and a boxed
79    /// [`Error`] is unwrapped; anything else is [`Error::Other`].
80    ///
81    /// ```
82    /// use strands::BoxError;
83    /// use strands::middleware::MiddlewareError;
84    ///
85    /// fn lookup() -> Result<u32, BoxError> {
86    ///     Err("cache unavailable".into())
87    /// }
88    ///
89    /// fn handler_step() -> Result<u32, MiddlewareError> {
90    ///     lookup().map_err(MiddlewareError::from_boxed)
91    /// }
92    ///
93    /// assert_eq!(handler_step().unwrap_err().to_string(), "cache unavailable");
94    /// ```
95    #[must_use]
96    pub fn from_boxed(error: BoxError) -> Self {
97        Error::from_boxed(error).into()
98    }
99}
100
101impl From<Error> for MiddlewareError {
102    fn from(error: Error) -> Self {
103        match error {
104            Error::Interrupt(interrupts) => Self::Interrupt(interrupts),
105            error => Self::Error(error),
106        }
107    }
108}
109
110impl From<Interrupt> for MiddlewareError {
111    fn from(interrupt: Interrupt) -> Self {
112        Self::Interrupt(interrupt.into())
113    }
114}
115
116impl From<InterruptError> for MiddlewareError {
117    fn from(interrupts: InterruptError) -> Self {
118        Self::Interrupt(interrupts)
119    }
120}
121
122/// The outcome of a stage.
123pub type StageResult<T> = std::result::Result<T, MiddlewareError>;
124
125/// One item of a stage stream: an event, or the stage outcome that ends the stream.
126#[allow(
127    clippy::large_enum_variant,
128    reason = "events are the common item and move straight to the agent's stream; boxing would allocate per model delta"
129)]
130#[non_exhaustive]
131pub enum StageItem<S: MiddlewareStage> {
132    /// A stream event, passed up through the outer handlers to the agent's stream.
133    Event(AgentStreamEvent),
134    /// The stage outcome; nothing follows it.
135    Done(StageResult<S::Result>),
136}
137
138impl<S: MiddlewareStage> fmt::Debug for StageItem<S> {
139    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
140        match self {
141            Self::Event(event) => f.debug_tuple("Event").field(event).finish(),
142            Self::Done(Ok(_)) => f.write_str("Done(Ok(..))"),
143            Self::Done(Err(error)) => f.debug_tuple("Done").field(error).finish(),
144        }
145    }
146}
147
148/// The stream a Wrap handler and `next` return: events, then one [`StageItem::Done`]. A stream that
149/// ends without one is a stage error.
150pub struct StageStream<S: MiddlewareStage> {
151    inner: BoxStream<'static, StageItem<S>>,
152}
153
154impl<S: MiddlewareStage> StageStream<S> {
155    /// Wraps any stream of stage items, such as one built with `async_stream::stream!`.
156    pub fn new(stream: impl Stream<Item = StageItem<S>> + Send + 'static) -> Self {
157        Self {
158            inner: Box::pin(stream),
159        }
160    }
161
162    /// A stream with no events that ends with `future`'s outcome.
163    ///
164    /// Events of any `next` stream the future drains with [`result`](Self::result) are dropped;
165    /// to keep them while doing async work first, use
166    /// [`from_stream_future`](Self::from_stream_future).
167    pub fn from_future(future: impl Future<Output = StageResult<S::Result>> + Send + 'static) -> Self {
168        Self::new(future.map(StageItem::Done).into_stream())
169    }
170
171    /// The stream `future` resolves to, with every event: for a Wrap handler that awaits
172    /// something (a rate limiter, a cache lookup) before it calls `next`.
173    ///
174    /// ```
175    /// use strands::middleware::{InvokeModelStage, StageStream};
176    ///
177    /// let throttled = InvokeModelStage::wrap(|context, next| {
178    ///     StageStream::from_stream_future(async move {
179    ///         tokio::task::yield_now().await;
180    ///         next.call(context)
181    ///     })
182    /// });
183    /// # let _ = throttled;
184    /// ```
185    pub fn from_stream_future(future: impl Future<Output = Self> + Send + 'static) -> Self {
186        Self::new(future.into_stream().flatten())
187    }
188
189    /// A stream with no events that ends with `result` (a short-circuit).
190    pub fn from_result(result: StageResult<S::Result>) -> Self {
191        Self::new(futures::stream::once(std::future::ready(StageItem::Done(result))))
192    }
193
194    /// Forwards every event and passes the outcome through `f` (an Output-style transform that
195    /// also sees errors).
196    #[must_use]
197    pub fn map_result<F, Fut>(self, f: F) -> Self
198    where
199        F: FnOnce(StageResult<S::Result>) -> Fut + Send + 'static,
200        Fut: Future<Output = StageResult<S::Result>> + Send + 'static,
201    {
202        let mut inner = self;
203        Self::new(async_stream::stream! {
204            while let Some(item) = inner.next().await {
205                match item {
206                    StageItem::Event(event) => yield StageItem::Event(event),
207                    StageItem::Done(result) => {
208                        yield StageItem::Done(f(result).await);
209                        return;
210                    }
211                }
212            }
213            yield StageItem::Done(f(Err(ended_without_result())).await);
214        })
215    }
216
217    /// Drains the stream and returns the outcome. Its events are dropped: they reach neither
218    /// hooks nor the agent's stream. Forward them instead when they matter (see the retry
219    /// example in the [module docs](super)).
220    pub async fn result(mut self) -> StageResult<S::Result> {
221        while let Some(item) = self.next().await {
222            if let StageItem::Done(result) = item {
223                return result;
224            }
225        }
226        Err(ended_without_result())
227    }
228}
229
230pub(crate) fn ended_without_result() -> MiddlewareError {
231    MiddlewareError::Error(Error::other("middleware stream ended without a result"))
232}
233
234impl<S: MiddlewareStage> Stream for StageStream<S> {
235    type Item = StageItem<S>;
236
237    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
238        self.inner.as_mut().poll_next(cx)
239    }
240}
241
242impl<S: MiddlewareStage> fmt::Debug for StageStream<S> {
243    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
244        f.debug_struct("StageStream")
245            .field("stage", &S::NAME)
246            .finish_non_exhaustive()
247    }
248}
249
250pub(crate) type InputFn<S> = Arc<
251    dyn Fn(<S as MiddlewareStage>::Context) -> BoxFuture<'static, StageResult<<S as MiddlewareStage>::Context>>
252        + Send
253        + Sync,
254>;
255pub(crate) type OutputFn<S> = Arc<
256    dyn Fn(<S as MiddlewareStage>::Result) -> BoxFuture<'static, StageResult<<S as MiddlewareStage>::Result>>
257        + Send
258        + Sync,
259>;
260pub(crate) type WrapFn<S> =
261    Arc<dyn Fn(<S as MiddlewareStage>::Context, MiddlewareNext<S>) -> StageStream<S> + Send + Sync>;
262pub(crate) type TerminalFn<S> = Arc<dyn Fn(<S as MiddlewareStage>::Context) -> StageStream<S> + Send + Sync>;
263
264/// The phase a handler runs in (`MiddlewarePhaseKind`). The chain composes Input outermost, then
265/// Output, then Wrap next to the stage, so handlers run Input, Wrap, Output.
266#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
267#[non_exhaustive]
268pub enum MiddlewarePhase {
269    /// Transforms the context before the stage runs (`input`).
270    Input,
271    /// Transforms the result after the stage runs (`output`).
272    Output,
273    /// Wraps the stage: may short-circuit, retry, filter or inject events (`wrap`).
274    Wrap,
275}
276
277pub(crate) enum Handler<S: MiddlewareStage> {
278    Input(InputFn<S>),
279    Output(OutputFn<S>),
280    Wrap(WrapFn<S>),
281}
282
283impl<S: MiddlewareStage> Clone for Handler<S> {
284    fn clone(&self) -> Self {
285        match self {
286            Self::Input(f) => Self::Input(f.clone()),
287            Self::Output(f) => Self::Output(f.clone()),
288            Self::Wrap(f) => Self::Wrap(f.clone()),
289        }
290    }
291}
292
293impl<S: MiddlewareStage> Handler<S> {
294    pub(crate) fn phase(&self) -> MiddlewarePhase {
295        match self {
296            Self::Input(_) => MiddlewarePhase::Input,
297            Self::Output(_) => MiddlewarePhase::Output,
298            Self::Wrap(_) => MiddlewarePhase::Wrap,
299        }
300    }
301
302    fn run(&self, context: S::Context, next: MiddlewareNext<S>) -> StageStream<S> {
303        match self {
304            Self::Wrap(wrap) => wrap(context, next),
305            Self::Input(input) => {
306                let input = input.clone();
307                StageStream::new(async_stream::stream! {
308                    match input(context).await {
309                        Ok(context) => {
310                            let mut inner = next.call(context);
311                            while let Some(item) = inner.next().await {
312                                yield item;
313                            }
314                        }
315                        Err(error) => yield StageItem::Done(Err(error)),
316                    }
317                })
318            }
319            Self::Output(output) => {
320                let output = output.clone();
321                next.call(context).map_result(move |result| async move {
322                    match result {
323                        Ok(result) => output(result).await,
324                        Err(error) => Err(error),
325                    }
326                })
327            }
328        }
329    }
330}
331
332/// A middleware handler for the stage `S`, ready for
333/// [`Agent::add_middleware`](crate::Agent::add_middleware). Build one with the stage's `input`,
334/// `output` or `wrap`, for example [`InvokeModelStage::input`](super::InvokeModelStage::input).
335pub struct Middleware<S: MiddlewareStage> {
336    pub(crate) handler: Handler<S>,
337}
338
339impl<S: MiddlewareStage> Middleware<S> {
340    /// An Input handler: transforms the context before the stage runs (`Stage.Input`).
341    pub fn input<F, Fut>(handler: F) -> Self
342    where
343        F: Fn(S::Context) -> Fut + Send + Sync + 'static,
344        Fut: Future<Output = StageResult<S::Context>> + Send + 'static,
345    {
346        Self {
347            handler: Handler::Input(Arc::new(move |context| Box::pin(handler(context)))),
348        }
349    }
350
351    /// An Output handler: transforms the result after the stage runs (`Stage.Output`). It does not
352    /// see events or failures.
353    pub fn output<F, Fut>(handler: F) -> Self
354    where
355        F: Fn(S::Result) -> Fut + Send + Sync + 'static,
356        Fut: Future<Output = StageResult<S::Result>> + Send + 'static,
357    {
358        Self {
359            handler: Handler::Output(Arc::new(move |result| Box::pin(handler(result)))),
360        }
361    }
362
363    /// A Wrap handler: gets the context and `next`, and returns the stage's stream (`Stage` or
364    /// `Stage.Wrap`). Return `next.call(context)` to pass through; skip `next` to short-circuit.
365    pub fn wrap<F>(handler: F) -> Self
366    where
367        F: Fn(S::Context, MiddlewareNext<S>) -> StageStream<S> + Send + Sync + 'static,
368    {
369        Self {
370            handler: Handler::Wrap(Arc::new(handler)),
371        }
372    }
373
374    /// The phase the handler runs in.
375    #[must_use]
376    pub fn phase(&self) -> MiddlewarePhase {
377        self.handler.phase()
378    }
379}
380
381impl<S: MiddlewareStage> fmt::Debug for Middleware<S> {
382    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
383        f.debug_struct("Middleware")
384            .field("stage", &S::NAME)
385            .field("phase", &self.phase())
386            .finish()
387    }
388}
389
390/// The rest of the chain a Wrap handler calls (`MiddlewareNext`). Cheap to clone; call it more
391/// than once to retry.
392pub struct MiddlewareNext<S: MiddlewareStage> {
393    handlers: Arc<[Handler<S>]>,
394    index: usize,
395    terminal: TerminalFn<S>,
396}
397
398impl<S: MiddlewareStage> Clone for MiddlewareNext<S> {
399    fn clone(&self) -> Self {
400        Self {
401            handlers: self.handlers.clone(),
402            index: self.index,
403            terminal: self.terminal.clone(),
404        }
405    }
406}
407
408impl<S: MiddlewareStage> MiddlewareNext<S> {
409    pub(crate) fn new(handlers: Arc<[Handler<S>]>, terminal: TerminalFn<S>) -> Self {
410        Self {
411            handlers,
412            index: 0,
413            terminal,
414        }
415    }
416
417    /// Runs the inner handlers and the stage with `context`.
418    pub fn call(&self, context: S::Context) -> StageStream<S> {
419        let Some(handler) = self.handlers.get(self.index) else {
420            return (self.terminal)(context);
421        };
422        let next = Self {
423            handlers: self.handlers.clone(),
424            index: self.index + 1,
425            terminal: self.terminal.clone(),
426        };
427        handler.run(context, next)
428    }
429}
430
431impl<S: MiddlewareStage> fmt::Debug for MiddlewareNext<S> {
432    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
433        f.debug_struct("MiddlewareNext")
434            .field("stage", &S::NAME)
435            .field("remaining", &(self.handlers.len() - self.index))
436            .finish()
437    }
438}
439
440/// Removes a registered middleware handler; [`Agent::add_middleware`](crate::Agent::add_middleware)
441/// returns it.
442///
443/// [`remove`](Self::remove) is idempotent and leaves other registrations alone. Dropping the
444/// handle keeps the handler registered.
445#[derive(Clone)]
446pub struct MiddlewareCleanup {
447    remove: Arc<dyn Fn() + Send + Sync>,
448}
449
450impl MiddlewareCleanup {
451    pub(crate) fn new(remove: impl Fn() + Send + Sync + 'static) -> Self {
452        Self {
453            remove: Arc::new(remove),
454        }
455    }
456
457    /// Unregisters the handler. Calling it again does nothing.
458    pub fn remove(&self) {
459        (self.remove)();
460    }
461}
462
463impl fmt::Debug for MiddlewareCleanup {
464    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
465        f.debug_struct("MiddlewareCleanup").finish_non_exhaustive()
466    }
467}