Skip to main content

ag_ui/server/
verify.rs

1//! The ordering state machine.
2//!
3//! `TEXT_MESSAGE_CONTENT` without a preceding `TEXT_MESSAGE_START` is a bug
4//! that currently surfaces as a confused frontend, three network hops from
5//! where it was caused. Neither the TypeScript SDK (which verifies on the
6//! client) nor the .NET one (which does not verify) catches it on the server.
7//! This crate does, on by default.
8//!
9//! # What it rejects
10//!
11//! | Rule | Rejected |
12//! | --- | --- |
13//! | [`RunEnded`] | anything after `RUN_ERROR` except the `RUN_STARTED` of the next run; anything after `RUN_FINISHED` except that or one `RUN_ERROR` |
14//! | [`DuplicateRunStarted`] | a `RUN_STARTED` inside a run that has not ended |
15//! | [`DuplicateStart`] | opening a message, reasoning block, tool call, step or subagent whose id is already open — or a subagent id that already finished in this run |
16//! | [`NotOpen`] | content or a terminator for something that was never opened, including `SUBAGENT_FINISHED` / `SUBAGENT_ERROR` for a subagent that is not active |
17//! | [`UnknownId`] | `TOOL_CALL_RESULT` for a call id neither this run nor the history it continues introduced, or a `parentSubagentRunId` that was never started |
18//! | [`OutOfOrder`] | `TOOL_CALL_RESULT` before the call's `TOOL_CALL_END`; a first event that is neither `RUN_STARTED` nor `RUN_ERROR` |
19//! | [`OpenAtFinish`] | `RUN_FINISHED` while a message, reasoning block, tool call, step or subagent is open |
20//! | [`OwnerMismatch`] | a tagged continuation, terminator or re-open whose `subagentRunId` is not the one that opened the entity — a message, reasoning block, tool call, activity, or the entity a `REASONING_ENCRYPTED_VALUE` names; a tool call tagged with one subagent whose parent message belongs to another |
21//! | [`MalformedChunk`] | a `*_CHUNK` event that names no id with no chunk stream to continue, opens a tool call without naming the tool, or repeats `role`, `name`, `toolCallName` or `parentMessageId` with a value other than the one its stream was opened with |
22//! | [`InvalidOutcome`] | `RUN_FINISHED` with an empty interrupt list or repeated interrupt IDs |
23//!
24//! `RUN_ERROR` is exempt from [`OpenAtFinish`]: a run that blew up mid-message
25//! could not have closed it. When several things are open, the error names
26//! one, and the same stream always names the same one: a message before a
27//! tool call, before a reasoning message, a reasoning block, a step and a
28//! subagent, and of several of a kind the one that was opened first.
29//!
30//! # After the run ended
31//!
32//! AG-UI 1.0 lets two things follow a run that ended: one `RUN_ERROR` after
33//! `RUN_FINISHED`, a failure that surfaced after the run reported success,
34//! and a `RUN_STARTED` after either terminal event, which begins the next
35//! run on the same stream. A standalone `EventVerifier` accepts both, so a
36//! recorded stream that carries a late failure or several runs in sequence
37//! verifies. The next run starts with nothing open, and keeps who owns each
38//! id. A hosted run sends neither: its event sink refuses every emit after a
39//! terminal event, with [`RunEnded`], whether or not this verifier is
40//! compiled in. That is the sink's own rule about what it sends, not the
41//! protocol's about what a stream may carry.
42//!
43//! # Chunks
44//!
45//! A `*_CHUNK` event is judged as the events it stands for: the end of the
46//! chunk stream it closes, the start it implies, its content. So a chunk for
47//! an id that is explicitly open is a second start ([`DuplicateStart`]), and
48//! an explicit event for an id a chunk opened finds it closed ([`NotOpen`]),
49//! because the chunk stream ended when that event arrived. A hosted run's
50//! `RUN_FINISHED` closes whatever chunk stream is still open, as a consumer
51//! reading it does.
52//!
53//! # Subagents
54//!
55//! Every entity is opened *by someone* — a subagent, or the parent agent when
56//! the opener carries no `subagentRunId` — and the verifier remembers who.
57//! A later event that *names* a different owner is rejected; one that names
58//! none is accepted, because attribution is optional on every event and a
59//! bare continuation is what a pre-subagent producer sends — and it does not
60//! hand the entity to the parent either: the first writer stays the owner, as
61//! upstream records it. Steps are keyed by owner as well as name, so a
62//! subagent cannot close the parent's step, or a sibling's, and two agents may
63//! run a step of the same name at once. A `MESSAGES_SNAPSHOT` seeds ownership
64//! from the messages it carries and is authoritative; the `RUN_STARTED` input
65//! echo seeds it too, for ids not yet recorded — and in a hosted run so do the
66//! request's `messages`, before the first event, whether or not they are
67//! echoed; a `TOOL_CALL_RESULT` mints the tool message it names under its own
68//! attribution.
69//!
70//! What is deliberately *not* checked, because the protocol does not require
71//! it: that an attributing `subagentRunId` was announced by `SUBAGENT_STARTED`
72//! (attribution without lifecycle events is a supported mode), that a
73//! subagent's own messages are closed before its `SUBAGENT_FINISHED`, or that
74//! events stop after it — a `parentSubagentRunId` may even name a subagent
75//! that already finished, since a parent legitimately finishes before its
76//! child. What *is* required is that every started subagent is closed before
77//! `RUN_FINISHED`.
78//!
79//! [`RunEnded`]: crate::server::Rule::RunEnded
80//! [`DuplicateRunStarted`]: crate::server::Rule::DuplicateRunStarted
81//! [`DuplicateStart`]: crate::server::Rule::DuplicateStart
82//! [`NotOpen`]: crate::server::Rule::NotOpen
83//! [`UnknownId`]: crate::server::Rule::UnknownId
84//! [`OutOfOrder`]: crate::server::Rule::OutOfOrder
85//! [`OpenAtFinish`]: crate::server::Rule::OpenAtFinish
86//! [`OwnerMismatch`]: crate::server::Rule::OwnerMismatch
87//! [`MalformedChunk`]: crate::server::Rule::MalformedChunk
88//! [`InvalidOutcome`]: crate::server::Rule::InvalidOutcome
89//!
90//! # What it lets through
91//!
92//! The deprecated `THINKING_*` family is not tracked at all. State, activity,
93//! raw and custom events are unordered — though an activity delta, like any
94//! continuation, may not name an owner other than its activity's, and a
95//! state, custom or step event ends the chunk stream of whoever sent it.
96//!
97//! # Cost
98//!
99//! A handful of maps and one lookup per event. Turning the `verify` feature
100//! off replaces the whole state machine with a zero-sized type whose
101//! `observe` is an inlined `Ok(())`. In debug builds a rejection additionally
102//! carries a dump of everything still open, which is the expensive part and is
103//! why it is debug-only.
104//!
105//! # One set of rules
106//!
107//! The rules are not written here. They are the crate's shared ordering
108//! rules, the ones `client::verify` reads an incoming stream by; this module
109//! names the [`Rule`](crate::server::Rule) a rejection broke and words it for
110//! whoever emitted the event.
111
112#[cfg(feature = "verify")]
113pub(crate) use enabled::Verifier;
114
115/// Standalone protocol ordering and attribution checks, without an event queue.
116/// Disabling verification does not expose a permissive no-op version of this API.
117#[cfg(feature = "verify")]
118pub use enabled::Verifier as EventVerifier;
119
120#[cfg(not(feature = "verify"))]
121pub(crate) use disabled::Verifier;
122
123#[cfg(feature = "verify")]
124mod enabled {
125    use std::fmt::Write as _;
126
127    use crate::ordering::{Broke, Open, Ordering, Policy, Violation, describe};
128    use crate::{Event, Message};
129
130    use crate::server::error::{Rule, VerificationError};
131
132    /// Tracks what is open, and who opened it, so misordered events can be
133    /// named precisely.
134    #[derive(Debug, Clone)]
135    pub struct Verifier {
136        rules: Ordering,
137    }
138
139    impl Default for Verifier {
140        fn default() -> Self {
141            Self::new()
142        }
143    }
144
145    impl Verifier {
146        /// Creates the ordering state for one stream.
147        pub fn new() -> Self {
148            Self {
149                rules: Ordering::new(Policy::PRODUCER),
150            }
151        }
152
153        /// Learns the conversation the run continues — the request's
154        /// `messages` — before its first event. As history, like the
155        /// `RUN_STARTED` echo, which is optional: a resumed run answering a
156        /// call the interrupted run opened is answering a call the consumer
157        /// already holds, echo or not.
158        ///
159        /// A hosted run does this itself. A verifier used on its own needs
160        /// it when the run answers a tool call an earlier run made, or
161        /// continues a message a subagent owns: without the history that
162        /// result is one for a call that never started.
163        ///
164        /// ```
165        /// # use ag_ui::{AssistantMessage, Event, Message, ToolCall};
166        /// # use ag_ui::server::EventVerifier;
167        /// // The request's history: the previous run asked for a search.
168        /// let history = [Message::Assistant(AssistantMessage {
169        ///     id: "msg-1".into(),
170        ///     tool_calls: Some(vec![ToolCall::new("call-1", "search", "{}")]),
171        ///     ..Default::default()
172        /// })];
173        /// let answer = Event::tool_call_result("msg-2", "call-1", "3 results");
174        ///
175        /// let mut verifier = EventVerifier::new();
176        /// verifier.observe(&Event::run_started("thread-1", "run-2"))?;
177        /// assert!(verifier.observe(&answer).is_err());
178        ///
179        /// let mut verifier = EventVerifier::new();
180        /// verifier.seed(&history);
181        /// verifier.observe(&Event::run_started("thread-1", "run-2"))?;
182        /// verifier.observe(&answer)?;
183        /// # Ok::<(), ag_ui::server::VerificationError>(())
184        /// ```
185        pub fn seed(&mut self, history: &[Message]) {
186            self.rules.seed(history);
187        }
188
189        /// Observes the events a run has already sent, in order, so that the
190        /// checks carry on from where the run is.
191        ///
192        /// This is how a verifier is made for a run that continues somewhere
193        /// else: in another process, or after the one that was driving it
194        /// stopped. Replay what was sent, then [`observe`](Self::observe)
195        /// what is sent next. The continuation sends no `RUN_STARTED`: the
196        /// one that was sent is among the events replayed, and a second
197        /// inside the same run is rejected.
198        ///
199        /// [`seed`](Self::seed) the history first when the run has one. What
200        /// is replayed may also begin with the runs that came before on the
201        /// same stream: the checks then stand in the last run it starts.
202        ///
203        /// ```
204        /// # use ag_ui::{Event, TextMessageRole};
205        /// # use ag_ui::server::{EventVerifier, Rule};
206        /// // What the store holds of the run so far.
207        /// let sent = [
208        ///     Event::run_started("thread-1", "run-1"),
209        ///     Event::text_message_start("msg-1", TextMessageRole::Assistant),
210        ///     Event::text_message_content("msg-1", "Hello"),
211        /// ];
212        ///
213        /// let mut verifier = EventVerifier::new();
214        /// verifier.replay(&sent)?;
215        ///
216        /// // The run is where it was left: started, with `msg-1` open.
217        /// let again = verifier.observe(&Event::run_started("thread-1", "run-1"));
218        /// assert_eq!(again.unwrap_err().rule, Rule::DuplicateRunStarted);
219        /// let early = verifier.observe(&Event::run_finished_success("thread-1", "run-1"));
220        /// assert_eq!(early.unwrap_err().rule, Rule::OpenAtFinish);
221        ///
222        /// verifier.observe(&Event::text_message_content("msg-1", " world"))?;
223        /// verifier.observe(&Event::text_message_end("msg-1"))?;
224        /// verifier.observe(&Event::run_finished_success("thread-1", "run-1"))?;
225        /// # Ok::<(), ag_ui::server::VerificationError>(())
226        /// ```
227        ///
228        /// # Cost
229        ///
230        /// One [`observe`](Self::observe) per event, and nothing is copied or
231        /// serialized. What the verifier keeps grows with the ids a run
232        /// introduces, not with the number of its events.
233        ///
234        /// # Errors
235        ///
236        /// The first event that breaks a rule, as `observe` reports it. The
237        /// events before it stay observed.
238        pub fn replay<'a>(
239            &mut self,
240            events: impl IntoIterator<Item = &'a Event>,
241        ) -> Result<(), VerificationError> {
242            events.into_iter().try_for_each(|event| self.observe(event))
243        }
244
245        /// Treats the stream as opened, for a sink the run driver is not
246        /// behind: `RunContext::new` emits no `RUN_STARTED`.
247        pub(crate) fn assume_opened(&mut self) {
248            self.rules.assume_opened();
249        }
250
251        /// Checks `event` against the state machine and folds it in.
252        pub fn observe(&mut self, event: &Event) -> Result<(), VerificationError> {
253            let observed = self.rules.observe(event);
254            observed.map_err(|violation| self.reject(&violation))
255        }
256
257        /// Names the rule a violation broke, appending the open-entity dump
258        /// in debug builds.
259        fn reject(&self, violation: &Violation) -> VerificationError {
260            let mut detail = detail(&violation.broke);
261            if cfg!(debug_assertions) {
262                detail.push_str(&self.dump());
263            }
264            VerificationError::new(violation.event, rule(&violation.broke), detail)
265        }
266
267        /// Debug-build-only dump of everything currently open.
268        fn dump(&self) -> String {
269            let open = self.rules.open();
270            let mut out = String::new();
271            let mut push = |label: &str, mut values: Vec<String>| {
272                if !values.is_empty() {
273                    values.sort();
274                    let _ = write!(out, " {label}={values:?}");
275                }
276            };
277            let strings = |ids: &[&str]| ids.iter().map(|id| (*id).to_owned()).collect();
278            push("messages", strings(&open.messages));
279            push("reasoning", strings(&open.reasoning_blocks));
280            push("reasoning_messages", strings(&open.reasoning_messages));
281            push("tool_calls", strings(&open.tool_calls));
282            push(
283                "steps",
284                open.steps
285                    .iter()
286                    .map(|(owner, name)| match owner {
287                        None => (*name).to_owned(),
288                        Some(id) => format!("{id}/{name}"),
289                    })
290                    .collect(),
291            );
292            push("subagents", strings(&open.subagents));
293            if out.is_empty() {
294                " [nothing open]".to_owned()
295            } else {
296                format!(" [open:{out}]")
297            }
298        }
299    }
300
301    /// The rule a violation is reported under.
302    fn rule(broke: &Broke) -> Rule {
303        match broke {
304            Broke::RunEnded => Rule::RunEnded,
305            Broke::RunStartedTwice => Rule::DuplicateRunStarted,
306            Broke::AlreadyOpen { .. }
307            | Broke::StepRunning { .. }
308            | Broke::SubagentActive { .. }
309            | Broke::SubagentReused { .. } => Rule::DuplicateStart,
310            Broke::NotOpen { .. }
311            | Broke::StepNotRunning { .. }
312            | Broke::SubagentNotActive { .. } => Rule::NotOpen,
313            Broke::UnknownToolCall { .. } | Broke::UnknownParentSubagent { .. } => Rule::UnknownId,
314            Broke::NotStarted | Broke::ResultBeforeEnd { .. } => Rule::OutOfOrder,
315            Broke::StillOpen(_) => Rule::OpenAtFinish,
316            Broke::OwnerMismatch { .. } | Broke::ParentMismatch { .. } => Rule::OwnerMismatch,
317            Broke::InvalidOutcome(_) => Rule::InvalidOutcome,
318            Broke::Chunk(_) => Rule::MalformedChunk,
319        }
320    }
321
322    /// What specifically was wrong, for whoever emitted the event.
323    fn detail(broke: &Broke) -> String {
324        match broke {
325            Broke::NotStarted => {
326                "the run has not started: RUN_STARTED or RUN_ERROR comes first".to_owned()
327            }
328            Broke::RunEnded => "the run already ended".to_owned(),
329            Broke::RunStartedTwice => "the run already started".to_owned(),
330            Broke::AlreadyOpen { entity, id } => {
331                format!("{} {id:?} is already open", entity.noun())
332            }
333            Broke::NotOpen { entity, id } => format!("{} {id:?} is not open", entity.noun()),
334            Broke::OwnerMismatch {
335                entity,
336                id,
337                owner,
338                named,
339                ..
340            } => format!(
341                "{} {id:?} belongs to {}, not {}",
342                entity.noun(),
343                describe(owner),
344                describe(named)
345            ),
346            Broke::ParentMismatch {
347                id,
348                named,
349                parent,
350                owner,
351            } => format!(
352                "tool call {id:?} is tagged {} but its parent message {parent:?} belongs to {}; \
353                 a tool call belongs to the message that carries it",
354                describe(named),
355                describe(owner)
356            ),
357            Broke::UnknownToolCall { id } => format!("tool call {id:?} was never started"),
358            Broke::ResultBeforeEnd { id } => format!("tool call {id:?} has no TOOL_CALL_END yet"),
359            Broke::StepRunning { name, owner } => {
360                format!("step {name:?} is already open under {}", describe(owner))
361            }
362            Broke::StepNotRunning { name, owner } => {
363                format!("step {name:?} is not open under {}", describe(owner))
364            }
365            Broke::SubagentActive { id } => format!("subagent {id:?} is already active"),
366            Broke::SubagentReused { id } => {
367                format!("subagent {id:?} already finished in this run; an id names one invocation")
368            }
369            Broke::UnknownParentSubagent { parent, .. } => {
370                format!("parent subagent {parent:?} was never started")
371            }
372            Broke::SubagentNotActive { id } => format!("subagent {id:?} is not active"),
373            Broke::StillOpen(Open::Entity { entity, id }) => {
374                format!("{} {id:?} is still open", entity.noun())
375            }
376            Broke::StillOpen(Open::Step { name, owner }) => {
377                format!("step {name:?} is still open under {}", describe(owner))
378            }
379            Broke::StillOpen(Open::Subagent { id }) => format!("subagent {id:?} is still active"),
380            Broke::InvalidOutcome(detail) => detail.clone(),
381            Broke::Chunk(error) => error.to_string(),
382        }
383    }
384}
385
386#[cfg(not(feature = "verify"))]
387mod disabled {
388    use crate::{Event, Message};
389
390    use crate::server::error::VerificationError;
391
392    /// The `verify` feature is off: every check compiles away.
393    #[derive(Clone, Debug, Default)]
394    pub(crate) struct Verifier;
395
396    impl Verifier {
397        #[inline]
398        pub(crate) fn new() -> Self {
399            Self
400        }
401
402        #[inline]
403        pub(crate) fn seed(&mut self, _history: &[Message]) {}
404
405        #[inline]
406        pub(crate) fn assume_opened(&mut self) {}
407
408        #[inline]
409        pub(crate) fn observe(&mut self, _event: &Event) -> Result<(), VerificationError> {
410            Ok(())
411        }
412    }
413}
414
415#[cfg(all(test, feature = "verify"))]
416mod tests {
417    use super::*;
418    use crate::{Event, TextMessageRole};
419
420    use crate::server::error::Rule;
421
422    fn verifier() -> Verifier {
423        let mut verifier = Verifier::new();
424        verifier
425            .observe(&Event::run_started("t", "r"))
426            .expect("RUN_STARTED must be accepted");
427        verifier
428    }
429
430    #[test]
431    fn a_well_formed_run_passes() {
432        let mut verifier = verifier();
433        for event in [
434            Event::step_started("plan"),
435            Event::text_message_start("m1", TextMessageRole::Assistant),
436            Event::text_message_content("m1", "hi"),
437            Event::text_message_end("m1"),
438            Event::tool_call_start("c1", "search"),
439            Event::tool_call_args("c1", "{}"),
440            Event::tool_call_end("c1"),
441            Event::tool_call_result("m2", "c1", "ok"),
442            Event::step_finished("plan"),
443            Event::run_finished_success("t", "r"),
444        ] {
445            verifier
446                .observe(&event)
447                .unwrap_or_else(|error| panic!("{event:?} should be accepted: {error}"));
448        }
449    }
450
451    #[test]
452    fn debug_builds_include_the_open_dump() {
453        let mut verifier = verifier();
454        verifier
455            .observe(&Event::text_message_start("m1", TextMessageRole::Assistant))
456            .expect("start");
457        let error = verifier
458            .observe(&Event::text_message_content("m2", "hi"))
459            .expect_err("m2 was never opened");
460        assert_eq!(error.rule, Rule::NotOpen);
461        assert!(
462            error.detail.contains("m1"),
463            "debug dump should name the open message: {}",
464            error.detail
465        );
466    }
467
468    #[test]
469    fn the_dump_names_open_subagents_and_owned_steps() {
470        let mut verifier = verifier();
471        verifier
472            .observe(&Event::subagent_started("s1", "researcher"))
473            .expect("start");
474        verifier
475            .observe(&Event::step_started("plan").with_subagent_run_id("s1"))
476            .expect("a subagent's step");
477        let error = verifier
478            .observe(&Event::run_finished_success("t", "r"))
479            .expect_err("the step and the subagent are open");
480        assert_eq!(error.rule, Rule::OpenAtFinish);
481        assert!(error.detail.contains("s1/plan"), "{}", error.detail);
482        assert!(error.detail.contains("subagents"), "{}", error.detail);
483    }
484}