Skip to main content

ag_ui/client/
chunks.rs

1//! Normalizing `*_CHUNK` events into explicit start/content/end triples.
2//!
3//! A producer that cannot bracket its output — most provider adapters, because
4//! the upstream API does not tell them a message has ended until the next one
5//! begins — sends `TEXT_MESSAGE_CHUNK`, `TOOL_CALL_CHUNK` and
6//! `REASONING_MESSAGE_CHUNK` instead. Those events fold start, content and end
7//! into one, and they carry their id and name **only on the first chunk**:
8//!
9//! ```text
10//! TEXT_MESSAGE_CHUNK { messageId: "msg-1", delta: "Hel" }
11//! TEXT_MESSAGE_CHUNK { delta: "lo" }
12//! TEXT_MESSAGE_CHUNK { messageId: "msg-2", delta: "Bye" }   <- msg-1 just ended
13//! ```
14//!
15//! So the id has to be remembered, and the end of one stream is only knowable
16//! from what follows it. That bookkeeping is this module.
17//!
18//! # What ends a chunk stream
19//!
20//! AG-UI 1.0 lists it, per *lane* — the parent agent's, or one subagent's:
21//!
22//! - a chunk that opens a different item in the same lane;
23//! - a message, tool-call, step, state, custom or reasoning event in that
24//!   lane. `RAW`, `ACTIVITY_SNAPSHOT`, `ACTIVITY_DELTA`,
25//!   `REASONING_ENCRYPTED_VALUE` and `SUBAGENT_STARTED` stand aside and end
26//!   nothing;
27//! - `RUN_STARTED`, `RUN_FINISHED`, `RUN_ERROR` or `MESSAGES_SNAPSHOT`, which
28//!   end every lane's;
29//! - `SUBAGENT_FINISHED` or `SUBAGENT_ERROR`, which end that subagent's.
30//!
31//! A chunk that names no id after one of these has nothing to continue, and is
32//! rejected. So is a continuation that repeats `role`, `name`, `toolCallName`
33//! or `parentMessageId` with a value other than the one its stream was opened
34//! with — an absent `role` having opened an `assistant` message.
35//!
36//! ```
37//! use ag_ui::client::chunks::normalize_all;
38//! use ag_ui::{Event, EventType, MessageId};
39//!
40//! let events = normalize_all([
41//!     Event::text_message_chunk(Some(MessageId::new("msg-1")), Some("Hel".into())),
42//!     Event::text_message_chunk(None, Some("lo".into())),
43//! ])?;
44//!
45//! let types: Vec<EventType> = events.iter().map(Event::event_type).collect();
46//! assert_eq!(types, [
47//!     EventType::TextMessageStart,
48//!     EventType::TextMessageContent,
49//!     EventType::TextMessageContent,
50//!     EventType::TextMessageEnd,
51//! ]);
52//! # Ok::<(), ag_ui::client::Error>(())
53//! ```
54//!
55//! # What the synthesized events carry
56//!
57//! A chunk's `metadata` goes on every event synthesized from it, so it merges
58//! into the item; its `rawEvent` goes on the content event; its `timestamp` on
59//! none, since the synthesized events are not the chunk. A continuation that
60//! carries only metadata, such as a final chunk reporting a finish reason,
61//! stands for a content event with an empty delta, which is how the metadata
62//! reaches the item. So does a chunk that carries a `rawEvent` and no delta.
63//!
64//! ```
65//! use ag_ui::client::chunks::normalize_all;
66//! use ag_ui::{Event, MessageId};
67//! use serde_json::json;
68//!
69//! let finish = json!({ "finishReason": "stop" }).as_object().unwrap().clone();
70//! let events = normalize_all([
71//!     Event::text_message_chunk(Some(MessageId::new("msg-1")), Some("Done.".into())),
72//!     Event::text_message_chunk(None, None).with_metadata(finish.clone()),
73//! ])?;
74//!
75//! let Event::TextMessageContent(last) = &events[2] else { panic!("{events:?}") };
76//! assert_eq!(last.delta, "");
77//! assert_eq!(last.base.metadata, Some(finish));
78//! # Ok::<(), ag_ui::client::Error>(())
79//! ```
80//!
81//! # The two spellings do not mix
82//!
83//! An item opened by a chunk is continued and closed in chunk form, and one
84//! opened by a `*_START` event explicitly. An explicit event that names the id
85//! a chunk stream is assembling is in that stream's lane like any other, so it
86//! ends the stream: the synthesized end comes out first, then the event,
87//! which [`crate::client::verify`] judges by the rules of the explicit form.
88//! The other way round, an explicitly opened item is not a stream a chunk can
89//! continue: a chunk that names no id is rejected unless a *chunk* opened
90//! something for it to continue, and one that names the open item's id opens
91//! it again.
92//!
93//! ```
94//! use ag_ui::client::{normalize_all, verify_all};
95//! use ag_ui::{Event, EventType, MessageId};
96//!
97//! let events = normalize_all([
98//!     Event::run_started("thread-1", "run-1"),
99//!     Event::text_message_chunk(Some(MessageId::new("msg-1")), Some("Hel".into())),
100//!     Event::text_message_end("msg-1"),
101//! ])?;
102//! let types: Vec<EventType> = events.iter().map(Event::event_type).collect();
103//! // The chunk stream ended when the explicit event arrived ...
104//! assert_eq!(types[3..], [EventType::TextMessageEnd, EventType::TextMessageEnd]);
105//! // ... so that event closes a message that is no longer open.
106//! assert!(verify_all(&events).is_err());
107//! # Ok::<(), ag_ui::client::Error>(())
108//! ```
109//!
110//! # Subagents
111//!
112//! "The previous chunk" is only meaningful *per subagent* once several stream
113//! at once, so the shorthand resolves within the sending subagent's own
114//! stream: one stream may be open per owner, and a chunk that names no id
115//! continues the stream of the subagent it is attributed to. A chunk that
116//! carries neither an id nor a `subagentRunId` continues the parent's open
117//! stream when there is one, and otherwise the sole open stream; when several
118//! subagents' streams could all claim it there is nothing to resolve it
119//! against, and it is rejected rather than guessed at. When streaming
120//! concurrently, attribute every chunk — or repeat the id.
121
122use crate::Event;
123use crate::streams::Streams;
124
125use crate::client::error::{Error, Result};
126
127/// Expands chunk events into the explicit events the rest of the protocol is
128/// written in.
129///
130/// Feed every event of a run through it, in order, and apply what comes out.
131/// Events that are not chunks pass through untouched, after the end of
132/// whatever chunk stream they close.
133#[derive(Clone, Debug, Default)]
134pub struct ChunkNormalizer {
135    streams: Streams,
136}
137
138impl ChunkNormalizer {
139    /// A normalizer with nothing open.
140    pub fn new() -> Self {
141        Self::default()
142    }
143
144    /// Whether a chunk stream is currently open: one a chunk opened and
145    /// nothing has ended yet.
146    pub fn is_open(&self) -> bool {
147        !self.streams.is_idle()
148    }
149
150    /// Expands one event, appending the result to `out`.
151    ///
152    /// Appends the synthesized end of each stream the event closes, then for
153    /// a chunk the synthesized start of the stream it opens and its content,
154    /// and for any other event the event itself.
155    ///
156    /// # Errors
157    ///
158    /// A chunk that names no stream and has none to continue — none open, or
159    /// several subagents' open and no attribution to pick one — or a tool call
160    /// chunk that opens a call without naming the tool, is a protocol
161    /// violation: there is no id to attach the payload to, and guessing one
162    /// would put text in the wrong message. So is a continuation chunk that
163    /// contradicts what its stream was opened with. Nothing is appended and
164    /// nothing changes when a chunk is rejected.
165    pub fn normalize(&mut self, event: Event, out: &mut Vec<Event>) -> Result<()> {
166        self.streams
167            .expand(event, out)
168            .map_err(|error| Error::protocol(error.to_string()))
169    }
170
171    /// Closes whatever the normalizer opened but never got to end.
172    ///
173    /// Call this when the transport stream ends. A chunk stream that never
174    /// terminates is the normal case, not an error: the last message of a run
175    /// has nothing after it to imply its end.
176    pub fn finish(&mut self, out: &mut Vec<Event>) {
177        self.streams.finish(out);
178    }
179
180    /// Drops what is being assembled without ending it, for a run that
181    /// failed: what it had open ends with it. Whose each item is stays
182    /// known, for the lane of an untagged event of a later run.
183    pub(crate) fn abandon(&mut self) {
184        self.streams.abandon();
185    }
186}
187
188/// Normalizes a whole run in one call, closing anything left open at the end.
189///
190/// The streaming form is [`ChunkNormalizer`]; this is the convenience for
191/// tests, recorded streams, and anything else that has all the events already.
192pub fn normalize_all(events: impl IntoIterator<Item = Event>) -> Result<Vec<Event>> {
193    let mut normalizer = ChunkNormalizer::new();
194    let mut out = Vec::new();
195    for event in events {
196        normalizer.normalize(event, &mut out)?;
197    }
198    normalizer.finish(&mut out);
199    Ok(out)
200}