Skip to main content

ag_ui/
message.rs

1//! The message union and its multimodal content parts.
2
3use serde::{Deserialize, Serialize};
4use serde_json::Value;
5
6use crate::JsonObject;
7use crate::ids::{MessageId, SubagentRunId, ToolCallId};
8use crate::tool::ToolCall;
9
10/// Every role the protocol defines.
11#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
12#[serde(rename_all = "lowercase")]
13#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
14#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
15pub enum Role {
16    /// Out-of-band instructions from the application developer.
17    Developer,
18    /// System prompt.
19    System,
20    /// Model output.
21    Assistant,
22    /// End-user input.
23    User,
24    /// The result of a tool call.
25    Tool,
26    /// A structured progress update rendered by the client.
27    Activity,
28    /// Model reasoning / chain-of-thought.
29    Reasoning,
30}
31
32impl Role {
33    /// The role string as it appears on the wire.
34    pub const fn as_str(&self) -> &'static str {
35        match self {
36            Self::Developer => "developer",
37            Self::System => "system",
38            Self::Assistant => "assistant",
39            Self::User => "user",
40            Self::Tool => "tool",
41            Self::Activity => "activity",
42            Self::Reasoning => "reasoning",
43        }
44    }
45}
46
47impl std::fmt::Display for Role {
48    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
49        f.write_str(self.as_str())
50    }
51}
52
53/// Where the bytes of a multimodal part live.
54#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
55#[serde(tag = "type", rename_all = "lowercase")]
56#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
57#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
58pub enum InputContentSource {
59    /// Inline data, typically base64.
60    Data {
61        /// The encoded payload.
62        value: String,
63        /// MIME type of the payload, for example `image/png`.
64        #[serde(rename = "mimeType")]
65        mime_type: String,
66    },
67    /// A URL the consumer fetches itself.
68    Url {
69        /// The URL.
70        value: String,
71        /// MIME type, when the producer knows it.
72        #[serde(
73            rename = "mimeType",
74            default,
75            deserialize_with = "crate::serde_util::reject_null",
76            skip_serializing_if = "Option::is_none"
77        )]
78        mime_type: Option<String>,
79    },
80    /// An opaque provider-issued file handle, not a URL to fetch.
81    File {
82        /// The handle exactly as the provider issued it.
83        value: String,
84        /// Issuing provider, when known.
85        #[serde(
86            default,
87            deserialize_with = "crate::serde_util::reject_null",
88            skip_serializing_if = "Option::is_none"
89        )]
90        provider: Option<String>,
91        /// MIME type, when known.
92        #[serde(
93            rename = "mimeType",
94            default,
95            deserialize_with = "crate::serde_util::reject_null",
96            skip_serializing_if = "Option::is_none"
97        )]
98        mime_type: Option<String>,
99    },
100}
101
102/// A plain-text content part.
103#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
104#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
105#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
106pub struct TextInputContent {
107    /// Optional identifier for this part within its message.
108    #[serde(
109        default,
110        deserialize_with = "crate::serde_util::reject_null",
111        skip_serializing_if = "Option::is_none"
112    )]
113    pub id: Option<String>,
114    /// The text.
115    pub text: String,
116    /// Producer-defined information about this part.
117    #[serde(
118        default,
119        deserialize_with = "crate::serde_util::reject_null",
120        skip_serializing_if = "crate::serde_util::is_none_or_null"
121    )]
122    pub metadata: Option<Value>,
123}
124
125/// An image, audio, video or document content part.
126///
127/// The four modalities share a shape, so they share a struct; which one it is
128/// is carried by the [`InputContent`] variant.
129#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
130#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
131#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
132pub struct MediaInputContent {
133    /// Optional identifier for this part within its message.
134    #[serde(
135        default,
136        deserialize_with = "crate::serde_util::reject_null",
137        skip_serializing_if = "Option::is_none"
138    )]
139    pub id: Option<String>,
140    /// Where the bytes are.
141    pub source: InputContentSource,
142    /// Producer-defined extras (dimensions, page counts, alt text, …).
143    #[serde(
144        default,
145        deserialize_with = "crate::serde_util::reject_null",
146        skip_serializing_if = "crate::serde_util::is_none_or_null"
147    )]
148    pub metadata: Option<Value>,
149}
150
151impl MediaInputContent {
152    /// Builds a media part from a source, with no metadata.
153    pub fn new(source: InputContentSource) -> Self {
154        Self {
155            id: None,
156            source,
157            metadata: None,
158        }
159    }
160}
161
162/// The legacy `binary` content part.
163///
164/// Superseded by the modality-specific parts, but still accepted: at least one
165/// of `id`, `url` or `data` must be set. That constraint is a runtime rule in
166/// the upstream schema and is not encoded in this type — see
167/// [`BinaryInputContent::has_payload`].
168#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
169#[serde(rename_all = "camelCase")]
170#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
171#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
172pub struct BinaryInputContent {
173    /// MIME type of the payload.
174    pub mime_type: String,
175    /// Reference to a previously uploaded blob.
176    #[serde(default, skip_serializing_if = "Option::is_none")]
177    pub id: Option<String>,
178    /// URL to fetch the payload from.
179    #[serde(default, skip_serializing_if = "Option::is_none")]
180    pub url: Option<String>,
181    /// Inline payload, typically base64.
182    #[serde(default, skip_serializing_if = "Option::is_none")]
183    pub data: Option<String>,
184    /// Original file name, for display.
185    #[serde(default, skip_serializing_if = "Option::is_none")]
186    pub filename: Option<String>,
187}
188
189impl BinaryInputContent {
190    /// Whether the part carries a payload in any of the three accepted forms.
191    pub fn has_payload(&self) -> bool {
192        self.id.is_some() || self.url.is_some() || self.data.is_some()
193    }
194}
195
196/// One part of a multimodal user message.
197#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
198#[serde(tag = "type", rename_all = "lowercase")]
199#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
200#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
201pub enum InputContent {
202    /// Text.
203    Text(TextInputContent),
204    /// An image.
205    Image(MediaInputContent),
206    /// An audio clip.
207    Audio(MediaInputContent),
208    /// A video clip.
209    Video(MediaInputContent),
210    /// A document, for example a PDF.
211    Document(MediaInputContent),
212    /// The legacy catch-all binary part.
213    Binary(BinaryInputContent),
214}
215
216impl InputContent {
217    /// Builds a text part.
218    pub fn text(text: impl Into<String>) -> Self {
219        Self::Text(TextInputContent {
220            text: text.into(),
221            ..Default::default()
222        })
223    }
224}
225
226/// The body of a user message: either a bare string or an ordered list of
227/// multimodal parts.
228#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
229#[serde(untagged)]
230#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
231#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
232pub enum UserContent {
233    /// Plain text.
234    Text(String),
235    /// Multimodal parts.
236    Parts(Vec<InputContent>),
237}
238
239impl UserContent {
240    /// The text, when the content is a plain string.
241    ///
242    /// `None` for multimodal content, even when every part of it happens to be
243    /// text: this borrows, and joining parts cannot. Reach for
244    /// [`UserContent::to_text`] when any text will do.
245    pub fn as_text(&self) -> Option<&str> {
246        match self {
247            Self::Text(text) => Some(text),
248            Self::Parts(_) => None,
249        }
250    }
251
252    /// Every text part, in order, joined with newlines.
253    ///
254    /// Non-text parts are dropped rather than described: an agent that does not
255    /// handle images wants the caption, not a placeholder it has to strip.
256    ///
257    /// ```
258    /// use ag_ui::{InputContent, InputContentSource, MediaInputContent, UserContent};
259    ///
260    /// let plain = UserContent::from("what is the weather?");
261    /// assert_eq!(plain.as_text(), Some("what is the weather?"));
262    /// assert_eq!(plain.to_text(), "what is the weather?");
263    ///
264    /// let image = MediaInputContent::new(InputContentSource::Url {
265    ///     value: "https://example.com/cat.png".into(),
266    ///     mime_type: None,
267    /// });
268    /// let mixed = UserContent::from(vec![
269    ///     InputContent::text("what is this?"),
270    ///     InputContent::Image(image),
271    ///     InputContent::text("be brief"),
272    /// ]);
273    /// assert_eq!(mixed.as_text(), None);
274    /// assert_eq!(mixed.to_text(), "what is this?\nbe brief");
275    /// ```
276    pub fn to_text(&self) -> String {
277        match self {
278            Self::Text(text) => text.clone(),
279            Self::Parts(parts) => parts
280                .iter()
281                .filter_map(|part| match part {
282                    InputContent::Text(part) => Some(part.text.as_str()),
283                    _ => None,
284                })
285                .collect::<Vec<_>>()
286                .join("\n"),
287        }
288    }
289}
290
291impl Default for UserContent {
292    fn default() -> Self {
293        Self::Text(String::new())
294    }
295}
296
297impl From<String> for UserContent {
298    fn from(value: String) -> Self {
299        Self::Text(value)
300    }
301}
302
303impl From<&str> for UserContent {
304    fn from(value: &str) -> Self {
305        Self::Text(value.to_owned())
306    }
307}
308
309impl From<Vec<InputContent>> for UserContent {
310    fn from(value: Vec<InputContent>) -> Self {
311        Self::Parts(value)
312    }
313}
314
315/// A tool result as plain text or an ordered list of text and media parts.
316#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
317#[serde(untagged)]
318#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
319#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
320pub enum ToolContent {
321    /// Plain text, including structured data serialized by the tool.
322    Text(String),
323    /// Multimodal parts in their original order.
324    Parts(Vec<InputContent>),
325}
326
327impl ToolContent {
328    /// Borrows the payload when it is plain text.
329    pub fn as_text(&self) -> Option<&str> {
330        match self {
331            Self::Text(text) => Some(text),
332            Self::Parts(_) => None,
333        }
334    }
335
336    /// Returns text portions, ignoring media parts.
337    pub fn to_text(&self) -> String {
338        match self {
339            Self::Text(text) => text.clone(),
340            Self::Parts(parts) => parts
341                .iter()
342                .filter_map(|part| match part {
343                    InputContent::Text(part) => Some(part.text.as_str()),
344                    _ => None,
345                })
346                .collect::<Vec<_>>()
347                .join("\n"),
348        }
349    }
350}
351
352impl Default for ToolContent {
353    fn default() -> Self {
354        Self::Text(String::new())
355    }
356}
357
358impl From<String> for ToolContent {
359    fn from(value: String) -> Self {
360        Self::Text(value)
361    }
362}
363
364impl From<&str> for ToolContent {
365    fn from(value: &str) -> Self {
366        Self::Text(value.to_owned())
367    }
368}
369
370impl From<Vec<InputContent>> for ToolContent {
371    fn from(value: Vec<InputContent>) -> Self {
372        Self::Parts(value)
373    }
374}
375
376/// Out-of-band instructions from the application developer.
377#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
378#[serde(rename_all = "camelCase")]
379#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
380#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
381pub struct DeveloperMessage {
382    /// Message id.
383    pub id: MessageId,
384    /// The instructions.
385    pub content: String,
386    /// Optional display name for the author.
387    #[serde(default, skip_serializing_if = "Option::is_none")]
388    pub name: Option<String>,
389    /// Opaque provider payload for zero-data-retention modes.
390    #[serde(default, skip_serializing_if = "Option::is_none")]
391    pub encrypted_value: Option<String>,
392    /// The subagent that produced this message; absent means the parent
393    /// agent. A JSON `null` is rejected — see [`crate::event::subagent`].
394    #[serde(
395        default,
396        deserialize_with = "crate::serde_util::reject_null",
397        skip_serializing_if = "Option::is_none"
398    )]
399    pub subagent_run_id: Option<SubagentRunId>,
400    /// Extra information, open by key. Absent or an object — a JSON `null`
401    /// is rejected. See [`crate::metadata`].
402    #[serde(
403        default,
404        deserialize_with = "crate::serde_util::reject_null",
405        skip_serializing_if = "Option::is_none"
406    )]
407    #[cfg_attr(
408        feature = "schemars",
409        schemars(with = "Option<std::collections::BTreeMap<String, serde_json::Value>>")
410    )]
411    #[cfg_attr(feature = "utoipa", schema(value_type = Option<Object>))]
412    pub metadata: Option<JsonObject>,
413}
414
415/// The system prompt.
416#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
417#[serde(rename_all = "camelCase")]
418#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
419#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
420pub struct SystemMessage {
421    /// Message id.
422    pub id: MessageId,
423    /// The prompt.
424    pub content: String,
425    /// Optional display name for the author.
426    #[serde(default, skip_serializing_if = "Option::is_none")]
427    pub name: Option<String>,
428    /// Opaque provider payload for zero-data-retention modes.
429    #[serde(default, skip_serializing_if = "Option::is_none")]
430    pub encrypted_value: Option<String>,
431    /// The subagent that produced this message; absent means the parent
432    /// agent. A JSON `null` is rejected — see [`crate::event::subagent`].
433    #[serde(
434        default,
435        deserialize_with = "crate::serde_util::reject_null",
436        skip_serializing_if = "Option::is_none"
437    )]
438    pub subagent_run_id: Option<SubagentRunId>,
439    /// Extra information, open by key. Absent or an object — a JSON `null`
440    /// is rejected. See [`crate::metadata`].
441    #[serde(
442        default,
443        deserialize_with = "crate::serde_util::reject_null",
444        skip_serializing_if = "Option::is_none"
445    )]
446    #[cfg_attr(
447        feature = "schemars",
448        schemars(with = "Option<std::collections::BTreeMap<String, serde_json::Value>>")
449    )]
450    #[cfg_attr(feature = "utoipa", schema(value_type = Option<Object>))]
451    pub metadata: Option<JsonObject>,
452}
453
454/// Model output, optionally requesting tool calls.
455#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
456#[serde(rename_all = "camelCase")]
457#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
458#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
459pub struct AssistantMessage {
460    /// Message id.
461    pub id: MessageId,
462    /// The reply text. Absent when the turn is tool calls only.
463    #[serde(default, skip_serializing_if = "Option::is_none")]
464    pub content: Option<String>,
465    /// Optional display name for the author.
466    #[serde(default, skip_serializing_if = "Option::is_none")]
467    pub name: Option<String>,
468    /// Opaque provider payload for zero-data-retention modes.
469    #[serde(default, skip_serializing_if = "Option::is_none")]
470    pub encrypted_value: Option<String>,
471    /// Tool calls the assistant wants executed.
472    #[serde(default, skip_serializing_if = "Option::is_none")]
473    pub tool_calls: Option<Vec<ToolCall>>,
474    /// The subagent that produced this message; absent means the parent
475    /// agent. A JSON `null` is rejected — see [`crate::event::subagent`].
476    #[serde(
477        default,
478        deserialize_with = "crate::serde_util::reject_null",
479        skip_serializing_if = "Option::is_none"
480    )]
481    pub subagent_run_id: Option<SubagentRunId>,
482    /// Extra information, open by key. Absent or an object — a JSON `null`
483    /// is rejected. See [`crate::metadata`].
484    #[serde(
485        default,
486        deserialize_with = "crate::serde_util::reject_null",
487        skip_serializing_if = "Option::is_none"
488    )]
489    #[cfg_attr(
490        feature = "schemars",
491        schemars(with = "Option<std::collections::BTreeMap<String, serde_json::Value>>")
492    )]
493    #[cfg_attr(feature = "utoipa", schema(value_type = Option<Object>))]
494    pub metadata: Option<JsonObject>,
495}
496
497/// End-user input, possibly multimodal.
498#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
499#[serde(rename_all = "camelCase")]
500#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
501#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
502pub struct UserMessage {
503    /// Message id.
504    pub id: MessageId,
505    /// Text or multimodal parts.
506    pub content: UserContent,
507    /// Optional display name for the author.
508    #[serde(default, skip_serializing_if = "Option::is_none")]
509    pub name: Option<String>,
510    /// Opaque provider payload for zero-data-retention modes.
511    #[serde(default, skip_serializing_if = "Option::is_none")]
512    pub encrypted_value: Option<String>,
513    /// The subagent that produced this message; absent means the parent
514    /// agent. A JSON `null` is rejected — see [`crate::event::subagent`].
515    #[serde(
516        default,
517        deserialize_with = "crate::serde_util::reject_null",
518        skip_serializing_if = "Option::is_none"
519    )]
520    pub subagent_run_id: Option<SubagentRunId>,
521    /// Extra information, open by key. Absent or an object — a JSON `null`
522    /// is rejected. See [`crate::metadata`].
523    #[serde(
524        default,
525        deserialize_with = "crate::serde_util::reject_null",
526        skip_serializing_if = "Option::is_none"
527    )]
528    #[cfg_attr(
529        feature = "schemars",
530        schemars(with = "Option<std::collections::BTreeMap<String, serde_json::Value>>")
531    )]
532    #[cfg_attr(feature = "utoipa", schema(value_type = Option<Object>))]
533    pub metadata: Option<JsonObject>,
534}
535
536/// The result of a tool call, fed back to the model.
537#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
538#[serde(rename_all = "camelCase")]
539#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
540#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
541pub struct ToolMessage {
542    /// Message id.
543    pub id: MessageId,
544    /// Plain text or ordered multimodal parts returned by the tool.
545    pub content: ToolContent,
546    /// The call this result answers.
547    pub tool_call_id: ToolCallId,
548    /// Set when the tool failed; `content` then holds whatever partial output
549    /// there was.
550    #[serde(default, skip_serializing_if = "Option::is_none")]
551    pub error: Option<String>,
552    /// Opaque provider payload for zero-data-retention modes.
553    #[serde(default, skip_serializing_if = "Option::is_none")]
554    pub encrypted_value: Option<String>,
555    /// The subagent that *executed* the call; absent means the parent agent.
556    /// Attributed independently of the call it answers — see
557    /// [`ToolCallResultEvent`](crate::event::ToolCallResultEvent). A JSON
558    /// `null` is rejected.
559    #[serde(
560        default,
561        deserialize_with = "crate::serde_util::reject_null",
562        skip_serializing_if = "Option::is_none"
563    )]
564    pub subagent_run_id: Option<SubagentRunId>,
565    /// Extra information, open by key. Absent or an object — a JSON `null`
566    /// is rejected. See [`crate::metadata`].
567    #[serde(
568        default,
569        deserialize_with = "crate::serde_util::reject_null",
570        skip_serializing_if = "Option::is_none"
571    )]
572    #[cfg_attr(
573        feature = "schemars",
574        schemars(with = "Option<std::collections::BTreeMap<String, serde_json::Value>>")
575    )]
576    #[cfg_attr(feature = "utoipa", schema(value_type = Option<Object>))]
577    pub metadata: Option<JsonObject>,
578}
579
580/// A structured progress update the client renders as it likes.
581#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
582#[serde(rename_all = "camelCase")]
583#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
584#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
585pub struct ActivityMessage {
586    /// Message id.
587    pub id: MessageId,
588    /// Client-defined activity discriminator, for example `"web_search"`.
589    pub activity_type: String,
590    /// The activity payload.
591    #[cfg_attr(
592        feature = "schemars",
593        schemars(with = "std::collections::BTreeMap<String, serde_json::Value>")
594    )]
595    #[cfg_attr(feature = "utoipa", schema(value_type = Object))]
596    pub content: JsonObject,
597    /// The subagent that produced this message; absent means the parent
598    /// agent. A JSON `null` is rejected — see [`crate::event::subagent`].
599    #[serde(
600        default,
601        deserialize_with = "crate::serde_util::reject_null",
602        skip_serializing_if = "Option::is_none"
603    )]
604    pub subagent_run_id: Option<SubagentRunId>,
605    /// Extra information, open by key. Absent or an object — a JSON `null`
606    /// is rejected. See [`crate::metadata`].
607    #[serde(
608        default,
609        deserialize_with = "crate::serde_util::reject_null",
610        skip_serializing_if = "Option::is_none"
611    )]
612    #[cfg_attr(
613        feature = "schemars",
614        schemars(with = "Option<std::collections::BTreeMap<String, serde_json::Value>>")
615    )]
616    #[cfg_attr(feature = "utoipa", schema(value_type = Option<Object>))]
617    pub metadata: Option<JsonObject>,
618}
619
620/// Model reasoning, shown separately from the reply.
621#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
622#[serde(rename_all = "camelCase")]
623#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
624#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
625pub struct ReasoningMessage {
626    /// Message id.
627    pub id: MessageId,
628    /// The reasoning text. Empty when the provider only returns an encrypted
629    /// blob.
630    pub content: String,
631    /// Opaque provider payload for zero-data-retention modes.
632    #[serde(default, skip_serializing_if = "Option::is_none")]
633    pub encrypted_value: Option<String>,
634    /// The subagent that produced this message; absent means the parent
635    /// agent. A JSON `null` is rejected — see [`crate::event::subagent`].
636    #[serde(
637        default,
638        deserialize_with = "crate::serde_util::reject_null",
639        skip_serializing_if = "Option::is_none"
640    )]
641    pub subagent_run_id: Option<SubagentRunId>,
642    /// Extra information, open by key. Absent or an object — a JSON `null`
643    /// is rejected. See [`crate::metadata`].
644    #[serde(
645        default,
646        deserialize_with = "crate::serde_util::reject_null",
647        skip_serializing_if = "Option::is_none"
648    )]
649    #[cfg_attr(
650        feature = "schemars",
651        schemars(with = "Option<std::collections::BTreeMap<String, serde_json::Value>>")
652    )]
653    #[cfg_attr(feature = "utoipa", schema(value_type = Option<Object>))]
654    pub metadata: Option<JsonObject>,
655}
656
657/// A message in a thread, discriminated by its `role`.
658#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
659#[serde(tag = "role", rename_all = "lowercase")]
660#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
661#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
662pub enum Message {
663    /// See [`DeveloperMessage`].
664    Developer(DeveloperMessage),
665    /// See [`SystemMessage`].
666    System(SystemMessage),
667    /// See [`AssistantMessage`].
668    Assistant(AssistantMessage),
669    /// See [`UserMessage`].
670    User(UserMessage),
671    /// See [`ToolMessage`].
672    Tool(ToolMessage),
673    /// See [`ActivityMessage`].
674    Activity(ActivityMessage),
675    /// See [`ReasoningMessage`].
676    Reasoning(ReasoningMessage),
677}
678
679impl Message {
680    /// Builds a user message carrying plain text.
681    pub fn user(id: impl Into<MessageId>, content: impl Into<UserContent>) -> Self {
682        Self::User(UserMessage {
683            id: id.into(),
684            content: content.into(),
685            ..Default::default()
686        })
687    }
688
689    /// Builds an assistant message carrying plain text.
690    pub fn assistant(id: impl Into<MessageId>, content: impl Into<String>) -> Self {
691        Self::Assistant(AssistantMessage {
692            id: id.into(),
693            content: Some(content.into()),
694            ..Default::default()
695        })
696    }
697
698    /// Builds a system message.
699    pub fn system(id: impl Into<MessageId>, content: impl Into<String>) -> Self {
700        Self::System(SystemMessage {
701            id: id.into(),
702            content: content.into(),
703            ..Default::default()
704        })
705    }
706
707    /// Builds a developer message.
708    pub fn developer(id: impl Into<MessageId>, content: impl Into<String>) -> Self {
709        Self::Developer(DeveloperMessage {
710            id: id.into(),
711            content: content.into(),
712            ..Default::default()
713        })
714    }
715
716    /// Builds a tool result message.
717    pub fn tool(
718        id: impl Into<MessageId>,
719        tool_call_id: impl Into<ToolCallId>,
720        content: impl Into<ToolContent>,
721    ) -> Self {
722        Self::Tool(ToolMessage {
723            id: id.into(),
724            content: content.into(),
725            tool_call_id: tool_call_id.into(),
726            ..Default::default()
727        })
728    }
729
730    /// The message id, whatever the role.
731    pub const fn id(&self) -> &MessageId {
732        match self {
733            Self::Developer(m) => &m.id,
734            Self::System(m) => &m.id,
735            Self::Assistant(m) => &m.id,
736            Self::User(m) => &m.id,
737            Self::Tool(m) => &m.id,
738            Self::Activity(m) => &m.id,
739            Self::Reasoning(m) => &m.id,
740        }
741    }
742
743    /// The role, whatever the variant.
744    pub const fn role(&self) -> Role {
745        match self {
746            Self::Developer(_) => Role::Developer,
747            Self::System(_) => Role::System,
748            Self::Assistant(_) => Role::Assistant,
749            Self::User(_) => Role::User,
750            Self::Tool(_) => Role::Tool,
751            Self::Activity(_) => Role::Activity,
752            Self::Reasoning(_) => Role::Reasoning,
753        }
754    }
755
756    /// The subagent that produced the message, whatever the role. `None`
757    /// means the parent agent. See [`crate::event::subagent`].
758    pub const fn subagent_run_id(&self) -> Option<&SubagentRunId> {
759        match self {
760            Self::Developer(m) => m.subagent_run_id.as_ref(),
761            Self::System(m) => m.subagent_run_id.as_ref(),
762            Self::Assistant(m) => m.subagent_run_id.as_ref(),
763            Self::User(m) => m.subagent_run_id.as_ref(),
764            Self::Tool(m) => m.subagent_run_id.as_ref(),
765            Self::Activity(m) => m.subagent_run_id.as_ref(),
766            Self::Reasoning(m) => m.subagent_run_id.as_ref(),
767        }
768    }
769
770    /// Sets or clears the subagent the message is attributed to.
771    pub fn set_subagent_run_id(&mut self, subagent_run_id: Option<SubagentRunId>) {
772        match self {
773            Self::Developer(m) => m.subagent_run_id = subagent_run_id,
774            Self::System(m) => m.subagent_run_id = subagent_run_id,
775            Self::Assistant(m) => m.subagent_run_id = subagent_run_id,
776            Self::User(m) => m.subagent_run_id = subagent_run_id,
777            Self::Tool(m) => m.subagent_run_id = subagent_run_id,
778            Self::Activity(m) => m.subagent_run_id = subagent_run_id,
779            Self::Reasoning(m) => m.subagent_run_id = subagent_run_id,
780        }
781    }
782
783    /// The message's metadata, whatever the role. See [`crate::metadata`].
784    pub const fn metadata(&self) -> Option<&JsonObject> {
785        match self {
786            Self::Developer(m) => m.metadata.as_ref(),
787            Self::System(m) => m.metadata.as_ref(),
788            Self::Assistant(m) => m.metadata.as_ref(),
789            Self::User(m) => m.metadata.as_ref(),
790            Self::Tool(m) => m.metadata.as_ref(),
791            Self::Activity(m) => m.metadata.as_ref(),
792            Self::Reasoning(m) => m.metadata.as_ref(),
793        }
794    }
795
796    /// The metadata slot, for a consumer merging an event's metadata into
797    /// the message it builds — see
798    /// [`merge_metadata_into`](crate::metadata::merge_metadata_into).
799    pub fn metadata_mut(&mut self) -> &mut Option<JsonObject> {
800        match self {
801            Self::Developer(m) => &mut m.metadata,
802            Self::System(m) => &mut m.metadata,
803            Self::Assistant(m) => &mut m.metadata,
804            Self::User(m) => &mut m.metadata,
805            Self::Tool(m) => &mut m.metadata,
806            Self::Activity(m) => &mut m.metadata,
807            Self::Reasoning(m) => &mut m.metadata,
808        }
809    }
810}
811
812macro_rules! message_from {
813    ($($ty:ident => $variant:ident),* $(,)?) => {
814        $(
815            impl From<$ty> for Message {
816                fn from(value: $ty) -> Self {
817                    Self::$variant(value)
818                }
819            }
820        )*
821    };
822}
823
824message_from! {
825    DeveloperMessage => Developer,
826    SystemMessage => System,
827    AssistantMessage => Assistant,
828    UserMessage => User,
829    ToolMessage => Tool,
830    ActivityMessage => Activity,
831    ReasoningMessage => Reasoning,
832}