1#![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#[cfg(feature = "protobuf")]
28pub mod protobuf;
29#[cfg(feature = "sse")]
30pub mod sse;
31
32use crate::error::{Error, Result};
33use crate::event::Event;
34
35pub const SSE_MEDIA_TYPE: &str = "text/event-stream";
37
38pub const PROTOBUF_MEDIA_TYPE: &str = "application/vnd.ag-ui.event+proto";
41
42#[cfg(feature = "sse")]
45const SUPPORTED: &[&str] = &[SSE_MEDIA_TYPE];
46#[cfg(not(feature = "sse"))]
47const SUPPORTED: &[&str] = &[];
48
49pub trait EventStreamFormatter {
54 fn content_type(&self) -> &'static str;
56
57 fn encode(&self, event: &Event) -> Result<Vec<u8>>;
59}
60
61pub const fn supported_media_types() -> &'static [&'static str] {
63 SUPPORTED
64}
65
66pub 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
102struct 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 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 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
153fn 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
173fn 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}