Skip to main content

ag_ui/encode/
mod.rs

1//! Wire encoding for the event stream.
2//!
3//! [`EventStreamFormatter`] is the abstraction a transport implements.
4#![cfg_attr(
5    feature = "sse",
6    doc = "[`sse::SseFormatter`] is the one every AG-UI implementation supports."
7)]
8#![cfg_attr(
9    not(feature = "sse"),
10    doc = "`sse::SseFormatter` is the one every AG-UI implementation supports, and the",
11    doc = "`sse` feature is off in this build."
12)]
13//!
14//! ```
15//! # #[cfg(feature = "sse")] {
16//! use ag_ui::{Event, EventStreamFormatter, SseFormatter};
17//!
18//! let formatter = SseFormatter::new();
19//! let bytes = formatter.encode(&Event::text_message_end("msg-1")).unwrap();
20//! assert_eq!(
21//!     String::from_utf8(bytes).unwrap(),
22//!     "data: {\"type\":\"TEXT_MESSAGE_END\",\"messageId\":\"msg-1\"}\n\n"
23//! );
24//! # }
25//! ```
26
27#[cfg(feature = "protobuf")]
28pub mod protobuf;
29#[cfg(feature = "sse")]
30pub mod sse;
31
32use crate::error::{Error, Result};
33use crate::event::Event;
34
35/// Media type of a Server-Sent Events stream.
36pub const SSE_MEDIA_TYPE: &str = "text/event-stream";
37
38/// Media type of the AG-UI binary stream, as defined by the upstream
39/// `@ag-ui/proto` package.
40pub const PROTOBUF_MEDIA_TYPE: &str = "application/vnd.ag-ui.event+proto";
41
42// Protobuf has a media type and, behind its feature, a formatter that refuses
43// every event. Negotiation must advertise only encodings we can actually emit.
44#[cfg(feature = "sse")]
45const SUPPORTED: &[&str] = &[SSE_MEDIA_TYPE];
46#[cfg(not(feature = "sse"))]
47const SUPPORTED: &[&str] = &[];
48
49/// Turns events into the bytes a transport puts on the wire.
50///
51/// Object-safe, so a server can pick a formatter once per connection and store
52/// it as `Box<dyn EventStreamFormatter>`.
53pub trait EventStreamFormatter {
54    /// The `Content-Type` to answer with.
55    fn content_type(&self) -> &'static str;
56
57    /// Encodes one event, framing included.
58    fn encode(&self, event: &Event) -> Result<Vec<u8>>;
59}
60
61/// The media types this build can emit, most preferred first.
62pub const fn supported_media_types() -> &'static [&'static str] {
63    SUPPORTED
64}
65
66/// Picks the media type to answer an `Accept` header with.
67///
68/// A missing or empty header is treated as `*/*`, per RFC 9110. Candidates are
69/// scored by quality value; ties go to this crate's own preference order.
70/// SSE is the only implemented transport, with or without the `protobuf`
71/// feature, so the binary media type is never the answer.
72///
73/// Returns [`Error::UnsupportedMediaType`] when the header excludes everything
74/// this build can emit — the case that deserves a `406`.
75///
76/// ```
77/// # use ag_ui::encode::{media_type, SSE_MEDIA_TYPE};
78/// assert_eq!(media_type(None).unwrap(), SSE_MEDIA_TYPE);
79/// assert_eq!(media_type(Some("text/event-stream")).unwrap(), SSE_MEDIA_TYPE);
80/// assert!(media_type(Some("application/xml")).is_err());
81/// ```
82pub fn media_type(accept: Option<&str>) -> Result<&'static str> {
83    let header = accept
84        .map(str::trim)
85        .filter(|value| !value.is_empty())
86        .unwrap_or("*/*");
87
88    let specs: Vec<AcceptSpec<'_>> = header.split(',').filter_map(AcceptSpec::parse).collect();
89
90    let mut best: Option<(&'static str, f32)> = None;
91    for candidate in SUPPORTED {
92        let quality = quality_of(candidate, &specs);
93        if quality > 0.0 && best.is_none_or(|(_, best_quality)| quality > best_quality) {
94            best = Some((candidate, quality));
95        }
96    }
97
98    best.map(|(media_type, _)| media_type)
99        .ok_or_else(|| Error::UnsupportedMediaType(header.to_owned()))
100}
101
102/// One entry of an `Accept` header: a media range and its quality value.
103struct AcceptSpec<'a> {
104    kind: &'a str,
105    subtype: &'a str,
106    quality: f32,
107}
108
109impl<'a> AcceptSpec<'a> {
110    fn parse(entry: &'a str) -> Option<Self> {
111        let mut parts = entry.split(';');
112        let (kind, subtype) = split_media_type(parts.next()?.trim())?;
113
114        // Only `q` is read. The other parameters affect specificity in the full
115        // RFC 9110 algorithm, but no media type this crate emits is
116        // parameterized, so they can never change the outcome here.
117        let quality = parts
118            .find_map(|param| {
119                let (key, value) = param.split_once('=')?;
120                key.trim().eq_ignore_ascii_case("q").then_some(value)
121            })
122            .and_then(|value| value.trim().trim_matches('"').parse::<f32>().ok())
123            .unwrap_or(1.0);
124
125        Some(Self {
126            kind,
127            subtype,
128            quality,
129        })
130    }
131
132    /// How specifically this range names `kind`/`subtype`, or `None` when it
133    /// does not match at all. Higher is more specific.
134    fn specificity(&self, kind: &str, subtype: &str) -> Option<u8> {
135        let mut score = 0;
136
137        if self.kind.eq_ignore_ascii_case(kind) {
138            score |= 4;
139        } else if self.kind != "*" {
140            return None;
141        }
142
143        if self.subtype.eq_ignore_ascii_case(subtype) {
144            score |= 2;
145        } else if self.subtype != "*" {
146            return None;
147        }
148
149        Some(score)
150    }
151}
152
153/// The quality the header assigns to `candidate`, from its most specific
154/// matching range. Zero means unacceptable.
155fn quality_of(candidate: &str, specs: &[AcceptSpec<'_>]) -> f32 {
156    let Some((kind, subtype)) = split_media_type(candidate) else {
157        return 0.0;
158    };
159
160    let mut best: Option<(u8, f32)> = None;
161    for spec in specs {
162        let Some(specificity) = spec.specificity(kind, subtype) else {
163            continue;
164        };
165        if best.is_none_or(|(best_specificity, _)| specificity > best_specificity) {
166            best = Some((specificity, spec.quality));
167        }
168    }
169
170    best.map_or(0.0, |(_, quality)| quality)
171}
172
173/// Splits `type/subtype`, ignoring any parameters.
174fn split_media_type(value: &str) -> Option<(&str, &str)> {
175    let value = value.split(';').next()?.trim();
176    let (kind, subtype) = value.split_once('/')?;
177    (!kind.is_empty() && !subtype.is_empty()).then_some((kind, subtype))
178}