Skip to main content

ag_ui/event/
text.rs

1//! Streaming assistant text: `TEXT_MESSAGE_*`.
2
3use serde::{Deserialize, Serialize};
4
5use crate::event::BaseEvent;
6use crate::ids::{MessageId, SubagentRunId};
7
8/// The roles a streamed text message may carry.
9///
10/// Every role except `tool` — a tool result is not streamed as text, it arrives
11/// whole in `TOOL_CALL_RESULT`.
12#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
13#[serde(rename_all = "lowercase")]
14#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
15#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
16pub enum TextMessageRole {
17    /// Out-of-band developer instructions.
18    Developer,
19    /// System prompt.
20    System,
21    /// Model output. The default when a producer omits the field.
22    #[default]
23    Assistant,
24    /// End-user input.
25    User,
26}
27
28impl TextMessageRole {
29    /// The role string as it appears on the wire.
30    pub const fn as_str(&self) -> &'static str {
31        match self {
32            Self::Developer => "developer",
33            Self::System => "system",
34            Self::Assistant => "assistant",
35            Self::User => "user",
36        }
37    }
38}
39
40/// Opens a text message. Every following `TEXT_MESSAGE_CONTENT` with the same
41/// `message_id` appends to it, until `TEXT_MESSAGE_END`.
42#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
43#[serde(rename_all = "camelCase")]
44#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
45#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
46pub struct TextMessageStartEvent {
47    /// Timestamp and raw provider event.
48    #[serde(flatten)]
49    pub base: BaseEvent,
50    /// Id of the message being opened.
51    pub message_id: MessageId,
52    /// Who is speaking. Defaults to `assistant` only when omitted.
53    /// An explicit JSON `null` is invalid, matching the upstream role schema.
54    #[serde(default)]
55    pub role: TextMessageRole,
56    /// Display name for the author.
57    #[serde(default, skip_serializing_if = "Option::is_none")]
58    pub name: Option<String>,
59    /// The subagent that produced this event; absent means the parent agent.
60    /// A JSON `null` is rejected — see [`crate::event::subagent`].
61    #[serde(
62        default,
63        deserialize_with = "crate::serde_util::reject_null",
64        skip_serializing_if = "Option::is_none"
65    )]
66    pub subagent_run_id: Option<SubagentRunId>,
67}
68
69impl TextMessageStartEvent {
70    /// Opens a message with the given id and role.
71    pub fn new(message_id: impl Into<MessageId>, role: TextMessageRole) -> Self {
72        Self {
73            base: BaseEvent::default(),
74            message_id: message_id.into(),
75            role,
76            name: None,
77            subagent_run_id: None,
78        }
79    }
80}
81
82/// Appends a chunk of text to an open message.
83#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
84#[serde(rename_all = "camelCase")]
85#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
86#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
87pub struct TextMessageContentEvent {
88    /// Timestamp and raw provider event.
89    #[serde(flatten)]
90    pub base: BaseEvent,
91    /// The message being appended to.
92    pub message_id: MessageId,
93    /// The text to append.
94    pub delta: String,
95    /// The subagent that produced this event; absent means the parent agent.
96    /// A JSON `null` is rejected — see [`crate::event::subagent`].
97    #[serde(
98        default,
99        deserialize_with = "crate::serde_util::reject_null",
100        skip_serializing_if = "Option::is_none"
101    )]
102    pub subagent_run_id: Option<SubagentRunId>,
103}
104
105impl TextMessageContentEvent {
106    /// Appends `delta` to the message.
107    pub fn new(message_id: impl Into<MessageId>, delta: impl Into<String>) -> Self {
108        Self {
109            base: BaseEvent::default(),
110            message_id: message_id.into(),
111            delta: delta.into(),
112            subagent_run_id: None,
113        }
114    }
115}
116
117/// Closes a text message.
118#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
119#[serde(rename_all = "camelCase")]
120#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
121#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
122pub struct TextMessageEndEvent {
123    /// Timestamp and raw provider event.
124    #[serde(flatten)]
125    pub base: BaseEvent,
126    /// The message being closed.
127    pub message_id: MessageId,
128    /// The subagent that produced this event; absent means the parent agent.
129    /// A JSON `null` is rejected — see [`crate::event::subagent`].
130    #[serde(
131        default,
132        deserialize_with = "crate::serde_util::reject_null",
133        skip_serializing_if = "Option::is_none"
134    )]
135    pub subagent_run_id: Option<SubagentRunId>,
136}
137
138impl TextMessageEndEvent {
139    /// Closes the message.
140    pub fn new(message_id: impl Into<MessageId>) -> Self {
141        Self {
142            base: BaseEvent::default(),
143            message_id: message_id.into(),
144            subagent_run_id: None,
145        }
146    }
147}
148
149/// A self-contained text update: start, content and end folded into one event.
150///
151/// Producers that cannot bracket a message use this; consumers expand a run of
152/// chunks sharing a `message_id` into the equivalent start/content/end triple.
153#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
154#[serde(rename_all = "camelCase")]
155#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
156#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
157pub struct TextMessageChunkEvent {
158    /// Timestamp and raw provider event.
159    #[serde(flatten)]
160    pub base: BaseEvent,
161    /// The message this chunk belongs to.
162    #[serde(default, skip_serializing_if = "Option::is_none")]
163    pub message_id: Option<MessageId>,
164    /// Who is speaking.
165    #[serde(default, skip_serializing_if = "Option::is_none")]
166    pub role: Option<TextMessageRole>,
167    /// The text to append.
168    #[serde(default, skip_serializing_if = "Option::is_none")]
169    pub delta: Option<String>,
170    /// Display name for the author.
171    #[serde(default, skip_serializing_if = "Option::is_none")]
172    pub name: Option<String>,
173    /// The subagent that produced this event; absent means the parent agent.
174    /// A JSON `null` is rejected — see [`crate::event::subagent`]. Under
175    /// concurrency a chunk that omits its `message_id` is resolved within the
176    /// sending subagent's own stream, so attribute every chunk when several
177    /// subagents stream at once.
178    #[serde(
179        default,
180        deserialize_with = "crate::serde_util::reject_null",
181        skip_serializing_if = "Option::is_none"
182    )]
183    pub subagent_run_id: Option<SubagentRunId>,
184}
185
186impl TextMessageChunkEvent {
187    /// Builds a chunk carrying a message id and a text delta.
188    pub fn new(message_id: Option<MessageId>, delta: Option<String>) -> Self {
189        Self {
190            base: BaseEvent::default(),
191            message_id,
192            role: None,
193            delta,
194            name: None,
195            subagent_run_id: None,
196        }
197    }
198}