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
//! Middleware wrapper for [`StreamFn`] that intercepts the output stream.
//!
//! Mirrors the [`ToolMiddleware`](crate::ToolMiddleware) pattern but for the
//! streaming boundary. Wraps an `Arc<dyn StreamFn>` and transforms the output
//! stream of [`AssistantMessageEvent`] values.
//!
//! # Example
//!
//! ```
//! use std::sync::Arc;
//! use swink_agent::{StreamMiddleware, AssistantMessageEvent};
//! # use swink_agent::StreamFn;
//! # fn example(stream_fn: Arc<dyn StreamFn>) {
//! let logged = StreamMiddleware::with_logging(stream_fn, |event| {
//! println!("event: {event:?}");
//! });
//! # }
//! ```
use std::pin::Pin;
use std::sync::Arc;
use futures::stream::{Stream, StreamExt};
use tokio_util::sync::CancellationToken;
use crate::stream::{AssistantMessageEvent, StreamFn, StreamOptions};
use crate::types::{AgentContext, ModelSpec};
// ─── Type alias for the stream transformation closure ───────────────────────
type MapStreamFn = Arc<
dyn for<'a> Fn(
Pin<Box<dyn Stream<Item = AssistantMessageEvent> + Send + 'a>>,
) -> Pin<Box<dyn Stream<Item = AssistantMessageEvent> + Send + 'a>>
+ Send
+ Sync,
>;
// ─── StreamMiddleware ───────────────────────────────────────────────────────
/// Intercepts the output stream from a wrapped [`StreamFn`].
///
/// The inner `StreamFn` is called normally, then `map_stream` transforms
/// the resulting event stream before it reaches the consumer.
pub struct StreamMiddleware {
inner: Arc<dyn StreamFn>,
map_stream: MapStreamFn,
}
impl StreamMiddleware {
/// Create a new middleware with a full stream transformation.
///
/// The closure receives the inner stream and returns a transformed stream.
pub fn new<F>(inner: Arc<dyn StreamFn>, f: F) -> Self
where
F: for<'a> Fn(
Pin<Box<dyn Stream<Item = AssistantMessageEvent> + Send + 'a>>,
)
-> Pin<Box<dyn Stream<Item = AssistantMessageEvent> + Send + 'a>>
+ Send
+ Sync
+ 'static,
{
Self {
inner,
map_stream: Arc::new(f),
}
}
/// Create a middleware that inspects each event via a logging callback.
///
/// Events pass through unmodified; the callback is called for each event.
pub fn with_logging<F>(inner: Arc<dyn StreamFn>, callback: F) -> Self
where
F: Fn(&AssistantMessageEvent) + Send + Sync + 'static,
{
let callback = Arc::new(callback);
Self::new(inner, move |stream| {
let cb = callback.clone();
Box::pin(stream.inspect(move |event| cb(event)))
})
}
/// Create a middleware that maps each event through a transformation.
pub fn with_map<F>(inner: Arc<dyn StreamFn>, f: F) -> Self
where
F: Fn(AssistantMessageEvent) -> AssistantMessageEvent + Send + Sync + 'static,
{
let f = Arc::new(f);
Self::new(inner, move |stream| {
let f = f.clone();
Box::pin(stream.map(move |event| f(event)))
})
}
/// Create a middleware that filters events based on a predicate.
///
/// Events for which the predicate returns `false` are dropped from the stream.
pub fn with_filter<F>(inner: Arc<dyn StreamFn>, f: F) -> Self
where
F: Fn(&AssistantMessageEvent) -> bool + Send + Sync + 'static,
{
let f = Arc::new(f);
Self::new(inner, move |stream| {
let f = f.clone();
Box::pin(stream.filter(move |event| {
let keep = f(event);
async move { keep }
}))
})
}
}
impl StreamFn for StreamMiddleware {
fn stream<'a>(
&'a self,
model: &'a ModelSpec,
context: &'a AgentContext,
options: &'a StreamOptions,
cancellation_token: CancellationToken,
) -> Pin<Box<dyn Stream<Item = AssistantMessageEvent> + Send + 'a>> {
let inner_stream = self
.inner
.stream(model, context, options, cancellation_token);
(self.map_stream)(inner_stream)
}
}
impl std::fmt::Debug for StreamMiddleware {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("StreamMiddleware").finish_non_exhaustive()
}
}
// ─── Compile-time Send + Sync assertion ─────────────────────────────────────
const _: () = {
const fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<StreamMiddleware>();
};
#[cfg(test)]
#[path = "stream_middleware_tests.rs"]
mod tests;