Skip to main content

ag_ui/event/
mod.rs

1//! The AG-UI event stream.
2//!
3//! An agent run is a sequence of these events. [`Event`] is the closed union of
4//! all of them, tagged on the wire by a `type` field holding a
5//! SCREAMING_SNAKE_CASE name:
6//!
7//! ```
8//! # use ag_ui::{Event, EventType};
9//! let event = Event::text_message_content("msg-1", "Hello");
10//! assert_eq!(event.event_type(), EventType::TextMessageContent);
11//! assert_eq!(
12//!     serde_json::to_string(&event).unwrap(),
13//!     r#"{"type":"TEXT_MESSAGE_CONTENT","messageId":"msg-1","delta":"Hello"}"#
14//! );
15//! ```
16//!
17//! Every event also carries the optional [`BaseEvent`] fields — a timestamp,
18//! the provider event it was translated from, and [`metadata`](crate::metadata)
19//! — flattened into the same JSON object. Most events additionally accept an
20//! optional `subagentRunId` saying which subagent produced them; see
21//! [`subagent`].
22
23// The THINKING_* events are deprecated but still part of the protocol, so this
24// module has to name them constantly — in the union, in `event_type()`, in the
25// factories. Downstream users still get the warnings; we just do not warn at
26// ourselves for implementing the spec as written.
27#![allow(deprecated)]
28
29pub mod activity;
30pub mod factories;
31pub mod lifecycle;
32pub mod reasoning;
33pub mod special;
34pub mod state;
35pub mod subagent;
36pub mod text;
37pub mod tool;
38
39use std::fmt;
40use std::str::FromStr;
41
42use serde::{Deserialize, Serialize};
43use serde_json::Value;
44
45use crate::JsonObject;
46use crate::error::{Error, Result};
47use crate::ids::SubagentRunId;
48
49pub use activity::{ActivityDeltaEvent, ActivitySnapshotEvent};
50pub use lifecycle::{
51    RunErrorEvent, RunFinishedEvent, RunStartedEvent, StepFinishedEvent, StepStartedEvent,
52};
53pub use reasoning::{
54    ReasoningEncryptedValueEvent, ReasoningEncryptedValueSubtype, ReasoningEndEvent,
55    ReasoningMessageChunkEvent, ReasoningMessageContentEvent, ReasoningMessageEndEvent,
56    ReasoningMessageStartEvent, ReasoningRole, ReasoningStartEvent, ThinkingEndEvent,
57    ThinkingStartEvent, ThinkingTextMessageContentEvent, ThinkingTextMessageEndEvent,
58    ThinkingTextMessageStartEvent,
59};
60pub use special::{CustomEvent, RawEvent};
61pub use state::{MessagesSnapshotEvent, StateDeltaEvent, StateSnapshotEvent};
62pub use subagent::{
63    SubagentErrorEvent, SubagentFinishedEvent, SubagentOutcome, SubagentStartedEvent,
64};
65pub use text::{
66    TextMessageChunkEvent, TextMessageContentEvent, TextMessageEndEvent, TextMessageRole,
67    TextMessageStartEvent,
68};
69pub use tool::{
70    ToolCallArgsEvent, ToolCallChunkEvent, ToolCallEndEvent, ToolCallResultEvent,
71    ToolCallStartEvent, ToolResultRole,
72};
73
74/// The fields every event may carry, flattened into the event's own JSON
75/// object rather than nested under a key.
76#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
77#[serde(rename_all = "camelCase")]
78#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
79#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
80pub struct BaseEvent {
81    /// When the event was produced, in milliseconds since the Unix epoch.
82    #[serde(
83        default,
84        skip_serializing_if = "Option::is_none",
85        serialize_with = "crate::serde_util::serialize_timestamp"
86    )]
87    pub timestamp: Option<i64>,
88    /// The provider event this was translated from, for debugging.
89    #[serde(default, skip_serializing_if = "crate::serde_util::is_none_or_null")]
90    pub raw_event: Option<Value>,
91    /// Extra information, open by key. Absent or an object — a JSON `null` in
92    /// place of the object is rejected. See [`crate::metadata`] for the
93    /// reserved key and how consumers merge it into messages.
94    #[serde(
95        default,
96        deserialize_with = "crate::serde_util::reject_null",
97        skip_serializing_if = "Option::is_none"
98    )]
99    #[cfg_attr(
100        feature = "schemars",
101        schemars(with = "Option<std::collections::BTreeMap<String, serde_json::Value>>")
102    )]
103    #[cfg_attr(feature = "utoipa", schema(value_type = Option<Object>))]
104    pub metadata: Option<JsonObject>,
105}
106
107impl BaseEvent {
108    /// Whether every field is absent, in which case the base contributes
109    /// nothing to the serialized event.
110    pub const fn is_empty(&self) -> bool {
111        self.timestamp.is_none()
112            && matches!(self.raw_event.as_ref(), None | Some(Value::Null))
113            && self.metadata.is_none()
114    }
115}
116
117macro_rules! define_events {
118    ($(
119        $(#[$meta:meta])*
120        $variant:ident($payload:ty) => $tag:literal,
121    )*) => {
122        /// One event in an AG-UI stream.
123        ///
124        /// Serializes as the payload's fields plus a `type` discriminator, so
125        /// there is no nesting on the wire.
126        ///
127        /// # Exhaustive on purpose
128        ///
129        /// This enum is deliberately *not* `#[non_exhaustive]`, unlike every
130        /// error type in this workspace. A new protocol event **should** be a
131        /// compile error where you match on events: that is what a typed SDK
132        /// buys you over `serde_json::Value`, and the alternative — a `_` arm
133        /// in every consumer — is exactly how the previous Rust SDK came to be
134        /// missing eight event types without anyone noticing.
135        ///
136        /// The consequence is that adding an event is a major version of this
137        /// crate. New variants therefore require a compatibility-breaking release;
138        /// see `docs/DESIGN.md`, "`Event` is exhaustive on purpose".
139        #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
140        #[serde(tag = "type")]
141        #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
142        #[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
143        pub enum Event {
144            $(
145                $(#[$meta])*
146                #[serde(rename = $tag)]
147                $variant($payload),
148            )*
149        }
150
151        /// The `type` discriminator of an [`Event`], on its own.
152        ///
153        /// Useful for routing and filtering without matching the payload.
154        /// Exhaustive for the same reason [`Event`] is, and
155        /// [`EventType::ALL`] is the list, in upstream order.
156        #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
157        #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
158        #[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
159        pub enum EventType {
160            $(
161                $(#[$meta])*
162                #[serde(rename = $tag)]
163                $variant,
164            )*
165        }
166
167        impl EventType {
168            /// Every event type the protocol defines, in upstream order.
169            pub const ALL: &'static [EventType] = &[$(EventType::$variant),*];
170
171            /// The wire string for this type.
172            pub const fn as_str(&self) -> &'static str {
173                match self {
174                    $(Self::$variant => $tag,)*
175                }
176            }
177        }
178
179        impl FromStr for EventType {
180            type Err = Error;
181
182            fn from_str(s: &str) -> Result<Self> {
183                match s {
184                    $($tag => Ok(Self::$variant),)*
185                    other => Err(Error::UnknownEventType(other.to_owned())),
186                }
187            }
188        }
189
190        impl Event {
191            /// The discriminator for this event.
192            pub const fn event_type(&self) -> EventType {
193                match self {
194                    $(Self::$variant(_) => EventType::$variant,)*
195                }
196            }
197
198            /// The timestamp and raw-event fields, whatever the variant.
199            pub const fn base(&self) -> &BaseEvent {
200                match self {
201                    $(Self::$variant(payload) => &payload.base,)*
202                }
203            }
204
205            /// Mutable access to the timestamp and raw-event fields.
206            pub const fn base_mut(&mut self) -> &mut BaseEvent {
207                match self {
208                    $(Self::$variant(payload) => &mut payload.base,)*
209                }
210            }
211        }
212
213        $(
214            impl From<$payload> for Event {
215                fn from(payload: $payload) -> Self {
216                    Self::$variant(payload)
217                }
218            }
219        )*
220    };
221}
222
223define_events! {
224    /// Opens a text message. See [`TextMessageStartEvent`].
225    TextMessageStart(TextMessageStartEvent) => "TEXT_MESSAGE_START",
226    /// Appends to a text message. See [`TextMessageContentEvent`].
227    TextMessageContent(TextMessageContentEvent) => "TEXT_MESSAGE_CONTENT",
228    /// Closes a text message. See [`TextMessageEndEvent`].
229    TextMessageEnd(TextMessageEndEvent) => "TEXT_MESSAGE_END",
230    /// A whole text update in one event. See [`TextMessageChunkEvent`].
231    TextMessageChunk(TextMessageChunkEvent) => "TEXT_MESSAGE_CHUNK",
232    /// Opens a tool call. See [`ToolCallStartEvent`].
233    ToolCallStart(ToolCallStartEvent) => "TOOL_CALL_START",
234    /// Appends tool-call arguments. See [`ToolCallArgsEvent`].
235    ToolCallArgs(ToolCallArgsEvent) => "TOOL_CALL_ARGS",
236    /// Closes a tool call. See [`ToolCallEndEvent`].
237    ToolCallEnd(ToolCallEndEvent) => "TOOL_CALL_END",
238    /// A whole tool call in one event. See [`ToolCallChunkEvent`].
239    ToolCallChunk(ToolCallChunkEvent) => "TOOL_CALL_CHUNK",
240    /// A tool call's result. See [`ToolCallResultEvent`].
241    ToolCallResult(ToolCallResultEvent) => "TOOL_CALL_RESULT",
242    /// Opens a thinking block. See [`ThinkingStartEvent`].
243    #[cfg_attr(not(feature = "utoipa"), deprecated(note = "use Event::ReasoningStart"))]
244    ThinkingStart(ThinkingStartEvent) => "THINKING_START",
245    /// Closes a thinking block. See [`ThinkingEndEvent`].
246    #[cfg_attr(not(feature = "utoipa"), deprecated(note = "use Event::ReasoningEnd"))]
247    ThinkingEnd(ThinkingEndEvent) => "THINKING_END",
248    /// Opens a thinking message. See [`ThinkingTextMessageStartEvent`].
249    #[cfg_attr(not(feature = "utoipa"), deprecated(note = "use Event::ReasoningMessageStart"))]
250    ThinkingTextMessageStart(ThinkingTextMessageStartEvent) => "THINKING_TEXT_MESSAGE_START",
251    /// Appends thinking text. See [`ThinkingTextMessageContentEvent`].
252    #[cfg_attr(not(feature = "utoipa"), deprecated(note = "use Event::ReasoningMessageContent"))]
253    ThinkingTextMessageContent(ThinkingTextMessageContentEvent) => "THINKING_TEXT_MESSAGE_CONTENT",
254    /// Closes a thinking message. See [`ThinkingTextMessageEndEvent`].
255    #[cfg_attr(not(feature = "utoipa"), deprecated(note = "use Event::ReasoningMessageEnd"))]
256    ThinkingTextMessageEnd(ThinkingTextMessageEndEvent) => "THINKING_TEXT_MESSAGE_END",
257    /// Replaces the shared state. See [`StateSnapshotEvent`].
258    StateSnapshot(StateSnapshotEvent) => "STATE_SNAPSHOT",
259    /// Patches the shared state. See [`StateDeltaEvent`].
260    StateDelta(StateDeltaEvent) => "STATE_DELTA",
261    /// Replaces the message history. See [`MessagesSnapshotEvent`].
262    MessagesSnapshot(MessagesSnapshotEvent) => "MESSAGES_SNAPSHOT",
263    /// Publishes an activity. See [`ActivitySnapshotEvent`].
264    ActivitySnapshot(ActivitySnapshotEvent) => "ACTIVITY_SNAPSHOT",
265    /// Patches an activity. See [`ActivityDeltaEvent`].
266    ActivityDelta(ActivityDeltaEvent) => "ACTIVITY_DELTA",
267    /// Forwards a provider event. See [`RawEvent`].
268    Raw(RawEvent) => "RAW",
269    /// An application-defined event. See [`CustomEvent`].
270    Custom(CustomEvent) => "CUSTOM",
271    /// Starts a run. See [`RunStartedEvent`].
272    RunStarted(RunStartedEvent) => "RUN_STARTED",
273    /// Finishes or pauses a run. See [`RunFinishedEvent`].
274    RunFinished(RunFinishedEvent) => "RUN_FINISHED",
275    /// Fails a run. See [`RunErrorEvent`].
276    RunError(RunErrorEvent) => "RUN_ERROR",
277    /// Starts a step. See [`StepStartedEvent`].
278    StepStarted(StepStartedEvent) => "STEP_STARTED",
279    /// Finishes a step. See [`StepFinishedEvent`].
280    StepFinished(StepFinishedEvent) => "STEP_FINISHED",
281    /// Opens a reasoning block. See [`ReasoningStartEvent`].
282    ReasoningStart(ReasoningStartEvent) => "REASONING_START",
283    /// Opens a reasoning message. See [`ReasoningMessageStartEvent`].
284    ReasoningMessageStart(ReasoningMessageStartEvent) => "REASONING_MESSAGE_START",
285    /// Appends reasoning text. See [`ReasoningMessageContentEvent`].
286    ReasoningMessageContent(ReasoningMessageContentEvent) => "REASONING_MESSAGE_CONTENT",
287    /// Closes a reasoning message. See [`ReasoningMessageEndEvent`].
288    ReasoningMessageEnd(ReasoningMessageEndEvent) => "REASONING_MESSAGE_END",
289    /// A whole reasoning update in one event. See [`ReasoningMessageChunkEvent`].
290    ReasoningMessageChunk(ReasoningMessageChunkEvent) => "REASONING_MESSAGE_CHUNK",
291    /// Closes a reasoning block. See [`ReasoningEndEvent`].
292    ReasoningEnd(ReasoningEndEvent) => "REASONING_END",
293    /// Carries an encrypted reasoning blob. See [`ReasoningEncryptedValueEvent`].
294    ReasoningEncryptedValue(ReasoningEncryptedValueEvent) => "REASONING_ENCRYPTED_VALUE",
295    /// Announces a subagent invocation. See [`SubagentStartedEvent`].
296    SubagentStarted(SubagentStartedEvent) => "SUBAGENT_STARTED",
297    /// Closes a subagent invocation. See [`SubagentFinishedEvent`].
298    SubagentFinished(SubagentFinishedEvent) => "SUBAGENT_FINISHED",
299    /// Fails a subagent invocation. See [`SubagentErrorEvent`].
300    SubagentError(SubagentErrorEvent) => "SUBAGENT_ERROR",
301}
302
303impl fmt::Display for EventType {
304    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
305        f.write_str(self.as_str())
306    }
307}
308
309impl Event {
310    /// Stamps the event with a millisecond Unix timestamp.
311    #[must_use]
312    pub fn with_timestamp(mut self, timestamp: i64) -> Self {
313        self.base_mut().timestamp = Some(timestamp);
314        self
315    }
316
317    /// Attaches the provider event this was translated from.
318    #[must_use]
319    pub fn with_raw_event(mut self, raw_event: impl Into<Value>) -> Self {
320        let raw_event = raw_event.into();
321        self.base_mut().raw_event = (!raw_event.is_null()).then_some(raw_event);
322        self
323    }
324
325    /// Attaches metadata, replacing any the event already carried. See
326    /// [`crate::metadata`].
327    #[must_use]
328    pub fn with_metadata(mut self, metadata: JsonObject) -> Self {
329        self.base_mut().metadata = Some(metadata);
330        self
331    }
332
333    /// The event's metadata, if it carries any.
334    pub const fn metadata(&self) -> Option<&JsonObject> {
335        self.base().metadata.as_ref()
336    }
337
338    /// Whether this event's type is deprecated in favour of a `REASONING_*`
339    /// one.
340    pub const fn is_deprecated(&self) -> bool {
341        matches!(
342            self.event_type(),
343            EventType::ThinkingStart
344                | EventType::ThinkingEnd
345                | EventType::ThinkingTextMessageStart
346                | EventType::ThinkingTextMessageContent
347                | EventType::ThinkingTextMessageEnd
348        )
349    }
350
351    // ---- subagent attribution ------------------------------------------
352
353    /// The subagent this event belongs to.
354    ///
355    /// `None` means the parent agent — or an event type that carries no
356    /// attribution at all; [`EventType::is_attributable`] tells the two
357    /// apart. For the three `SUBAGENT_*` lifecycle events this is the
358    /// subagent they announce, which is required rather than optional.
359    pub fn subagent_run_id(&self) -> Option<&SubagentRunId> {
360        match self {
361            Self::SubagentStarted(e) => Some(&e.subagent_run_id),
362            Self::SubagentFinished(e) => Some(&e.subagent_run_id),
363            Self::SubagentError(e) => Some(&e.subagent_run_id),
364            _ => self.attribution().and_then(Option::as_ref),
365        }
366    }
367
368    /// Attributes the event to `id`.
369    ///
370    /// Returns `false`, leaving the event untouched, for the nine event types
371    /// the protocol defines without the field: `RUN_*`, `MESSAGES_SNAPSHOT`
372    /// and the deprecated `THINKING_*` family. On a `SUBAGENT_*` event it sets
373    /// the subject.
374    pub fn set_subagent_run_id(&mut self, id: impl Into<SubagentRunId>) -> bool {
375        let id = id.into();
376        match self {
377            Self::SubagentStarted(e) => e.subagent_run_id = id,
378            Self::SubagentFinished(e) => e.subagent_run_id = id,
379            Self::SubagentError(e) => e.subagent_run_id = id,
380            _ => match self.attribution_mut() {
381                Some(slot) => *slot = Some(id),
382                None => return false,
383            },
384        }
385        true
386    }
387
388    /// Removes attribution from an attributable event and returns it.
389    ///
390    /// The `SUBAGENT_*` events carry their id as a required subject, so this
391    /// leaves them alone and returns `None`, as it does for the event types
392    /// that never carry the field.
393    pub fn clear_subagent_run_id(&mut self) -> Option<SubagentRunId> {
394        self.attribution_mut().and_then(Option::take)
395    }
396
397    /// Builder form of [`set_subagent_run_id`](Self::set_subagent_run_id); a
398    /// no-op on the event types that cannot carry attribution.
399    #[must_use]
400    pub fn with_subagent_run_id(mut self, id: impl Into<SubagentRunId>) -> Self {
401        self.set_subagent_run_id(id);
402        self
403    }
404}
405
406/// Which event types carry the optional `subagentRunId` tag, stated once.
407///
408/// Every variant is on one side or the other, and what this generates matches
409/// without a wildcard arm: a new variant has to be placed here before the
410/// crate compiles, which is the point.
411macro_rules! attribution {
412    (
413        tagged: [$($tagged:ident),* $(,)?],
414        untagged: [$($untagged:ident),* $(,)?] $(,)?
415    ) => {
416        impl Event {
417            /// The `subagentRunId` slot of the event types that carry
418            /// attribution.
419            fn attribution(&self) -> Option<&Option<SubagentRunId>> {
420                match self {
421                    $(Self::$tagged(e) => Some(&e.subagent_run_id),)*
422                    $(Self::$untagged(_))|* => None,
423                }
424            }
425
426            fn attribution_mut(&mut self) -> Option<&mut Option<SubagentRunId>> {
427                match self {
428                    $(Self::$tagged(e) => Some(&mut e.subagent_run_id),)*
429                    $(Self::$untagged(_))|* => None,
430                }
431            }
432        }
433
434        impl EventType {
435            /// Whether this event type carries the optional `subagentRunId`
436            /// attribution — 24 of the 36 do.
437            ///
438            /// The three `SUBAGENT_*` lifecycle events return `false`: they
439            /// carry the field as their required subject, not as a tag. The
440            /// run lifecycle, `MESSAGES_SNAPSHOT` (whose messages carry their
441            /// own) and the deprecated `THINKING_*` family have no such field.
442            pub const fn is_attributable(self) -> bool {
443                match self {
444                    $(Self::$tagged)|* => true,
445                    $(Self::$untagged)|* => false,
446                }
447            }
448        }
449    };
450}
451
452attribution! {
453    tagged: [
454        TextMessageStart,
455        TextMessageContent,
456        TextMessageEnd,
457        TextMessageChunk,
458        ToolCallStart,
459        ToolCallArgs,
460        ToolCallEnd,
461        ToolCallChunk,
462        ToolCallResult,
463        StateSnapshot,
464        StateDelta,
465        ActivitySnapshot,
466        ActivityDelta,
467        Raw,
468        Custom,
469        StepStarted,
470        StepFinished,
471        ReasoningStart,
472        ReasoningMessageStart,
473        ReasoningMessageContent,
474        ReasoningMessageEnd,
475        ReasoningMessageChunk,
476        ReasoningEnd,
477        ReasoningEncryptedValue,
478    ],
479    untagged: [
480        RunStarted,
481        RunFinished,
482        RunError,
483        MessagesSnapshot,
484        ThinkingStart,
485        ThinkingEnd,
486        ThinkingTextMessageStart,
487        ThinkingTextMessageContent,
488        ThinkingTextMessageEnd,
489        SubagentStarted,
490        SubagentFinished,
491        SubagentError,
492    ],
493}