ag_ui/client/verify.rs
1//! Client-side protocol verification.
2//!
3//! The TypeScript SDK puts its verifier on the *client*, and that is the right
4//! instinct for a consumer: the events arrive from someone else's process, and
5//! a stream that breaks the rules should produce one clear error rather than a
6//! confused UI. This module is that check, as an ordering state machine.
7//!
8//! [`crate::client::Thread`] runs it by default. Turn it off with
9//! [`ThreadBuilder::verify`](crate::client::ThreadBuilder::verify) when talking to a
10//! producer whose quirks you have decided to live with.
11//!
12//! ```
13//! use ag_ui::client::verify::Verifier;
14//! use ag_ui::Event;
15//!
16//! let mut verifier = Verifier::new();
17//! verifier.verify(&Event::run_started("thread-1", "run-1"))?;
18//!
19//! // Content for a message that was never opened.
20//! let orphan = Event::text_message_content("msg-1", "Hello");
21//! assert!(verifier.verify(&orphan).is_err());
22//! # Ok::<(), ag_ui::client::Error>(())
23//! ```
24//!
25//! # The rules
26//!
27//! 1. `RUN_STARTED` opens the stream — or `RUN_ERROR` does, for a run that
28//! failed before it began. Nothing else may come first, `RAW` and `CUSTOM`
29//! included.
30//! 2. `RUN_FINISHED` and `RUN_ERROR` end the run. Two things may follow: one
31//! `RUN_ERROR` after `RUN_FINISHED`, a failure that surfaced after the run
32//! reported success, which fails the run; and after either, a
33//! `RUN_STARTED`, which begins the next run on the same stream. A
34//! `RUN_STARTED` inside a run that has not ended is rejected.
35//! 3. `TEXT_MESSAGE_CONTENT` and `TEXT_MESSAGE_END` require an open message
36//! with the same id, and `TEXT_MESSAGE_START` may not re-open an id that is
37//! already open.
38//! 4. The same, for `TOOL_CALL_*`, for `REASONING_MESSAGE_*`, and for the
39//! block `REASONING_START` and `REASONING_END` bracket. A block and the
40//! message inside it may share an id, so each has its own open set: content
41//! naming a block's id has no open message to land in.
42//! 5. `TOOL_CALL_RESULT` may not answer a call that has not ended.
43//! 6. `STEP_FINISHED` requires a matching `STEP_STARTED`, and step names do not
44//! nest with themselves.
45//! 7. Everything open must be closed before `RUN_FINISHED`.
46//! 8. An `interrupt` outcome must carry at least one interrupt — the one rule
47//! the type system cannot express, checked by
48//! [`RunOutcome::validate`](crate::outcome::RunOutcome::validate).
49//! 9. A continuation, terminator or re-open that *names* a subagent must name
50//! the one that opened the entity — a message, a reasoning block or the
51//! message inside it, a tool call, an activity, or whatever a
52//! `REASONING_ENCRYPTED_VALUE` attaches to. One that names none is
53//! accepted: attribution is optional per event, and a bare continuation is
54//! what a pre-subagent producer sends. It does not hand the entity to the
55//! parent either: the first writer stays the owner.
56//! 10. A tool call belongs to the message its `parentMessageId` names, so a
57//! `TOOL_CALL_START` tagged with one subagent while that message belongs
58//! to another is rejected; an untagged one inherits the message's owner.
59//! 11. Steps are scoped to the agent that opened them: a subagent cannot close
60//! the parent's step, or a sibling's, and the same name may be open under
61//! two owners at once.
62//! 12. `SUBAGENT_STARTED` names an invocation that is neither active nor
63//! already finished in this run, and a `parentSubagentRunId` that was
64//! started. `SUBAGENT_FINISHED` and `SUBAGENT_ERROR` name an active one.
65//! 13. Every started subagent is closed before `RUN_FINISHED` — not before
66//! `RUN_ERROR`, where an unclosed subagent is the expected shape.
67//!
68//! What is deliberately *not* a rule: that one stream must close before the
69//! next opens. Everything here is keyed by id, exactly as the TypeScript
70//! verifier keys its `activeMessages` / `activeToolCalls` maps. Two messages
71//! may stream at once, two tool calls may stream at once, and a tool call may
72//! open inside the message that narrates it — which is what every provider
73//! doing parallel tool calls actually sends. Nor must an attributing
74//! `subagentRunId` have been announced: attribution without lifecycle events
75//! is a supported mode. Events outside these families (state, activity, raw,
76//! custom) are unordered and close nothing that was opened explicitly. A
77//! `MESSAGES_SNAPSHOT`
78//! seeds ownership from the messages it carries and is authoritative; the
79//! `RUN_STARTED` input echo seeds it too, for ids not yet recorded; and a
80//! `TOOL_CALL_RESULT` mints the tool message it names under its own
81//! attribution.
82//!
83//! # Several runs
84//!
85//! AG-UI 1.0 lets one stream carry several runs in sequence: the run a
86//! request asked for, preceded by runs the producer replays. Every rule
87//! above that says "open" is about one run. A new run starts with nothing
88//! open, whatever a failed run left behind, and may announce again a
89//! subagent the run before it suspended. Who owns an id is about the stream:
90//! messages accumulate across runs, and a message keeps its first writer.
91//!
92//! ```
93//! use ag_ui::client::verify_all;
94//! use ag_ui::Event;
95//!
96//! verify_all(&[
97//! Event::run_started("thread-1", "run-1"),
98//! Event::run_error("the model provider went away"),
99//! Event::run_started("thread-1", "run-2"),
100//! Event::run_finished_success("thread-1", "run-2"),
101//! ])?;
102//! # Ok::<(), ag_ui::client::Error>(())
103//! ```
104//!
105//! # Chunks
106//!
107//! A `*_CHUNK` event is judged as the events it stands for.
108//! [`crate::client::chunks`] expands chunks before this stage, so a
109//! [`Thread`](crate::client::Thread) never shows it one; a verifier handed a
110//! raw stream expands each chunk itself, by the same model, and rejects one
111//! that cannot be expanded.
112//!
113//! # One set of rules
114//!
115//! The rules are not written here. They are the crate's shared ordering
116//! rules, the ones a hosted run checks what it emits by. This module words a
117//! rejection for whoever is reading the stream, and differs from the
118//! producer's reading in two places, both about what only one end knows:
119//!
120//! - [`Verifier::finish`] reports a stream that stopped before a terminal
121//! event. Only a reader can see that.
122//! - A `TOOL_CALL_RESULT` for a call this stream never introduced is
123//! accepted. A producer rejects one, since it knows every call it answers;
124//! a reader may hold less of the conversation than the producer does.
125
126use crate::ordering::{Broke, Claim, Entity, Open, Ordering, Policy, Violation, describe};
127use crate::{Event, EventType};
128
129use crate::client::error::{Error, Result};
130
131/// An ordering state machine for one event stream.
132///
133/// One verifier per stream: it is stateful, and its state is that stream's
134/// progress, through however many runs the stream carries.
135#[derive(Clone, Debug)]
136pub struct Verifier {
137 rules: Ordering,
138}
139
140impl Default for Verifier {
141 fn default() -> Self {
142 Self::new()
143 }
144}
145
146impl Verifier {
147 /// A verifier for a stream that has not started yet.
148 pub fn new() -> Self {
149 Self {
150 rules: Ordering::new(Policy::CONSUMER),
151 }
152 }
153
154 /// Checks one event against the rules, and records it.
155 ///
156 /// # Errors
157 ///
158 /// [`Error::Protocol`], naming the rule that was broken.
159 pub fn verify(&mut self, event: &Event) -> Result<()> {
160 let observed = self.rules.observe(event);
161 if observed.is_err() && matches!(event, Event::RunFinished(_)) {
162 // The run is over whether or not it ended tidily: the event
163 // arrived. Reporting the untidiness twice, once here and again
164 // from `finish`, helps nobody.
165 self.rules.end_run();
166 }
167 observed.map_err(|violation| Error::protocol(sentence(&violation)))
168 }
169
170 /// Checks the stream ended where it was supposed to.
171 ///
172 /// # Errors
173 ///
174 /// [`Error::Protocol`] when the transport ended the stream before the agent
175 /// finished the run it was in — a truncated response, which otherwise
176 /// looks exactly like a short answer.
177 pub fn finish(&self) -> Result<()> {
178 // A stream that opened with RUN_ERROR never started, and is complete.
179 if !self.rules.has_opened() {
180 return Err(Error::protocol("the stream ended before RUN_STARTED"));
181 }
182 if !self.rules.has_ended() {
183 return Err(Error::protocol(
184 "the stream ended before RUN_FINISHED or RUN_ERROR",
185 ));
186 }
187 Ok(())
188 }
189}
190
191/// A violation as one sentence, for whoever is reading the stream: the event
192/// that arrived, then what was wrong with it.
193fn sentence(violation: &Violation) -> String {
194 let event = violation.event;
195 match &violation.broke {
196 Broke::NotStarted => format!("{event} arrived before RUN_STARTED"),
197 Broke::RunEnded => format!("{event} arrived after the run had already finished"),
198 Broke::RunStartedTwice => format!("{event} arrived while a run was still active"),
199 Broke::AlreadyOpen { entity, id } => {
200 format!(
201 "{event} for {} {id:?}, which is already open",
202 entity.noun()
203 )
204 }
205 Broke::NotOpen { entity, id } => {
206 format!("{event} for {} {id:?}, which is not open", entity.noun())
207 }
208 Broke::OwnerMismatch {
209 entity,
210 id,
211 owner,
212 named,
213 claim,
214 } => {
215 let what = entity.noun();
216 let relation = match (claim, entity) {
217 (Claim::Continues, _) => format!("the {what} was opened by"),
218 (Claim::Opens, Entity::ToolCall) => "the call belongs to".to_owned(),
219 (Claim::Opens, _) => format!("the {what} belongs to"),
220 };
221 format!(
222 "{event} for {what} {id:?} names {}, but {relation} {}",
223 describe(named),
224 describe(owner)
225 )
226 }
227 Broke::ParentMismatch {
228 id,
229 named,
230 parent,
231 owner,
232 } => format!(
233 "{event} for tool call {id:?} names {}, but its parent message {parent:?} belongs to {}; \
234 a tool call belongs to the message that carries it",
235 describe(named),
236 describe(owner)
237 ),
238 Broke::UnknownToolCall { id } => {
239 format!("{event} for tool call {id:?}, which was never started")
240 }
241 Broke::ResultBeforeEnd { id } => {
242 format!("{event} for tool call {id:?}, which has not ended yet")
243 }
244 Broke::StepRunning { name, owner } => format!(
245 "{event} for {name:?}, which is already running under {}",
246 describe(owner)
247 ),
248 Broke::StepNotRunning { name, owner } => format!(
249 "{event} for {name:?}, which never started under {}",
250 describe(owner)
251 ),
252 Broke::SubagentActive { id } => {
253 format!("{event} for subagent {id:?}, which is already active")
254 }
255 Broke::SubagentReused { id } => format!(
256 "{event} for subagent {id:?}, which already finished in this run; \
257 an id names one invocation"
258 ),
259 Broke::UnknownParentSubagent { id, parent } => {
260 format!("{event} for subagent {id:?} names parent {parent:?}, which was never started")
261 }
262 Broke::SubagentNotActive { id } => {
263 format!("{event} for subagent {id:?}, which is not active")
264 }
265 Broke::StillOpen(Open::Entity { entity, id }) => format!(
266 "{event} arrived while {} {id:?} was still open",
267 entity.noun()
268 ),
269 Broke::StillOpen(Open::Step { name, owner }) => format!(
270 "{event} arrived while step {name:?} was still running under {}",
271 describe(owner)
272 ),
273 Broke::StillOpen(Open::Subagent { id }) => {
274 format!("{event} arrived while subagent {id:?} was still active")
275 }
276 Broke::InvalidOutcome(detail) => detail.clone(),
277 // Already a sentence that begins with the chunk it is about.
278 Broke::Chunk(error) => error.to_string(),
279 }
280}
281
282/// The rejection of a `RUN_STARTED` inside a run that has not ended, for a
283/// reader that pairs runs without a [`Verifier`].
284pub(crate) fn nested_run_started() -> Error {
285 Error::protocol(sentence(&Violation {
286 event: EventType::RunStarted,
287 broke: Broke::RunStartedTwice,
288 }))
289}
290
291/// Verifies a whole stream in one call: one run, or several in sequence.
292///
293/// The streaming form is [`Verifier`]; this is the convenience for recorded
294/// streams and tests.
295pub fn verify_all<'a>(events: impl IntoIterator<Item = &'a Event>) -> Result<()> {
296 let mut verifier = Verifier::new();
297 for event in events {
298 verifier.verify(event)?;
299 }
300 verifier.finish()
301}