ag-ui 1.0.0

Rust SDK for AG-UI 1.0 with protocol types, SSE, a server runtime for hosting agents, and a client runtime for consuming them.
Documentation
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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
//! Decoding `text/event-stream`.
//!
//! The encoder lives in `ag_ui::encode`; this is the other half. It is a wire
//! format parser fed by a network, so it assumes nothing about what it is
//! handed: bytes arrive in arbitrary chunks that split lines, split UTF-8
//! sequences, and end without the terminating blank line the format calls for.
//!
//! What it handles, because real servers and proxies do all of it:
//!
//! - `data:` repeated over several lines, rejoined with `\n` — the format's own
//!   way of carrying a payload that contains newlines.
//! - Comment lines (`: keep-alive`), which proxies inject to hold a connection
//!   open and which dispatch nothing.
//! - A body that ends without a blank line: [`SseDecoder::finish`] dispatches
//!   the last frame rather than dropping it.
//! - `\n`, `\r\n` and lone `\r` line endings, including a `\r\n` split across
//!   two chunks.
//! - A leading UTF-8 byte-order mark.
//! - A field with no colon, an empty field value, and unknown field names.
//! - A frame with no `data` field, which the format says not to dispatch.
//!
//! What it refuses: invalid UTF-8, and a single frame larger than
//! [`SseDecoder::max_frame_size`] — an unterminated line is otherwise an
//! unbounded allocation driven by the other end. The cap is on the frame, not
//! on the chunk: one read carrying a thousand complete frames is ordinary, and
//! counting it against a per-frame limit would refuse a well-behaved server.
//!
//! ```
//! use ag_ui::client::transport::SseDecoder;
//!
//! let mut decoder = SseDecoder::new();
//! decoder.push(b": keep-alive\n\ndata: {\"type\":\"RUN_ERROR\",\"mes")?;
//! assert!(decoder.next_frame()?.is_none());
//!
//! decoder.push(b"sage\":\"boom\"}\n\n")?;
//! let frame = decoder.next_frame()?.expect("a complete frame");
//! assert_eq!(frame.into_event()?.event_type().as_str(), "RUN_ERROR");
//! # Ok::<(), ag_ui::client::Error>(())
//! ```

use std::collections::VecDeque;

use crate::Event;
use futures_core::Stream;
use futures_util::StreamExt;
use serde_json::Value;

use crate::client::error::{Error, Result};

/// The default cap on one frame, before the decoder gives up: 8 MiB.
pub const DEFAULT_MAX_FRAME_SIZE: usize = 8 * 1024 * 1024;

/// One decoded `text/event-stream` frame.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct SseFrame {
    /// The `event:` field, if the server sent one. AG-UI does not use it.
    pub event: Option<String>,
    /// The `data:` field, with the trailing newline removed and multiple
    /// `data:` lines rejoined with `\n`.
    pub data: String,
    /// The `id:` field, if the server sent one.
    pub id: Option<String>,
    /// The `retry:` field, in milliseconds, if the server sent one.
    pub retry: Option<u64>,
}

impl SseFrame {
    /// Parses the frame payload as JSON without discarding any unknown fields.
    pub fn into_raw_value(self) -> Result<Value> {
        serde_json::from_str(&self.data).map_err(Error::from)
    }

    /// Parses one frame strictly, without the stream compatibility and
    /// enforcement stages. Application streams use [`decode_events`].
    pub fn into_event(self) -> Result<Event> {
        serde_json::from_str(&self.data).map_err(Error::from)
    }
}

/// An incremental `text/event-stream` decoder.
///
/// Push bytes, pull frames. It owns a buffer for the partial line at the end of
/// each chunk, which is why it has to be a struct and not a function.
#[derive(Clone, Debug)]
pub struct SseDecoder {
    buffer: Vec<u8>,
    /// How much of `buffer` has already been handed out as lines.
    ///
    /// The consumed prefix is dropped on the next push rather than as each line
    /// is taken: shifting the remainder once per read instead of once per line
    /// is what keeps a chunk carrying a thousand frames linear.
    consumed: usize,
    /// A CR at the end of the last read already ended its line. If the
    /// next nonempty read begins with LF, consume it as part of that CRLF.
    skip_lf: bool,
    /// First byte of the pending line not yet checked for a terminator.
    scan_from: usize,
    data: String,
    event: Option<String>,
    id: Option<String>,
    retry: Option<u64>,
    max_frame_size: usize,
    frame_bytes: usize,
    at_start: bool,
}

impl Default for SseDecoder {
    fn default() -> Self {
        Self::new()
    }
}

impl SseDecoder {
    /// A decoder with the default frame size cap.
    pub fn new() -> Self {
        Self {
            buffer: Vec::new(),
            consumed: 0,
            skip_lf: false,
            scan_from: 0,
            data: String::new(),
            event: None,
            id: None,
            retry: None,
            max_frame_size: DEFAULT_MAX_FRAME_SIZE,
            frame_bytes: 0,
            at_start: true,
        }
    }

    /// Sets the cap on a single frame, counting UTF-8 field and comment bytes
    /// but excluding line terminators and the initial byte-order mark.
    #[must_use]
    pub fn with_max_frame_size(mut self, bytes: usize) -> Self {
        self.max_frame_size = bytes;
        self
    }

    /// The cap on a single frame, in bytes.
    pub fn max_frame_size(&self) -> usize {
        self.max_frame_size
    }

    /// Feeds the decoder a chunk of the response body.
    ///
    /// # Errors
    ///
    /// [`Error::Decode`] when the frame being assembled exceeds
    /// [`SseDecoder::max_frame_size`] — a server that never sends a line break
    /// would otherwise grow this buffer without bound.
    pub fn push(&mut self, bytes: &[u8]) -> Result<()> {
        if self.consumed > 0 {
            self.buffer.drain(..self.consumed);
            self.scan_from -= self.consumed;
            self.consumed = 0;
        }
        let bytes = if self.skip_lf && !bytes.is_empty() {
            self.skip_lf = false;
            bytes.strip_prefix(b"\n").unwrap_or(bytes)
        } else {
            bytes
        };
        self.buffer.extend_from_slice(bytes);
        // A complete line may dispatch an earlier frame. Leave later lines
        // for next_frame so network chunking cannot hide a valid prefix.
        if self.line_end().is_none() {
            self.check_partial_line()?;
        }
        Ok(())
    }

    /// The bytes pushed but not yet handed out as lines.
    fn pending(&self) -> &[u8] {
        &self.buffer[self.consumed..]
    }

    fn line_end(&mut self) -> Option<usize> {
        let rest = &self.buffer[self.scan_from..];
        let scanned = rest
            .iter()
            .position(|b| matches!(b, b'\n' | b'\r'))
            .unwrap_or(rest.len());
        self.scan_from += scanned;
        (self.scan_from < self.buffer.len()).then_some(self.scan_from)
    }

    fn check_partial_line(&self) -> Result<()> {
        let pending = self.without_initial_bom(self.pending());
        self.check_size(self.frame_bytes.saturating_add(pending.len()))
    }

    fn without_initial_bom<'a>(&self, pending: &'a [u8]) -> &'a [u8] {
        if self.at_start {
            if b"\xef\xbb\xbf".starts_with(pending) {
                return &[];
            }
            pending.strip_prefix(b"\xef\xbb\xbf").unwrap_or(pending)
        } else {
            pending
        }
    }

    fn check_size(&self, bytes: usize) -> Result<()> {
        if bytes > self.max_frame_size {
            return Err(Error::decode(format!(
                "frame exceeded the {} byte limit across its data lines or fields",
                self.max_frame_size
            )));
        }
        Ok(())
    }

    fn checked_process(&mut self, line: &str) -> Result<Option<SseFrame>> {
        if line.is_empty() {
            self.frame_bytes = 0;
        } else {
            self.frame_bytes = self.frame_bytes.saturating_add(line.len());
            self.check_size(self.frame_bytes)?;
        }
        Ok(self.process(line))
    }

    /// Pulls the next complete frame, if the bytes pushed so far contain one.
    ///
    /// # Errors
    ///
    /// [`Error::Decode`] when the bytes are not UTF-8 or the frame exceeds its cap.
    pub fn next_frame(&mut self) -> Result<Option<SseFrame>> {
        while let Some(line) = self.take_line(false)? {
            if let Some(frame) = self.checked_process(&line)? {
                return Ok(Some(frame));
            }
        }
        self.check_partial_line()?;
        Ok(None)
    }

    /// Drains the decoder at the end of the stream.
    ///
    /// A body that stops without the blank line that terminates its last frame
    /// is common enough — a closed connection, a server that forgets — that
    /// dropping the frame would lose real events. Anything still buffered is
    /// dispatched here.
    ///
    /// # Errors
    ///
    /// [`Error::Decode`] when the trailing bytes are not UTF-8 or exceed the cap.
    pub fn finish(&mut self) -> Result<Vec<SseFrame>> {
        let mut frames = Vec::new();
        while let Some(line) = self.take_line(true)? {
            if let Some(frame) = self.checked_process(&line)? {
                frames.push(frame);
            }
        }
        if let Some(frame) = self.dispatch() {
            frames.push(frame);
        }
        Ok(frames)
    }

    /// Takes one complete line, minus its terminator.
    ///
    /// At `eof` the trailing bytes count as a line even without a terminator.
    /// A trailing CR is already a terminator, even if the next read never arrives.
    fn take_line(&mut self, eof: bool) -> Result<Option<String>> {
        let position = self.line_end().map(|end| end - self.consumed);
        let pending = self.pending();
        let Some(position) = position else {
            if eof && !pending.is_empty() {
                let line = pending.to_vec();
                self.consumed = self.buffer.len();
                return self.decode_line(line).map(Some);
            }
            return Ok(None);
        };

        let is_cr = pending[position] == b'\r';
        let trailing_cr = is_cr && position + 1 == pending.len();
        let width = if is_cr && pending.get(position + 1) == Some(&b'\n') {
            2
        } else {
            1
        };
        let line = pending[..position].to_vec();
        self.skip_lf = trailing_cr;
        self.consumed += position + width;
        self.scan_from = self.consumed;
        self.decode_line(line).map(Some)
    }

    fn decode_line(&mut self, line: Vec<u8>) -> Result<String> {
        let mut line = String::from_utf8(line)
            .map_err(|error| Error::decode(format!("stream is not UTF-8: {error}")))?;
        if self.at_start {
            self.at_start = false;
            if let Some(stripped) = line.strip_prefix('\u{feff}') {
                line = stripped.to_owned();
            }
        }
        Ok(line)
    }

    /// Applies one line to the frame being built, dispatching on a blank line.
    fn process(&mut self, line: &str) -> Option<SseFrame> {
        if line.is_empty() {
            return self.dispatch();
        }
        if line.starts_with(':') {
            // A comment. Heartbeats are the usual reason one is here.
            return None;
        }

        let (field, value) = match line.find(':') {
            Some(index) => (&line[..index], strip_one_space(&line[index + 1..])),
            // A field name with no colon has an empty value.
            None => (line, ""),
        };

        match field {
            "data" => {
                self.data.push_str(value);
                self.data.push('\n');
            }
            "event" => self.event = Some(value.to_owned()),
            "id" => self.id = Some(value.to_owned()),
            "retry" => {
                if let Ok(milliseconds) = value.parse() {
                    self.retry = Some(milliseconds);
                }
            }
            // Unknown fields are ignored, as the format requires.
            _ => {}
        }
        None
    }

    /// Emits the buffered frame, if it has a payload.
    fn dispatch(&mut self) -> Option<SseFrame> {
        self.frame_bytes = 0;
        let event = self.event.take();
        let id = self.id.take();
        let retry = self.retry.take();
        let mut data = std::mem::take(&mut self.data);
        if data.is_empty() {
            // No data field: the format says this dispatches nothing. A frame
            // of pure comments or a stray blank line lands here.
            return None;
        }
        data.pop();
        Some(SseFrame {
            event,
            data,
            id,
            retry,
        })
    }
}

/// Removes the single optional space after a field's colon.
fn strip_one_space(value: &str) -> &str {
    value.strip_prefix(' ').unwrap_or(value)
}

/// Decodes a stream of byte chunks into a stream of events.
///
/// This is the adapter between a transport's body stream and the rest of the
/// crate. Unknown additions are dropped, while malformed known fields and
/// framing errors end the stream with an error item.
pub fn decode_events<S, B, E>(chunks: S) -> impl Stream<Item = Result<Event>>
where
    S: Stream<Item = core::result::Result<B, E>>,
    B: AsRef<[u8]>,
    E: std::error::Error + Send + Sync + 'static,
{
    crate::client::enforce::stream(decode_raw_events(chunks))
}

/// Decodes SSE frames into raw JSON values. A transport hands these on as
/// [`TransportStream::json`](super::TransportStream::json), so the common
/// compatibility boundary runs on what the peer actually sent.
pub fn decode_raw_events<S, B, E>(chunks: S) -> impl Stream<Item = Result<Value>>
where
    S: Stream<Item = core::result::Result<B, E>>,
    B: AsRef<[u8]>,
    E: std::error::Error + Send + Sync + 'static,
{
    let state = Decoding {
        chunks: Some(Box::pin(chunks)),
        decoder: SseDecoder::new(),
        ready: VecDeque::new(),
    };

    futures_util::stream::unfold(state, |mut state| async move {
        loop {
            if let Some(item) = state.ready.pop_front() {
                return Some((item, state));
            }
            match state.chunks.as_mut()?.next().await {
                Some(Ok(bytes)) => {
                    if let Err(error) = state.decoder.push(bytes.as_ref()) {
                        state.chunks = None;
                        return Some((Err(error), state));
                    }
                    loop {
                        match state.decoder.next_frame() {
                            Ok(Some(frame)) => match frame.into_raw_value() {
                                Ok(value) => state.ready.push_back(Ok(value)),
                                Err(error) => {
                                    state.ready.push_back(Err(error));
                                    state.chunks = None;
                                    break;
                                }
                            },
                            Ok(None) => break,
                            Err(error) => {
                                state.chunks = None;
                                state.ready.push_back(Err(error));
                                break;
                            }
                        }
                    }
                }
                Some(Err(error)) => {
                    state.chunks = None;
                    return Some((Err(Error::transport(error)), state));
                }
                None => {
                    state.chunks = None;
                    match state.decoder.finish() {
                        Ok(frames) => {
                            for frame in frames {
                                match frame.into_raw_value() {
                                    Ok(value) => state.ready.push_back(Ok(value)),
                                    Err(error) => {
                                        state.ready.push_back(Err(error));
                                        break;
                                    }
                                }
                            }
                        }
                        Err(error) => state.ready.push_back(Err(error)),
                    }
                }
            }
        }
    })
}

/// The state [`decode_events`] carries between polls.
struct Decoding<S> {
    chunks: Option<std::pin::Pin<Box<S>>>,
    decoder: SseDecoder,
    ready: VecDeque<Result<Value>>,
}

#[cfg(test)]
mod tests {
    use super::SseDecoder;

    /// A body of `frames` identical two-line frames, and the size of one.
    fn body(frames: usize) -> (String, usize) {
        let frame = "data: {\"type\":\"CUSTOM\"}\n\n";
        (frame.repeat(frames), frame.len())
    }

    #[test]
    fn taking_a_line_moves_the_cursor_instead_of_the_bytes_behind_it() {
        // `take_line` used to `split_off` the remainder of the buffer, copying
        // every byte still unread once per line. One read carrying a thousand
        // frames — a fast agent filling a TCP window — then cost a thousand
        // copies of a shrinking buffer, and the total grew with the square of
        // the frame count. The cursor is what makes it linear, and the buffer
        // holding still while frames come out of it is how that is visible
        // without timing anything.
        let (body, frame_size) = body(64);
        let mut decoder = SseDecoder::new();
        decoder.push(body.as_bytes()).expect("pushes");
        let pushed = decoder.buffer.len();

        for taken in 1..=32 {
            decoder
                .next_frame()
                .expect("decodes")
                .expect("64 frames went in");
            assert_eq!(
                decoder.buffer.len(),
                pushed,
                "the unread remainder was recopied after {taken} frames"
            );
            assert_eq!(decoder.consumed, taken * frame_size);
        }

        // The consumed prefix is dropped once, on the next push, rather than
        // once per line.
        decoder.push(b"data: x\n\n").expect("pushes");
        assert_eq!(decoder.consumed, 0);
        assert_eq!(decoder.buffer.len(), pushed - 32 * frame_size + 9);
    }

    #[test]
    fn dropping_the_consumed_prefix_does_not_disturb_what_is_still_buffered() {
        // That drop rewrites the offset every remaining byte sits at, so the
        // frames either side of a push have to come out whole and in order.
        let (body, _) = body(4);
        let mut decoder = SseDecoder::new();
        decoder.push(body.as_bytes()).expect("pushes");
        decoder.next_frame().expect("decodes").expect("a frame");
        decoder.next_frame().expect("decodes").expect("a frame");

        decoder.push(b"data: last\n\n").expect("pushes");
        let mut rest = Vec::new();
        while let Some(frame) = decoder.next_frame().expect("decodes") {
            rest.push(frame.data);
        }
        assert_eq!(
            rest,
            [r#"{"type":"CUSTOM"}"#, r#"{"type":"CUSTOM"}"#, "last"]
        );
    }
}