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, flattened into
18//! the same JSON object.
19
20// The THINKING_* events are deprecated but still part of the protocol, so this
21// module has to name them constantly — in the union, in `event_type()`, in the
22// factories. Downstream users still get the warnings; we just do not warn at
23// ourselves for implementing the spec as written.
24#![allow(deprecated)]
25
26pub mod activity;
27pub mod factories;
28pub mod lifecycle;
29pub mod reasoning;
30pub mod special;
31pub mod state;
32pub mod text;
33pub mod tool;
34
35use std::fmt;
36use std::str::FromStr;
37
38use serde::{Deserialize, Serialize};
39use serde_json::Value;
40
41use crate::error::{Error, Result};
42
43pub use activity::{ActivityDeltaEvent, ActivitySnapshotEvent};
44pub use lifecycle::{
45    RunErrorEvent, RunFinishedEvent, RunStartedEvent, StepFinishedEvent, StepStartedEvent,
46};
47pub use reasoning::{
48    ReasoningEncryptedValueEvent, ReasoningEncryptedValueSubtype, ReasoningEndEvent,
49    ReasoningMessageChunkEvent, ReasoningMessageContentEvent, ReasoningMessageEndEvent,
50    ReasoningMessageStartEvent, ReasoningRole, ReasoningStartEvent, ThinkingEndEvent,
51    ThinkingStartEvent, ThinkingTextMessageContentEvent, ThinkingTextMessageEndEvent,
52    ThinkingTextMessageStartEvent,
53};
54pub use special::{CustomEvent, RawEvent};
55pub use state::{MessagesSnapshotEvent, StateDeltaEvent, StateSnapshotEvent};
56pub use text::{
57    TextMessageChunkEvent, TextMessageContentEvent, TextMessageEndEvent, TextMessageRole,
58    TextMessageStartEvent,
59};
60pub use tool::{
61    ToolCallArgsEvent, ToolCallChunkEvent, ToolCallEndEvent, ToolCallResultEvent,
62    ToolCallStartEvent, ToolResultRole,
63};
64
65/// The fields every event may carry, flattened into the event's own JSON
66/// object rather than nested under a key.
67#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
68#[serde(rename_all = "camelCase")]
69#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
70#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
71pub struct BaseEvent {
72    /// When the event was produced, in milliseconds since the Unix epoch.
73    #[serde(default, skip_serializing_if = "Option::is_none")]
74    pub timestamp: Option<i64>,
75    /// The provider event this was translated from, for debugging.
76    #[serde(default, skip_serializing_if = "Option::is_none")]
77    pub raw_event: Option<Value>,
78}
79
80impl BaseEvent {
81    /// An empty base — no timestamp, no raw event.
82    pub fn new() -> Self {
83        Self::default()
84    }
85
86    /// Whether both fields are absent, in which case the base contributes
87    /// nothing to the serialized event.
88    pub const fn is_empty(&self) -> bool {
89        self.timestamp.is_none() && self.raw_event.is_none()
90    }
91}
92
93macro_rules! define_events {
94    ($(
95        $(#[$meta:meta])*
96        $variant:ident($payload:ty) => $tag:literal,
97    )*) => {
98        /// One event in an AG-UI stream.
99        ///
100        /// Serializes as the payload's fields plus a `type` discriminator, so
101        /// there is no nesting on the wire.
102        ///
103        /// # Exhaustive on purpose
104        ///
105        /// This enum is deliberately *not* `#[non_exhaustive]`, unlike every
106        /// error type in this workspace. A new protocol event **should** be a
107        /// compile error where you match on events: that is what a typed SDK
108        /// buys you over `serde_json::Value`, and the alternative — a `_` arm
109        /// in every consumer — is exactly how the previous Rust SDK came to be
110        /// missing eight event types without anyone noticing.
111        ///
112        /// The consequence is that adding an event is a major version of this
113        /// crate. That is the intended price; see `docs/DESIGN.md`.
114        #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
115        #[serde(tag = "type")]
116        #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
117        #[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
118        pub enum Event {
119            $(
120                $(#[$meta])*
121                #[serde(rename = $tag)]
122                $variant($payload),
123            )*
124        }
125
126        /// The `type` discriminator of an [`Event`], on its own.
127        ///
128        /// Useful for routing and filtering without matching the payload.
129        /// Exhaustive for the same reason [`Event`] is, and
130        /// [`EventType::ALL`] is the list, in upstream order.
131        #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
132        #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
133        #[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
134        pub enum EventType {
135            $(
136                $(#[$meta])*
137                #[serde(rename = $tag)]
138                $variant,
139            )*
140        }
141
142        impl EventType {
143            /// Every event type the protocol defines, in upstream order.
144            pub const ALL: &'static [EventType] = &[$(EventType::$variant),*];
145
146            /// The wire string for this type.
147            pub const fn as_str(&self) -> &'static str {
148                match self {
149                    $(Self::$variant => $tag,)*
150                }
151            }
152        }
153
154        impl FromStr for EventType {
155            type Err = Error;
156
157            fn from_str(s: &str) -> Result<Self> {
158                match s {
159                    $($tag => Ok(Self::$variant),)*
160                    other => Err(Error::UnknownEventType(other.to_owned())),
161                }
162            }
163        }
164
165        impl Event {
166            /// The discriminator for this event.
167            pub const fn event_type(&self) -> EventType {
168                match self {
169                    $(Self::$variant(_) => EventType::$variant,)*
170                }
171            }
172
173            /// The timestamp and raw-event fields, whatever the variant.
174            pub const fn base(&self) -> &BaseEvent {
175                match self {
176                    $(Self::$variant(payload) => &payload.base,)*
177                }
178            }
179
180            /// Mutable access to the timestamp and raw-event fields.
181            pub const fn base_mut(&mut self) -> &mut BaseEvent {
182                match self {
183                    $(Self::$variant(payload) => &mut payload.base,)*
184                }
185            }
186        }
187
188        $(
189            impl From<$payload> for Event {
190                fn from(payload: $payload) -> Self {
191                    Self::$variant(payload)
192                }
193            }
194        )*
195    };
196}
197
198define_events! {
199    /// Opens a text message. See [`TextMessageStartEvent`].
200    TextMessageStart(TextMessageStartEvent) => "TEXT_MESSAGE_START",
201    /// Appends to a text message. See [`TextMessageContentEvent`].
202    TextMessageContent(TextMessageContentEvent) => "TEXT_MESSAGE_CONTENT",
203    /// Closes a text message. See [`TextMessageEndEvent`].
204    TextMessageEnd(TextMessageEndEvent) => "TEXT_MESSAGE_END",
205    /// A whole text update in one event. See [`TextMessageChunkEvent`].
206    TextMessageChunk(TextMessageChunkEvent) => "TEXT_MESSAGE_CHUNK",
207    /// Opens a tool call. See [`ToolCallStartEvent`].
208    ToolCallStart(ToolCallStartEvent) => "TOOL_CALL_START",
209    /// Appends tool-call arguments. See [`ToolCallArgsEvent`].
210    ToolCallArgs(ToolCallArgsEvent) => "TOOL_CALL_ARGS",
211    /// Closes a tool call. See [`ToolCallEndEvent`].
212    ToolCallEnd(ToolCallEndEvent) => "TOOL_CALL_END",
213    /// A whole tool call in one event. See [`ToolCallChunkEvent`].
214    ToolCallChunk(ToolCallChunkEvent) => "TOOL_CALL_CHUNK",
215    /// A tool call's result. See [`ToolCallResultEvent`].
216    ToolCallResult(ToolCallResultEvent) => "TOOL_CALL_RESULT",
217    /// Opens a thinking block. See [`ThinkingStartEvent`].
218    #[cfg_attr(not(feature = "utoipa"), deprecated(note = "use Event::ReasoningStart"))]
219    ThinkingStart(ThinkingStartEvent) => "THINKING_START",
220    /// Closes a thinking block. See [`ThinkingEndEvent`].
221    #[cfg_attr(not(feature = "utoipa"), deprecated(note = "use Event::ReasoningEnd"))]
222    ThinkingEnd(ThinkingEndEvent) => "THINKING_END",
223    /// Opens a thinking message. See [`ThinkingTextMessageStartEvent`].
224    #[cfg_attr(not(feature = "utoipa"), deprecated(note = "use Event::ReasoningMessageStart"))]
225    ThinkingTextMessageStart(ThinkingTextMessageStartEvent) => "THINKING_TEXT_MESSAGE_START",
226    /// Appends thinking text. See [`ThinkingTextMessageContentEvent`].
227    #[cfg_attr(not(feature = "utoipa"), deprecated(note = "use Event::ReasoningMessageContent"))]
228    ThinkingTextMessageContent(ThinkingTextMessageContentEvent) => "THINKING_TEXT_MESSAGE_CONTENT",
229    /// Closes a thinking message. See [`ThinkingTextMessageEndEvent`].
230    #[cfg_attr(not(feature = "utoipa"), deprecated(note = "use Event::ReasoningMessageEnd"))]
231    ThinkingTextMessageEnd(ThinkingTextMessageEndEvent) => "THINKING_TEXT_MESSAGE_END",
232    /// Replaces the shared state. See [`StateSnapshotEvent`].
233    StateSnapshot(StateSnapshotEvent) => "STATE_SNAPSHOT",
234    /// Patches the shared state. See [`StateDeltaEvent`].
235    StateDelta(StateDeltaEvent) => "STATE_DELTA",
236    /// Replaces the message history. See [`MessagesSnapshotEvent`].
237    MessagesSnapshot(MessagesSnapshotEvent) => "MESSAGES_SNAPSHOT",
238    /// Publishes an activity. See [`ActivitySnapshotEvent`].
239    ActivitySnapshot(ActivitySnapshotEvent) => "ACTIVITY_SNAPSHOT",
240    /// Patches an activity. See [`ActivityDeltaEvent`].
241    ActivityDelta(ActivityDeltaEvent) => "ACTIVITY_DELTA",
242    /// Forwards a provider event. See [`RawEvent`].
243    Raw(RawEvent) => "RAW",
244    /// An application-defined event. See [`CustomEvent`].
245    Custom(CustomEvent) => "CUSTOM",
246    /// Starts a run. See [`RunStartedEvent`].
247    RunStarted(RunStartedEvent) => "RUN_STARTED",
248    /// Finishes or pauses a run. See [`RunFinishedEvent`].
249    RunFinished(RunFinishedEvent) => "RUN_FINISHED",
250    /// Fails a run. See [`RunErrorEvent`].
251    RunError(RunErrorEvent) => "RUN_ERROR",
252    /// Starts a step. See [`StepStartedEvent`].
253    StepStarted(StepStartedEvent) => "STEP_STARTED",
254    /// Finishes a step. See [`StepFinishedEvent`].
255    StepFinished(StepFinishedEvent) => "STEP_FINISHED",
256    /// Opens a reasoning block. See [`ReasoningStartEvent`].
257    ReasoningStart(ReasoningStartEvent) => "REASONING_START",
258    /// Opens a reasoning message. See [`ReasoningMessageStartEvent`].
259    ReasoningMessageStart(ReasoningMessageStartEvent) => "REASONING_MESSAGE_START",
260    /// Appends reasoning text. See [`ReasoningMessageContentEvent`].
261    ReasoningMessageContent(ReasoningMessageContentEvent) => "REASONING_MESSAGE_CONTENT",
262    /// Closes a reasoning message. See [`ReasoningMessageEndEvent`].
263    ReasoningMessageEnd(ReasoningMessageEndEvent) => "REASONING_MESSAGE_END",
264    /// A whole reasoning update in one event. See [`ReasoningMessageChunkEvent`].
265    ReasoningMessageChunk(ReasoningMessageChunkEvent) => "REASONING_MESSAGE_CHUNK",
266    /// Closes a reasoning block. See [`ReasoningEndEvent`].
267    ReasoningEnd(ReasoningEndEvent) => "REASONING_END",
268    /// Carries an encrypted reasoning blob. See [`ReasoningEncryptedValueEvent`].
269    ReasoningEncryptedValue(ReasoningEncryptedValueEvent) => "REASONING_ENCRYPTED_VALUE",
270}
271
272impl fmt::Display for EventType {
273    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
274        f.write_str(self.as_str())
275    }
276}
277
278impl Event {
279    /// Stamps the event with a millisecond Unix timestamp.
280    #[must_use]
281    pub fn with_timestamp(mut self, timestamp: i64) -> Self {
282        self.base_mut().timestamp = Some(timestamp);
283        self
284    }
285
286    /// Attaches the provider event this was translated from.
287    #[must_use]
288    pub fn with_raw_event(mut self, raw_event: impl Into<Value>) -> Self {
289        self.base_mut().raw_event = Some(raw_event.into());
290        self
291    }
292
293    /// Whether this event's type is deprecated in favour of a `REASONING_*`
294    /// one.
295    pub const fn is_deprecated(&self) -> bool {
296        matches!(
297            self.event_type(),
298            EventType::ThinkingStart
299                | EventType::ThinkingEnd
300                | EventType::ThinkingTextMessageStart
301                | EventType::ThinkingTextMessageContent
302                | EventType::ThinkingTextMessageEnd
303        )
304    }
305}