1use 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 pub trait Sealed: Sized + 'static {
23 #[doc(hidden)]
24 fn slot(registry: &MiddlewareRegistry) -> &StageRegistry<Self>
25 where
26 Self: super::MiddlewareStage;
27 }
28}
29
30pub trait MiddlewareStage: private::Sealed + Send + Sync {
33 type Context: Send + 'static;
35 type Result: Send + 'static;
37 const NAME: &'static str;
39}
40
41#[derive(Debug)]
47#[non_exhaustive]
48pub enum MiddlewareError {
49 Error(Error),
51 Interrupt(InterruptError),
53 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 #[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
122pub type StageResult<T> = std::result::Result<T, MiddlewareError>;
124
125#[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 Event(AgentStreamEvent),
134 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
148pub struct StageStream<S: MiddlewareStage> {
151 inner: BoxStream<'static, StageItem<S>>,
152}
153
154impl<S: MiddlewareStage> StageStream<S> {
155 pub fn new(stream: impl Stream<Item = StageItem<S>> + Send + 'static) -> Self {
157 Self {
158 inner: Box::pin(stream),
159 }
160 }
161
162 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 pub fn from_stream_future(future: impl Future<Output = Self> + Send + 'static) -> Self {
186 Self::new(future.into_stream().flatten())
187 }
188
189 pub fn from_result(result: StageResult<S::Result>) -> Self {
191 Self::new(futures::stream::once(std::future::ready(StageItem::Done(result))))
192 }
193
194 #[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 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#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
267#[non_exhaustive]
268pub enum MiddlewarePhase {
269 Input,
271 Output,
273 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
332pub struct Middleware<S: MiddlewareStage> {
336 pub(crate) handler: Handler<S>,
337}
338
339impl<S: MiddlewareStage> Middleware<S> {
340 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 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 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 #[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
390pub 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 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#[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 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}