ag_ui/axum/respond.rs
1//! Turning a run's event stream into an HTTP response.
2//!
3//! Two things happen here that are easy to get wrong.
4//!
5//! **Negotiation is a decision, not a fallback.** [`negotiate`] asks
6//! [`crate::encode::media_type`] what to answer with and refuses the
7//! request when the answer is "nothing" — a client that asked for
8//! `application/xml` gets a `406`, not an SSE stream it cannot read.
9//!
10//! **The body owns its input stream.** For [`crate::server::Runner`], polling
11//! that stream *is* running the agent
12//! ([`crate::server::run()`] has no executor of its own), so the response body and
13//! the run have exactly the same lifetime. That is what makes disconnect
14//! handling work: when the client goes away hyper drops the body, and the body
15//! drops a guard that trips the run's [`CancellationToken`]. See
16//! [`SseResponse::cancellation`]. An externally owned durable run can instead
17//! pass a subscription to [`SseResponse::stream_frames`] and omit cancellation;
18//! dropping the response then detaches the subscription, leaving execution to
19//! its owner.
20
21use std::io;
22use std::pin::Pin;
23use std::task::{Context, Poll};
24use std::time::Duration;
25
26use crate::encode::sse;
27use crate::server::CancellationToken;
28use crate::{Event, SSE_MEDIA_TYPE, SseFormatter, media_type};
29use axum::body::Body;
30use axum::http::{HeaderValue, header};
31use axum::response::sse::{Event as HttpEvent, KeepAlive};
32use axum::response::{IntoResponse, Response, Sse};
33use futures_util::stream::{Stream, StreamExt};
34use serde::Serialize;
35
36use crate::axum::error::{Error, Result};
37
38/// Picks the response encoding for an `Accept` header.
39///
40/// A missing or empty header means `*/*` and yields SSE. Anything that excludes
41/// every media type this build can emit is [`Error::NotAcceptable`], which
42/// renders as a `406`.
43///
44/// ```
45/// # use ag_ui::axum::respond::negotiate;
46/// assert!(negotiate(None).is_ok());
47/// assert!(negotiate(Some("text/event-stream")).is_ok());
48/// assert!(negotiate(Some("text/*;q=0.4, application/json")).is_ok());
49/// assert!(negotiate(Some("application/xml")).is_err());
50/// assert!(negotiate(Some("*/*;q=0")).is_err());
51/// ```
52pub fn negotiate(accept: Option<&str>) -> Result<SseFormatter> {
53 let refuse = || Error::NotAcceptable {
54 accept: accept.unwrap_or("*/*").to_owned(),
55 };
56 match media_type(accept).map_err(|_| refuse())? {
57 SSE_MEDIA_TYPE => Ok(SseFormatter::new()),
58 // Only reachable if this crate ever enables a core encoding it has not
59 // taught this function to build. Refusing beats answering with a
60 // content type whose body would be SSE.
61 _ => Err(refuse()),
62 }
63}
64
65pub use crate::encode::sse::SseFrame;
66
67/// A negotiated event-stream response, waiting for the stream to put in it.
68///
69/// The full manual wiring, for a handler that does its own work before starting
70/// the run — [`route_agui`](crate::axum::RouterExt::route_agui) is this, with the
71/// defaults filled in:
72///
73/// ```
74/// use ag_ui::axum::SseResponse;
75/// use ag_ui::{RunAgentInput, RunOutcome};
76/// use ag_ui::server::{Agent, Result, RunContext, Runner};
77///
78/// # struct Greeter;
79/// # impl Agent for Greeter {
80/// # type State = ();
81/// # async fn run(&self, ctx: &mut RunContext<()>) -> Result<RunOutcome> {
82/// # ctx.say("hi")?;
83/// # Ok(RunOutcome::Success)
84/// # }
85/// # }
86/// # fn serve(accept: Option<&str>, input: RunAgentInput) -> axum::response::Result<axum::response::Response> {
87/// let response = SseResponse::negotiate(accept)?;
88///
89/// let runner = Runner::new(Greeter);
90/// // Take the token *before* `run` consumes the runner.
91/// let response = response.cancellation(runner.cancellation_token());
92///
93/// Ok(response.stream(runner.run(input)))
94/// # }
95/// ```
96#[derive(Clone, Debug)]
97#[must_use = "an SseResponse does nothing until a stream is attached"]
98pub struct SseResponse {
99 formatter: SseFormatter,
100 cancellation: Option<CancellationToken>,
101 keep_alive: Option<Duration>,
102}
103
104impl SseResponse {
105 /// Negotiates the encoding for an `Accept` header — see [`negotiate`].
106 pub fn negotiate(accept: Option<&str>) -> Result<Self> {
107 Ok(Self {
108 formatter: self::negotiate(accept)?,
109 cancellation: None,
110 keep_alive: None,
111 })
112 }
113
114 /// Trips `token` when the client disconnects.
115 ///
116 /// The token to pass is the one the run was built with —
117 /// [`crate::server::Runner::cancellation_token`].
118 ///
119 /// # How the disconnect is noticed
120 ///
121 /// There is no callback to register: hyper *drops* the response body when
122 /// the connection breaks, so a [`Drop`] impl on the body is the signal. The
123 /// guard disarms itself when the stream ends normally, so a completed run
124 /// is never reported as cancelled.
125 ///
126 /// Dropping the body would already stop the agent — the future lives inside
127 /// the stream. The token is what reaches everything *outside* it: a
128 /// spawned tool call, an in-flight model request, a lock the run holds.
129 pub fn cancellation(mut self, token: CancellationToken) -> Self {
130 self.cancellation = Some(token);
131 self
132 }
133
134 /// Sends an SSE comment whenever the agent has produced nothing for
135 /// `interval`.
136 ///
137 /// Off by default on this lower-level response builder. The hosted
138 /// [`AgentEndpoint`](crate::axum::AgentEndpoint) enables 15-second comments
139 /// automatically. Choose an interval below the hosting proxy's idle timeout.
140 pub fn keep_alive(mut self, interval: Duration) -> Self {
141 self.keep_alive = Some(interval);
142 self
143 }
144
145 /// Attaches a run's event stream and builds the response.
146 ///
147 /// This is what [`Runner::run`](crate::server::Runner::run) returns: a
148 /// stream that reports its own failures as `RUN_ERROR` and so has no error
149 /// item. For a stream that can fail, use [`Self::try_stream`].
150 pub fn stream<S>(self, events: S) -> Response
151 where
152 S: Stream<Item = Event> + Send + 'static,
153 {
154 self.stream_frames(
155 events.map(|event| Ok::<_, std::convert::Infallible>(SseFrame::Event(event))),
156 )
157 }
158
159 /// Attaches a run-owned event stream whose source can fail, and builds the
160 /// response.
161 ///
162 /// For a run supplied from outside [`Runner`](crate::server::Runner): a
163 /// source error ends that run, so it is reported as `RUN_ERROR`, trips the
164 /// cancellation token and nothing after it is read. For a subscription
165 /// whose transport can fail independently of execution, use
166 /// [`Self::stream_frames`] instead.
167 pub fn try_stream<S>(self, events: S) -> Response
168 where
169 S: Stream<Item = crate::server::Result<Event>> + Send + 'static,
170 {
171 let events = crate::server::run::terminal_error_events(events, self.cancellation.clone());
172 self.stream(events)
173 }
174
175 /// Optional lower-level SSE transport for supplied values and comments.
176 /// The source may use its own error type; no SDK hosting error is required.
177 /// Use `Ok::<_, std::convert::Infallible>(frame)` for an infallible source.
178 ///
179 /// Serialization is not protocol validation or a schema extension. New
180 /// producers use standard `Event` values and `metadata`; a host can supply
181 /// its own compatibility representation when replaying older data.
182 ///
183 /// Source and serialization failures become response-body errors and stop
184 /// polling. They never manufacture `RUN_ERROR`: the producer owns the run
185 /// lifecycle, which may outlive this subscription.
186 ///
187 /// For externally owned runs, omit `cancellation`: dropping this response
188 /// detaches its subscription. An explicitly supplied token is cancelled
189 /// on disconnect or transport failure, never on clean EOF.
190 pub fn stream_frames<S, E, StreamError>(self, frames: S) -> Response
191 where
192 S: Stream<Item = std::result::Result<SseFrame<E>, StreamError>> + Send + 'static,
193 E: Serialize + Send + 'static,
194 StreamError: Send + 'static,
195 {
196 let events = HttpEvents {
197 guard: DisconnectGuard {
198 token: self.cancellation,
199 armed: true,
200 },
201 events: Some(Box::pin(frames)),
202 formatter: self.formatter,
203 };
204 // Axum owns framing, body polling and keep-alive. Construct its timer
205 // only when the body is polled, so building a response needs no runtime.
206 let body = Body::from_stream(
207 futures_util::stream::once(async move {
208 let sse = Sse::new(events);
209 let response = match self.keep_alive {
210 Some(interval) => sse
211 .keep_alive(KeepAlive::new().interval(interval))
212 .into_response(),
213 None => sse.into_response(),
214 };
215 response.into_body().into_data_stream()
216 })
217 .flatten(),
218 );
219 let mut response = Response::new(body);
220 let headers = response.headers_mut();
221 headers.insert(
222 header::CONTENT_TYPE,
223 HeaderValue::from_static(SSE_MEDIA_TYPE),
224 );
225 headers.insert(
226 header::CACHE_CONTROL,
227 HeaderValue::from_static("no-cache, no-store, no-transform"),
228 );
229 headers.insert(
230 header::HeaderName::from_static("x-accel-buffering"),
231 HeaderValue::from_static("no"),
232 );
233 headers.insert(header::VARY, HeaderValue::from_static("accept"));
234 response
235 }
236}
237
238type EventFrames<E, StreamError> =
239 Pin<Box<dyn Stream<Item = std::result::Result<SseFrame<E>, StreamError>> + Send>>;
240
241/// Converts typed SDK values into Axum SSE items. It owns no run lifecycle.
242struct HttpEvents<E, StreamError> {
243 // Cancel before dropping the input stream, including before its first poll.
244 guard: DisconnectGuard,
245 events: Option<EventFrames<E, StreamError>>,
246 formatter: SseFormatter,
247}
248
249impl<E: Serialize, StreamError> HttpEvents<E, StreamError> {
250 fn encode(&self, frame: SseFrame<E>) -> std::result::Result<HttpEvent, io::Error> {
251 match frame {
252 SseFrame::Event(event) => self
253 .formatter
254 .event_json(&event)
255 .map(|json| HttpEvent::default().data(json))
256 .map_err(|_| io::Error::other("SSE event serialization failed")),
257 SseFrame::Comment(comment) => Ok(sse::comment_lines(&comment)
258 .fold(HttpEvent::default(), |event, line| event.comment(line))),
259 }
260 }
261
262 fn finish(&mut self) {
263 self.guard.armed = false;
264 self.events = None;
265 }
266
267 fn fail(&mut self) {
268 if let Some(token) = &self.guard.token {
269 token.cancel();
270 }
271 self.finish();
272 }
273}
274
275impl<E: Serialize, StreamError> Stream for HttpEvents<E, StreamError> {
276 type Item = std::result::Result<HttpEvent, io::Error>;
277
278 fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
279 let this = self.get_mut();
280 let Some(events) = this.events.as_mut() else {
281 return Poll::Ready(None);
282 };
283 match events.as_mut().poll_next(cx) {
284 Poll::Ready(Some(Ok(frame))) => {
285 let encoded = this.encode(frame);
286 if encoded.is_err() {
287 this.fail();
288 }
289 Poll::Ready(Some(encoded))
290 }
291 Poll::Ready(Some(Err(_))) => {
292 this.fail();
293 Poll::Ready(Some(Err(io::Error::other("SSE source stream failed"))))
294 }
295 Poll::Ready(None) => {
296 this.finish();
297 Poll::Ready(None)
298 }
299 Poll::Pending => Poll::Pending,
300 }
301 }
302}
303
304/// Only an explicitly supplied token can tie disconnection to execution.
305struct DisconnectGuard {
306 token: Option<CancellationToken>,
307 armed: bool,
308}
309
310impl Drop for DisconnectGuard {
311 fn drop(&mut self) {
312 if self.armed {
313 if let Some(token) = &self.token {
314 token.cancel();
315 }
316 }
317 }
318}
319
320#[cfg(test)]
321mod tests {
322 use super::*;
323 use axum::http::StatusCode;
324 use axum::response::IntoResponse;
325
326 #[test]
327 fn a_refused_accept_is_a_406() {
328 let error = negotiate(Some("application/xml")).expect_err("should refuse");
329 assert_eq!(error.status(), StatusCode::NOT_ACCEPTABLE);
330 assert_eq!(
331 error.into_response().status(),
332 StatusCode::NOT_ACCEPTABLE,
333 "the rendered response should carry the status too"
334 );
335 }
336
337 #[test]
338 fn a_quality_of_zero_is_a_refusal() {
339 assert!(negotiate(Some("text/event-stream;q=0")).is_err());
340 }
341
342 #[test]
343 fn an_empty_accept_header_means_anything() {
344 assert!(negotiate(Some("")).is_ok());
345 assert!(negotiate(Some(" ")).is_ok());
346 }
347
348 #[test]
349 fn the_message_names_what_the_endpoint_can_emit() {
350 let error = negotiate(Some("application/xml")).expect_err("should refuse");
351 assert!(error.to_string().contains(SSE_MEDIA_TYPE), "{error}");
352 }
353}