ag-ui 0.1.0

An independent Rust SDK for the AG-UI protocol: protocol types and wire encoding, a server runtime for hosting an agent, and a client runtime for consuming one. Not affiliated with the AG-UI protocol organisation.
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
//! The ordering state machine.
//!
//! `TEXT_MESSAGE_CONTENT` without a preceding `TEXT_MESSAGE_START` is a bug
//! that currently surfaces as a confused frontend, three network hops from
//! where it was caused. Neither the TypeScript SDK (which verifies on the
//! client) nor the .NET one (which does not verify) catches it on the server.
//! This crate does, on by default.
//!
//! # What it rejects
//!
//! | Rule | Rejected |
//! | --- | --- |
//! | [`RunEnded`] | anything after `RUN_FINISHED` / `RUN_ERROR` |
//! | [`DuplicateRunStarted`] | a second `RUN_STARTED` |
//! | [`DuplicateStart`] | opening a message, reasoning block, tool call or step whose id is already open |
//! | [`NotOpen`] | content or a terminator for something that was never opened |
//! | [`UnknownId`] | `TOOL_CALL_RESULT` for a call id that was never introduced |
//! | [`OutOfOrder`] | `TOOL_CALL_RESULT` before the call's `TOOL_CALL_END` |
//! | [`OpenAtFinish`] | `RUN_FINISHED` while a message, reasoning block, tool call or step is open |
//!
//! `RUN_ERROR` is exempt from [`OpenAtFinish`]: a run that blew up mid-message
//! could not have closed it.
//!
//! [`RunEnded`]: crate::serve::Rule::RunEnded
//! [`DuplicateRunStarted`]: crate::serve::Rule::DuplicateRunStarted
//! [`DuplicateStart`]: crate::serve::Rule::DuplicateStart
//! [`NotOpen`]: crate::serve::Rule::NotOpen
//! [`UnknownId`]: crate::serve::Rule::UnknownId
//! [`OutOfOrder`]: crate::serve::Rule::OutOfOrder
//! [`OpenAtFinish`]: crate::serve::Rule::OpenAtFinish
//!
//! # What it lets through
//!
//! The `*_CHUNK` events are self-contained by design, so a chunk carrying a new
//! id registers that id rather than being rejected for having no start. The
//! deprecated `THINKING_*` family is not tracked at all. State, activity, raw
//! and custom events are unordered.
//!
//! # Cost
//!
//! A handful of `HashSet`s and one lookup per event. Turning the `verify`
//! feature off replaces the whole state machine with a zero-sized type whose
//! `observe` is an inlined `Ok(())`. In debug builds a rejection additionally
//! carries a dump of everything still open, which is the expensive part and is
//! why it is debug-only.

#[cfg(feature = "verify")]
pub(crate) use enabled::Verifier;

#[cfg(not(feature = "verify"))]
pub(crate) use disabled::Verifier;

#[cfg(feature = "verify")]
mod enabled {
    use std::collections::HashSet;
    use std::fmt::Write as _;

    use crate::{Event, MessageId, StepName, ToolCallId};

    use crate::serve::error::{Rule, VerificationError};

    /// Builds a rejection, appending the open-entity dump in debug builds.
    fn reject(
        event: &Event,
        rule: Rule,
        detail: impl Into<String>,
        open: impl FnOnce() -> String,
    ) -> VerificationError {
        let mut detail = detail.into();
        if cfg!(debug_assertions) {
            detail.push_str(&open());
        }
        VerificationError::new(event.event_type(), rule, detail)
    }

    /// Tracks what is open so misordered events can be named precisely.
    #[derive(Debug, Default)]
    pub(crate) struct Verifier {
        started: bool,
        ended: bool,
        messages: HashSet<MessageId>,
        reasoning: HashSet<MessageId>,
        reasoning_messages: HashSet<MessageId>,
        tool_calls: HashSet<ToolCallId>,
        known_tool_calls: HashSet<ToolCallId>,
        steps: HashSet<StepName>,
    }

    impl Verifier {
        pub(crate) fn new() -> Self {
            Self::default()
        }

        /// Checks `event` against the state machine and folds it in.
        pub(crate) fn observe(&mut self, event: &Event) -> Result<(), VerificationError> {
            if self.ended {
                return Err(self.fail(event, Rule::RunEnded, "the run already ended"));
            }

            match event {
                Event::RunStarted(_) => {
                    if self.started {
                        return Err(self.fail(
                            event,
                            Rule::DuplicateRunStarted,
                            "the run already started",
                        ));
                    }
                    self.started = true;
                }
                Event::RunFinished(_) => {
                    if let Some(detail) = self.first_open() {
                        return Err(self.fail(event, Rule::OpenAtFinish, detail));
                    }
                    self.ended = true;
                }
                Event::RunError(_) => self.ended = true,

                Event::TextMessageStart(payload) => {
                    self.open(event, Kind::Message, &payload.message_id)?;
                }
                Event::TextMessageContent(payload) => {
                    self.require(event, Kind::Message, &payload.message_id)?;
                }
                Event::TextMessageEnd(payload) => {
                    self.close(event, Kind::Message, &payload.message_id)?;
                }
                Event::TextMessageChunk(payload) => {
                    if let Some(id) = &payload.message_id {
                        // Self-contained: a chunk needs no bracketing events.
                        self.messages.remove(id);
                    }
                }

                Event::ReasoningStart(payload) => {
                    self.open(event, Kind::Reasoning, &payload.message_id)?;
                }
                Event::ReasoningEnd(payload) => {
                    self.close(event, Kind::Reasoning, &payload.message_id)?;
                }
                Event::ReasoningMessageStart(payload) => {
                    self.open(event, Kind::ReasoningMessage, &payload.message_id)?;
                }
                Event::ReasoningMessageContent(payload) => {
                    self.require(event, Kind::ReasoningMessage, &payload.message_id)?;
                }
                Event::ReasoningMessageEnd(payload) => {
                    self.close(event, Kind::ReasoningMessage, &payload.message_id)?;
                }
                Event::ReasoningMessageChunk(payload) => {
                    if let Some(id) = &payload.message_id {
                        self.reasoning_messages.remove(id);
                    }
                }

                Event::ToolCallStart(payload) => {
                    let id = &payload.tool_call_id;
                    if !self.tool_calls.insert(id.clone()) {
                        return Err(self.fail(
                            event,
                            Rule::DuplicateStart,
                            format!("tool call {id:?} is already open"),
                        ));
                    }
                    self.known_tool_calls.insert(id.clone());
                }
                Event::ToolCallArgs(payload) => {
                    let id = &payload.tool_call_id;
                    if !self.tool_calls.contains(id) {
                        return Err(self.fail(
                            event,
                            Rule::NotOpen,
                            format!("tool call {id:?} is not open"),
                        ));
                    }
                }
                Event::ToolCallEnd(payload) => {
                    let id = &payload.tool_call_id;
                    if !self.tool_calls.remove(id) {
                        return Err(self.fail(
                            event,
                            Rule::NotOpen,
                            format!("tool call {id:?} is not open"),
                        ));
                    }
                }
                Event::ToolCallChunk(payload) => {
                    if let Some(id) = &payload.tool_call_id {
                        self.tool_calls.remove(id);
                        self.known_tool_calls.insert(id.clone());
                    }
                }
                Event::ToolCallResult(payload) => {
                    let id = &payload.tool_call_id;
                    if !self.known_tool_calls.contains(id) {
                        return Err(self.fail(
                            event,
                            Rule::UnknownId,
                            format!("tool call {id:?} was never started"),
                        ));
                    }
                    if self.tool_calls.contains(id) {
                        return Err(self.fail(
                            event,
                            Rule::OutOfOrder,
                            format!("tool call {id:?} has no TOOL_CALL_END yet"),
                        ));
                    }
                }

                Event::StepStarted(payload) => {
                    let name = &payload.step_name;
                    if !self.steps.insert(name.clone()) {
                        return Err(self.fail(
                            event,
                            Rule::DuplicateStart,
                            format!("step {name:?} is already open"),
                        ));
                    }
                }
                Event::StepFinished(payload) => {
                    let name = &payload.step_name;
                    if !self.steps.remove(name) {
                        return Err(self.fail(
                            event,
                            Rule::NotOpen,
                            format!("step {name:?} is not open"),
                        ));
                    }
                }

                _ => {}
            }

            Ok(())
        }

        fn open(
            &mut self,
            event: &Event,
            kind: Kind,
            id: &MessageId,
        ) -> Result<(), VerificationError> {
            if !self.set_mut(kind).insert(id.clone()) {
                return Err(self.fail(
                    event,
                    Rule::DuplicateStart,
                    format!("{} {id:?} is already open", kind.noun()),
                ));
            }
            Ok(())
        }

        fn require(
            &mut self,
            event: &Event,
            kind: Kind,
            id: &MessageId,
        ) -> Result<(), VerificationError> {
            if !self.set_mut(kind).contains(id) {
                return Err(self.fail(
                    event,
                    Rule::NotOpen,
                    format!("{} {id:?} is not open", kind.noun()),
                ));
            }
            Ok(())
        }

        fn close(
            &mut self,
            event: &Event,
            kind: Kind,
            id: &MessageId,
        ) -> Result<(), VerificationError> {
            if !self.set_mut(kind).remove(id) {
                return Err(self.fail(
                    event,
                    Rule::NotOpen,
                    format!("{} {id:?} is not open", kind.noun()),
                ));
            }
            Ok(())
        }

        fn set_mut(&mut self, kind: Kind) -> &mut HashSet<MessageId> {
            match kind {
                Kind::Message => &mut self.messages,
                Kind::Reasoning => &mut self.reasoning,
                Kind::ReasoningMessage => &mut self.reasoning_messages,
            }
        }

        fn fail(&self, event: &Event, rule: Rule, detail: impl Into<String>) -> VerificationError {
            reject(event, rule, detail, || self.dump())
        }

        /// The first thing still open at `RUN_FINISHED`, if any.
        fn first_open(&self) -> Option<String> {
            if let Some(id) = self.messages.iter().next() {
                return Some(format!("message {id:?} is still open"));
            }
            if let Some(id) = self.reasoning_messages.iter().next() {
                return Some(format!("reasoning message {id:?} is still open"));
            }
            if let Some(id) = self.reasoning.iter().next() {
                return Some(format!("reasoning block {id:?} is still open"));
            }
            if let Some(id) = self.tool_calls.iter().next() {
                return Some(format!("tool call {id:?} is still open"));
            }
            if let Some(name) = self.steps.iter().next() {
                return Some(format!("step {name:?} is still open"));
            }
            None
        }

        /// Debug-build-only dump of everything currently open.
        fn dump(&self) -> String {
            let mut out = String::new();
            let mut push = |label: &str, values: Vec<String>| {
                if !values.is_empty() {
                    let _ = write!(out, " {label}={:?}", values);
                }
            };
            push("messages", strings(&self.messages));
            push("reasoning", strings(&self.reasoning));
            push("reasoning_messages", strings(&self.reasoning_messages));
            push("tool_calls", strings(&self.tool_calls));
            push("steps", strings(&self.steps));
            if out.is_empty() {
                " [nothing open]".to_owned()
            } else {
                format!(" [open:{out}]")
            }
        }
    }

    fn strings<T: ToString>(set: &HashSet<T>) -> Vec<String> {
        let mut values: Vec<String> = set.iter().map(ToString::to_string).collect();
        values.sort();
        values
    }

    /// The three id-keyed things a message id can open.
    #[derive(Clone, Copy, Debug)]
    enum Kind {
        Message,
        Reasoning,
        ReasoningMessage,
    }

    impl Kind {
        const fn noun(self) -> &'static str {
            match self {
                Self::Message => "message",
                Self::Reasoning => "reasoning block",
                Self::ReasoningMessage => "reasoning message",
            }
        }
    }
}

#[cfg(not(feature = "verify"))]
mod disabled {
    use crate::Event;

    use crate::serve::error::VerificationError;

    /// The `verify` feature is off: every check compiles away.
    #[derive(Debug, Default)]
    pub(crate) struct Verifier;

    impl Verifier {
        #[inline]
        pub(crate) fn new() -> Self {
            Self
        }

        #[inline]
        pub(crate) fn observe(&mut self, _event: &Event) -> Result<(), VerificationError> {
            Ok(())
        }
    }
}

#[cfg(all(test, feature = "verify"))]
mod tests {
    use super::*;
    use crate::{Event, TextMessageRole};

    use crate::serve::error::Rule;

    fn verifier() -> Verifier {
        let mut verifier = Verifier::new();
        verifier
            .observe(&Event::run_started("t", "r"))
            .expect("RUN_STARTED must be accepted");
        verifier
    }

    #[test]
    fn a_well_formed_run_passes() {
        let mut verifier = verifier();
        for event in [
            Event::step_started("plan"),
            Event::text_message_start("m1", TextMessageRole::Assistant),
            Event::text_message_content("m1", "hi"),
            Event::text_message_end("m1"),
            Event::tool_call_start("c1", "search"),
            Event::tool_call_args("c1", "{}"),
            Event::tool_call_end("c1"),
            Event::tool_call_result("m2", "c1", "ok"),
            Event::step_finished("plan"),
            Event::run_finished_success("t", "r"),
        ] {
            verifier
                .observe(&event)
                .unwrap_or_else(|error| panic!("{event:?} should be accepted: {error}"));
        }
    }

    #[test]
    fn debug_builds_include_the_open_dump() {
        let mut verifier = verifier();
        verifier
            .observe(&Event::text_message_start("m1", TextMessageRole::Assistant))
            .expect("start");
        let error = verifier
            .observe(&Event::text_message_content("m2", "hi"))
            .expect_err("m2 was never opened");
        assert_eq!(error.rule, Rule::NotOpen);
        assert!(
            error.detail.contains("m1"),
            "debug dump should name the open message: {}",
            error.detail
        );
    }
}