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
//! Normalizing `*_CHUNK` events into explicit start/content/end triples.
//!
//! A producer that cannot bracket its output — most provider adapters, because
//! the upstream API does not tell them a message has ended until the next one
//! begins — sends `TEXT_MESSAGE_CHUNK`, `TOOL_CALL_CHUNK` and
//! `REASONING_MESSAGE_CHUNK` instead. Those events fold start, content and end
//! into one, and they carry their id and name **only on the first chunk**:
//!
//! ```text
//! TEXT_MESSAGE_CHUNK { messageId: "msg-1", delta: "Hel" }
//! TEXT_MESSAGE_CHUNK { delta: "lo" }
//! TEXT_MESSAGE_CHUNK { messageId: "msg-2", delta: "Bye" } <- msg-1 just ended
//! ```
//!
//! So the id has to be remembered, and the end of one stream is only knowable
//! from what follows it. That bookkeeping is this module.
//!
//! # What ends a chunk stream
//!
//! AG-UI 1.0 lists it, per *lane* — the parent agent's, or one subagent's:
//!
//! - a chunk that opens a different item in the same lane;
//! - a message, tool-call, step, state, custom or reasoning event in that
//! lane. `RAW`, `ACTIVITY_SNAPSHOT`, `ACTIVITY_DELTA`,
//! `REASONING_ENCRYPTED_VALUE` and `SUBAGENT_STARTED` stand aside and end
//! nothing;
//! - `RUN_STARTED`, `RUN_FINISHED`, `RUN_ERROR` or `MESSAGES_SNAPSHOT`, which
//! end every lane's;
//! - `SUBAGENT_FINISHED` or `SUBAGENT_ERROR`, which end that subagent's.
//!
//! A chunk that names no id after one of these has nothing to continue, and is
//! rejected. So is a continuation that repeats `role`, `name`, `toolCallName`
//! or `parentMessageId` with a value other than the one its stream was opened
//! with — an absent `role` having opened an `assistant` message.
//!
//! ```
//! use ag_ui::client::chunks::normalize_all;
//! use ag_ui::{Event, EventType, MessageId};
//!
//! let events = normalize_all([
//! Event::text_message_chunk(Some(MessageId::new("msg-1")), Some("Hel".into())),
//! Event::text_message_chunk(None, Some("lo".into())),
//! ])?;
//!
//! let types: Vec<EventType> = events.iter().map(Event::event_type).collect();
//! assert_eq!(types, [
//! EventType::TextMessageStart,
//! EventType::TextMessageContent,
//! EventType::TextMessageContent,
//! EventType::TextMessageEnd,
//! ]);
//! # Ok::<(), ag_ui::client::Error>(())
//! ```
//!
//! # What the synthesized events carry
//!
//! A chunk's `metadata` goes on every event synthesized from it, so it merges
//! into the item; its `rawEvent` goes on the content event; its `timestamp` on
//! none, since the synthesized events are not the chunk. A continuation that
//! carries only metadata, such as a final chunk reporting a finish reason,
//! stands for a content event with an empty delta, which is how the metadata
//! reaches the item. So does a chunk that carries a `rawEvent` and no delta.
//!
//! ```
//! use ag_ui::client::chunks::normalize_all;
//! use ag_ui::{Event, MessageId};
//! use serde_json::json;
//!
//! let finish = json!({ "finishReason": "stop" }).as_object().unwrap().clone();
//! let events = normalize_all([
//! Event::text_message_chunk(Some(MessageId::new("msg-1")), Some("Done.".into())),
//! Event::text_message_chunk(None, None).with_metadata(finish.clone()),
//! ])?;
//!
//! let Event::TextMessageContent(last) = &events[2] else { panic!("{events:?}") };
//! assert_eq!(last.delta, "");
//! assert_eq!(last.base.metadata, Some(finish));
//! # Ok::<(), ag_ui::client::Error>(())
//! ```
//!
//! # The two spellings do not mix
//!
//! An item opened by a chunk is continued and closed in chunk form, and one
//! opened by a `*_START` event explicitly. An explicit event that names the id
//! a chunk stream is assembling is in that stream's lane like any other, so it
//! ends the stream: the synthesized end comes out first, then the event,
//! which [`crate::client::verify`] judges by the rules of the explicit form.
//! The other way round, an explicitly opened item is not a stream a chunk can
//! continue: a chunk that names no id is rejected unless a *chunk* opened
//! something for it to continue, and one that names the open item's id opens
//! it again.
//!
//! ```
//! use ag_ui::client::{normalize_all, verify_all};
//! use ag_ui::{Event, EventType, MessageId};
//!
//! let events = normalize_all([
//! Event::run_started("thread-1", "run-1"),
//! Event::text_message_chunk(Some(MessageId::new("msg-1")), Some("Hel".into())),
//! Event::text_message_end("msg-1"),
//! ])?;
//! let types: Vec<EventType> = events.iter().map(Event::event_type).collect();
//! // The chunk stream ended when the explicit event arrived ...
//! assert_eq!(types[3..], [EventType::TextMessageEnd, EventType::TextMessageEnd]);
//! // ... so that event closes a message that is no longer open.
//! assert!(verify_all(&events).is_err());
//! # Ok::<(), ag_ui::client::Error>(())
//! ```
//!
//! # Subagents
//!
//! "The previous chunk" is only meaningful *per subagent* once several stream
//! at once, so the shorthand resolves within the sending subagent's own
//! stream: one stream may be open per owner, and a chunk that names no id
//! continues the stream of the subagent it is attributed to. A chunk that
//! carries neither an id nor a `subagentRunId` continues the parent's open
//! stream when there is one, and otherwise the sole open stream; when several
//! subagents' streams could all claim it there is nothing to resolve it
//! against, and it is rejected rather than guessed at. When streaming
//! concurrently, attribute every chunk — or repeat the id.
use crateEvent;
use crateStreams;
use crate;
/// Expands chunk events into the explicit events the rest of the protocol is
/// written in.
///
/// Feed every event of a run through it, in order, and apply what comes out.
/// Events that are not chunks pass through untouched, after the end of
/// whatever chunk stream they close.
/// Normalizes a whole run in one call, closing anything left open at the end.
///
/// The streaming form is [`ChunkNormalizer`]; this is the convenience for
/// tests, recorded streams, and anything else that has all the events already.