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    /// The 1.0 media part this legacy part stands for: its inline data, or
196    /// else its URL, under the modality its MIME type names, the file name
197    /// kept as `metadata.filename`. `None` when it carries only an `id`,
198    /// which no 1.0 source can express.
199    #[cfg(any(feature = "client", feature = "axum"))]
200    fn upgraded(&self) -> Option<InputContent> {
201        let mime_type = self.mime_type.clone();
202        let filled = |value: &Option<String>| value.clone().filter(|value| !value.is_empty());
203        let source = if let Some(value) = filled(&self.data) {
204            InputContentSource::Data { value, mime_type }
205        } else {
206            InputContentSource::Url {
207                value: filled(&self.url)?,
208                mime_type: Some(mime_type),
209            }
210        };
211        let media = MediaInputContent {
212            id: None,
213            source,
214            metadata: filled(&self.filename)
215                .map(|filename| serde_json::json!({ "filename": filename })),
216        };
217        let modality = self.mime_type.split_once('/').map(|(kind, _)| kind);
218        Some(match modality {
219            Some(kind) if kind.eq_ignore_ascii_case("image") => InputContent::Image(media),
220            Some(kind) if kind.eq_ignore_ascii_case("audio") => InputContent::Audio(media),
221            Some(kind) if kind.eq_ignore_ascii_case("video") => InputContent::Video(media),
222            _ => InputContent::Document(media),
223        })
224    }
225}
226
227/// Rewrites the legacy `binary` parts of a request's messages as the 1.0
228/// media parts they stand for. AG-UI 1.0 retired the shape: a consumer
229/// translates it rather than send what a 1.0 producer strips.
230///
231/// A legacy part that merely mirrors a media part already in the same message
232/// is dropped. An id-only part is left for schema enforcement to remove with a warning.
233#[cfg(feature = "client")]
234pub(crate) fn upgrade_legacy_content(messages: &mut [Message]) {
235    for message in messages {
236        let parts = match message {
237            Message::User(user) => match &mut user.content {
238                UserContent::Parts(parts) => parts,
239                UserContent::Text(_) => continue,
240            },
241            Message::Tool(tool) => match &mut tool.content {
242                ToolContent::Parts(parts) => parts,
243                ToolContent::Text(_) => continue,
244            },
245            _ => continue,
246        };
247        if !parts
248            .iter()
249            .any(|part| matches!(part, InputContent::Binary(_)))
250        {
251            continue;
252        }
253        let original = std::mem::take(parts);
254        for part in &original {
255            let InputContent::Binary(binary) = part else {
256                parts.push(part.clone());
257                continue;
258            };
259            match binary.upgraded() {
260                // Matched against the parts as they arrived, so two legacy
261                // parts with the same payload stay two.
262                Some(media) if original.iter().any(|other| mirrors(other, &media, binary)) => {}
263                Some(media) => parts.push(media),
264                None => parts.push(part.clone()),
265            }
266        }
267    }
268}
269
270/// The same translation on a wire event, before the boundary enforces the
271/// schema, which would drop the part as unrecognised: the content of the
272/// messages `MESSAGES_SNAPSHOT` and the `RUN_STARTED` input echo carry, and of
273/// a `TOOL_CALL_RESULT`. Each translation is a warning naming the part.
274#[cfg(feature = "client")]
275pub(crate) fn upgrade_legacy_event_content(
276    event: &mut Value,
277    tag: &str,
278    warnings: &mut Vec<String>,
279) {
280    let (messages, at) = match tag {
281        "TOOL_CALL_RESULT" => {
282            return upgrade_wire_parts(event.get_mut("content"), "/content", warnings);
283        }
284        "MESSAGES_SNAPSHOT" => (event.get_mut("messages"), "/messages"),
285        "RUN_STARTED" => (event.pointer_mut("/input/messages"), "/input/messages"),
286        _ => return,
287    };
288    upgrade_wire_messages(messages, at, warnings);
289}
290
291#[cfg(any(feature = "client", feature = "axum"))]
292pub(crate) fn upgrade_wire_messages(
293    messages: Option<&mut Value>,
294    at: &str,
295    warnings: &mut Vec<String>,
296) {
297    for (index, message) in messages
298        .and_then(Value::as_array_mut)
299        .into_iter()
300        .flatten()
301        .enumerate()
302    {
303        if matches!(
304            message.get("role").and_then(Value::as_str),
305            Some("user" | "tool")
306        ) && message.get("content").is_some_and(Value::is_array)
307        {
308            let at = format!("{at}/{index}/content");
309            upgrade_wire_parts(message.get_mut("content"), &at, warnings);
310        }
311    }
312}
313
314/// One content list on the wire. A part that is not a well-formed legacy
315/// part is left for enforcement to judge.
316#[cfg(any(feature = "client", feature = "axum"))]
317fn upgrade_wire_parts(content: Option<&mut Value>, at: &str, warnings: &mut Vec<String>) {
318    let Some(parts) = content.and_then(Value::as_array_mut) else {
319        return;
320    };
321    let legacy = |part: &Value| -> Option<BinaryInputContent> {
322        (part.get("type").and_then(Value::as_str) == Some("binary"))
323            .then(|| serde_json::from_value(part.clone()).ok())
324            .flatten()
325    };
326    if !parts.iter().any(|part| legacy(part).is_some()) {
327        return;
328    }
329    let original = std::mem::take(parts);
330    // What the list already holds in 1.0 form, for the mirror check.
331    let modern: Vec<InputContent> = original
332        .iter()
333        .filter(|part| legacy(part).is_none())
334        .filter_map(|part| serde_json::from_value(part.clone()).ok())
335        .collect();
336    for (index, part) in original.iter().enumerate() {
337        let translated = legacy(part).and_then(|binary| {
338            let media = binary.upgraded()?;
339            Some((serde_json::to_value(&media).ok()?, media, binary))
340        });
341        let Some((wire, media, binary)) = translated else {
342            parts.push(part.clone());
343            continue;
344        };
345        let modality = wire.get("type").and_then(Value::as_str).unwrap_or("media");
346        if modern.iter().any(|other| mirrors(other, &media, &binary)) {
347            warnings.push(format!(
348                "dropped retired binary content part at {at}/{index}: the {modality} part \
349                 beside it carries the same payload"
350            ));
351        } else {
352            warnings.push(format!(
353                "translated retired binary content part at {at}/{index} to {modality}"
354            ));
355            parts.push(wire);
356        }
357    }
358}
359
360/// Whether `part` is the media part `media` was converted to, file name
361/// included when the legacy part had one.
362#[cfg(any(feature = "client", feature = "axum"))]
363fn mirrors(part: &InputContent, media: &InputContent, legacy: &BinaryInputContent) -> bool {
364    let (part, media) = match (part, media) {
365        (InputContent::Image(part), InputContent::Image(media))
366        | (InputContent::Audio(part), InputContent::Audio(media))
367        | (InputContent::Video(part), InputContent::Video(media))
368        | (InputContent::Document(part), InputContent::Document(media)) => (part, media),
369        _ => return false,
370    };
371    let kept_name = part
372        .metadata
373        .as_ref()
374        .and_then(|metadata| metadata.get("filename"))
375        .and_then(Value::as_str);
376    let same_mime = |a: &str, b: &str| {
377        let (kind_a, params_a) = a.split_once(';').unwrap_or((a, ""));
378        let (kind_b, params_b) = b.split_once(';').unwrap_or((b, ""));
379        kind_a.eq_ignore_ascii_case(kind_b) && params_a == params_b
380    };
381    // A URL may omit MIME, while a retired binary part always carries it.
382    // Discard the mirror only when the modern attachment retains that fact.
383    let same_source = match (&part.source, &media.source) {
384        (
385            InputContentSource::Url {
386                value: a,
387                mime_type: Some(mime_a),
388            },
389            InputContentSource::Url {
390                value: b,
391                mime_type: Some(mime_b),
392            },
393        )
394        | (
395            InputContentSource::Data {
396                value: a,
397                mime_type: mime_a,
398            },
399            InputContentSource::Data {
400                value: b,
401                mime_type: mime_b,
402            },
403        ) => a == b && same_mime(mime_a, mime_b),
404        _ => false,
405    };
406    same_source
407        && legacy
408            .filename
409            .as_deref()
410            .filter(|filename| !filename.is_empty())
411            .is_none_or(|filename| kept_name == Some(filename))
412}
413
414/// One part of a multimodal user message.
415#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
416#[serde(tag = "type", rename_all = "lowercase")]
417#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
418#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
419pub enum InputContent {
420    /// Text.
421    Text(TextInputContent),
422    /// An image.
423    Image(MediaInputContent),
424    /// An audio clip.
425    Audio(MediaInputContent),
426    /// A video clip.
427    Video(MediaInputContent),
428    /// A document, for example a PDF.
429    Document(MediaInputContent),
430    /// The legacy catch-all binary part.
431    Binary(BinaryInputContent),
432}
433
434impl InputContent {
435    /// Builds a text part.
436    pub fn text(text: impl Into<String>) -> Self {
437        Self::Text(TextInputContent {
438            text: text.into(),
439            ..Default::default()
440        })
441    }
442}
443
444/// The body of a user message: either a bare string or an ordered list of
445/// multimodal parts.
446#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
447#[serde(untagged)]
448#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
449#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
450pub enum UserContent {
451    /// Plain text.
452    Text(String),
453    /// Multimodal parts.
454    Parts(Vec<InputContent>),
455}
456
457impl UserContent {
458    /// The text, when the content is a plain string.
459    ///
460    /// `None` for multimodal content, even when every part of it happens to be
461    /// text: this borrows, and joining parts cannot. Reach for
462    /// [`UserContent::to_text`] when any text will do.
463    pub fn as_text(&self) -> Option<&str> {
464        match self {
465            Self::Text(text) => Some(text),
466            Self::Parts(_) => None,
467        }
468    }
469
470    /// Every text part, in order, joined with newlines.
471    ///
472    /// Non-text parts are dropped rather than described: an agent that does not
473    /// handle images wants the caption, not a placeholder it has to strip.
474    ///
475    /// ```
476    /// use ag_ui::{InputContent, InputContentSource, MediaInputContent, UserContent};
477    ///
478    /// let plain = UserContent::from("what is the weather?");
479    /// assert_eq!(plain.as_text(), Some("what is the weather?"));
480    /// assert_eq!(plain.to_text(), "what is the weather?");
481    ///
482    /// let image = MediaInputContent::new(InputContentSource::Url {
483    ///     value: "https://example.com/cat.png".into(),
484    ///     mime_type: None,
485    /// });
486    /// let mixed = UserContent::from(vec![
487    ///     InputContent::text("what is this?"),
488    ///     InputContent::Image(image),
489    ///     InputContent::text("be brief"),
490    /// ]);
491    /// assert_eq!(mixed.as_text(), None);
492    /// assert_eq!(mixed.to_text(), "what is this?\nbe brief");
493    /// ```
494    pub fn to_text(&self) -> String {
495        match self {
496            Self::Text(text) => text.clone(),
497            Self::Parts(parts) => parts
498                .iter()
499                .filter_map(|part| match part {
500                    InputContent::Text(part) => Some(part.text.as_str()),
501                    _ => None,
502                })
503                .collect::<Vec<_>>()
504                .join("\n"),
505        }
506    }
507}
508
509impl Default for UserContent {
510    fn default() -> Self {
511        Self::Text(String::new())
512    }
513}
514
515impl From<String> for UserContent {
516    fn from(value: String) -> Self {
517        Self::Text(value)
518    }
519}
520
521impl From<&str> for UserContent {
522    fn from(value: &str) -> Self {
523        Self::Text(value.to_owned())
524    }
525}
526
527impl From<Vec<InputContent>> for UserContent {
528    fn from(value: Vec<InputContent>) -> Self {
529        Self::Parts(value)
530    }
531}
532
533/// A tool result as plain text or an ordered list of text and media parts.
534#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
535#[serde(untagged)]
536#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
537#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
538pub enum ToolContent {
539    /// Plain text, including structured data serialized by the tool.
540    Text(String),
541    /// Multimodal parts in their original order.
542    Parts(Vec<InputContent>),
543}
544
545impl ToolContent {
546    /// Borrows the payload when it is plain text.
547    pub fn as_text(&self) -> Option<&str> {
548        match self {
549            Self::Text(text) => Some(text),
550            Self::Parts(_) => None,
551        }
552    }
553
554    /// Returns text portions, ignoring media parts.
555    pub fn to_text(&self) -> String {
556        match self {
557            Self::Text(text) => text.clone(),
558            Self::Parts(parts) => parts
559                .iter()
560                .filter_map(|part| match part {
561                    InputContent::Text(part) => Some(part.text.as_str()),
562                    _ => None,
563                })
564                .collect::<Vec<_>>()
565                .join("\n"),
566        }
567    }
568}
569
570impl Default for ToolContent {
571    fn default() -> Self {
572        Self::Text(String::new())
573    }
574}
575
576impl From<String> for ToolContent {
577    fn from(value: String) -> Self {
578        Self::Text(value)
579    }
580}
581
582impl From<&str> for ToolContent {
583    fn from(value: &str) -> Self {
584        Self::Text(value.to_owned())
585    }
586}
587
588impl From<Vec<InputContent>> for ToolContent {
589    fn from(value: Vec<InputContent>) -> Self {
590        Self::Parts(value)
591    }
592}
593
594/// Out-of-band instructions from the application developer.
595#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
596#[serde(rename_all = "camelCase")]
597#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
598#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
599pub struct DeveloperMessage {
600    /// Message id.
601    pub id: MessageId,
602    /// The instructions.
603    pub content: String,
604    /// Optional display name for the author.
605    #[serde(default, skip_serializing_if = "Option::is_none")]
606    pub name: Option<String>,
607    /// Opaque provider payload for zero-data-retention modes.
608    #[serde(default, skip_serializing_if = "Option::is_none")]
609    pub encrypted_value: Option<String>,
610    /// The subagent that produced this message; absent means the parent
611    /// agent. A JSON `null` is rejected — see [`crate::event::subagent`].
612    #[serde(
613        default,
614        deserialize_with = "crate::serde_util::reject_null",
615        skip_serializing_if = "Option::is_none"
616    )]
617    pub subagent_run_id: Option<SubagentRunId>,
618    /// Extra information, open by key. Absent or an object — a JSON `null`
619    /// is rejected. See [`crate::metadata`].
620    #[serde(
621        default,
622        deserialize_with = "crate::serde_util::reject_null",
623        skip_serializing_if = "Option::is_none"
624    )]
625    #[cfg_attr(
626        feature = "schemars",
627        schemars(with = "Option<std::collections::BTreeMap<String, serde_json::Value>>")
628    )]
629    #[cfg_attr(feature = "utoipa", schema(value_type = Option<Object>))]
630    pub metadata: Option<JsonObject>,
631}
632
633/// The system prompt.
634#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
635#[serde(rename_all = "camelCase")]
636#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
637#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
638pub struct SystemMessage {
639    /// Message id.
640    pub id: MessageId,
641    /// The prompt.
642    pub content: String,
643    /// Optional display name for the author.
644    #[serde(default, skip_serializing_if = "Option::is_none")]
645    pub name: Option<String>,
646    /// Opaque provider payload for zero-data-retention modes.
647    #[serde(default, skip_serializing_if = "Option::is_none")]
648    pub encrypted_value: Option<String>,
649    /// The subagent that produced this message; absent means the parent
650    /// agent. A JSON `null` is rejected — see [`crate::event::subagent`].
651    #[serde(
652        default,
653        deserialize_with = "crate::serde_util::reject_null",
654        skip_serializing_if = "Option::is_none"
655    )]
656    pub subagent_run_id: Option<SubagentRunId>,
657    /// Extra information, open by key. Absent or an object — a JSON `null`
658    /// is rejected. See [`crate::metadata`].
659    #[serde(
660        default,
661        deserialize_with = "crate::serde_util::reject_null",
662        skip_serializing_if = "Option::is_none"
663    )]
664    #[cfg_attr(
665        feature = "schemars",
666        schemars(with = "Option<std::collections::BTreeMap<String, serde_json::Value>>")
667    )]
668    #[cfg_attr(feature = "utoipa", schema(value_type = Option<Object>))]
669    pub metadata: Option<JsonObject>,
670}
671
672/// Model output, optionally requesting tool calls.
673#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
674#[serde(rename_all = "camelCase")]
675#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
676#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
677pub struct AssistantMessage {
678    /// Message id.
679    pub id: MessageId,
680    /// The reply text. Absent when the turn is tool calls only.
681    #[serde(default, skip_serializing_if = "Option::is_none")]
682    pub content: Option<String>,
683    /// Optional display name for the author.
684    #[serde(default, skip_serializing_if = "Option::is_none")]
685    pub name: Option<String>,
686    /// Opaque provider payload for zero-data-retention modes.
687    #[serde(default, skip_serializing_if = "Option::is_none")]
688    pub encrypted_value: Option<String>,
689    /// Tool calls the assistant wants executed.
690    #[serde(default, skip_serializing_if = "Option::is_none")]
691    pub tool_calls: Option<Vec<ToolCall>>,
692    /// The subagent that produced this message; absent means the parent
693    /// agent. A JSON `null` is rejected — see [`crate::event::subagent`].
694    #[serde(
695        default,
696        deserialize_with = "crate::serde_util::reject_null",
697        skip_serializing_if = "Option::is_none"
698    )]
699    pub subagent_run_id: Option<SubagentRunId>,
700    /// Extra information, open by key. Absent or an object — a JSON `null`
701    /// is rejected. See [`crate::metadata`].
702    #[serde(
703        default,
704        deserialize_with = "crate::serde_util::reject_null",
705        skip_serializing_if = "Option::is_none"
706    )]
707    #[cfg_attr(
708        feature = "schemars",
709        schemars(with = "Option<std::collections::BTreeMap<String, serde_json::Value>>")
710    )]
711    #[cfg_attr(feature = "utoipa", schema(value_type = Option<Object>))]
712    pub metadata: Option<JsonObject>,
713}
714
715/// End-user input, possibly multimodal.
716#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
717#[serde(rename_all = "camelCase")]
718#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
719#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
720pub struct UserMessage {
721    /// Message id.
722    pub id: MessageId,
723    /// Text or multimodal parts.
724    pub content: UserContent,
725    /// Optional display name for the author.
726    #[serde(default, skip_serializing_if = "Option::is_none")]
727    pub name: Option<String>,
728    /// Opaque provider payload for zero-data-retention modes.
729    #[serde(default, skip_serializing_if = "Option::is_none")]
730    pub encrypted_value: Option<String>,
731    /// The subagent that produced this message; absent means the parent
732    /// agent. A JSON `null` is rejected — see [`crate::event::subagent`].
733    #[serde(
734        default,
735        deserialize_with = "crate::serde_util::reject_null",
736        skip_serializing_if = "Option::is_none"
737    )]
738    pub subagent_run_id: Option<SubagentRunId>,
739    /// Extra information, open by key. Absent or an object — a JSON `null`
740    /// is rejected. See [`crate::metadata`].
741    #[serde(
742        default,
743        deserialize_with = "crate::serde_util::reject_null",
744        skip_serializing_if = "Option::is_none"
745    )]
746    #[cfg_attr(
747        feature = "schemars",
748        schemars(with = "Option<std::collections::BTreeMap<String, serde_json::Value>>")
749    )]
750    #[cfg_attr(feature = "utoipa", schema(value_type = Option<Object>))]
751    pub metadata: Option<JsonObject>,
752}
753
754/// The result of a tool call, fed back to the model.
755#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
756#[serde(rename_all = "camelCase")]
757#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
758#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
759pub struct ToolMessage {
760    /// Message id.
761    pub id: MessageId,
762    /// Plain text or ordered multimodal parts returned by the tool.
763    pub content: ToolContent,
764    /// The call this result answers.
765    pub tool_call_id: ToolCallId,
766    /// Set when the tool failed; `content` then holds whatever partial output
767    /// there was.
768    #[serde(default, skip_serializing_if = "Option::is_none")]
769    pub error: Option<String>,
770    /// Opaque provider payload for zero-data-retention modes.
771    #[serde(default, skip_serializing_if = "Option::is_none")]
772    pub encrypted_value: Option<String>,
773    /// The subagent that *executed* the call; absent means the parent agent.
774    /// Attributed independently of the call it answers — see
775    /// [`ToolCallResultEvent`](crate::event::ToolCallResultEvent). A JSON
776    /// `null` is rejected.
777    #[serde(
778        default,
779        deserialize_with = "crate::serde_util::reject_null",
780        skip_serializing_if = "Option::is_none"
781    )]
782    pub subagent_run_id: Option<SubagentRunId>,
783    /// Extra information, open by key. Absent or an object — a JSON `null`
784    /// is rejected. See [`crate::metadata`].
785    #[serde(
786        default,
787        deserialize_with = "crate::serde_util::reject_null",
788        skip_serializing_if = "Option::is_none"
789    )]
790    #[cfg_attr(
791        feature = "schemars",
792        schemars(with = "Option<std::collections::BTreeMap<String, serde_json::Value>>")
793    )]
794    #[cfg_attr(feature = "utoipa", schema(value_type = Option<Object>))]
795    pub metadata: Option<JsonObject>,
796}
797
798/// A structured progress update the client renders as it likes.
799#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
800#[serde(rename_all = "camelCase")]
801#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
802#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
803pub struct ActivityMessage {
804    /// Message id.
805    pub id: MessageId,
806    /// Client-defined activity discriminator, for example `"web_search"`.
807    pub activity_type: String,
808    /// The activity payload.
809    #[cfg_attr(
810        feature = "schemars",
811        schemars(with = "std::collections::BTreeMap<String, serde_json::Value>")
812    )]
813    #[cfg_attr(feature = "utoipa", schema(value_type = Object))]
814    pub content: JsonObject,
815    /// The subagent that produced this message; absent means the parent
816    /// agent. A JSON `null` is rejected — see [`crate::event::subagent`].
817    #[serde(
818        default,
819        deserialize_with = "crate::serde_util::reject_null",
820        skip_serializing_if = "Option::is_none"
821    )]
822    pub subagent_run_id: Option<SubagentRunId>,
823    /// Extra information, open by key. Absent or an object — a JSON `null`
824    /// is rejected. See [`crate::metadata`].
825    #[serde(
826        default,
827        deserialize_with = "crate::serde_util::reject_null",
828        skip_serializing_if = "Option::is_none"
829    )]
830    #[cfg_attr(
831        feature = "schemars",
832        schemars(with = "Option<std::collections::BTreeMap<String, serde_json::Value>>")
833    )]
834    #[cfg_attr(feature = "utoipa", schema(value_type = Option<Object>))]
835    pub metadata: Option<JsonObject>,
836}
837
838/// Model reasoning, shown separately from the reply.
839#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
840#[serde(rename_all = "camelCase")]
841#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
842#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
843pub struct ReasoningMessage {
844    /// Message id.
845    pub id: MessageId,
846    /// The reasoning text. Empty when the provider only returns an encrypted
847    /// blob.
848    pub content: String,
849    /// Opaque provider payload for zero-data-retention modes.
850    #[serde(default, skip_serializing_if = "Option::is_none")]
851    pub encrypted_value: Option<String>,
852    /// The subagent that produced this message; absent means the parent
853    /// agent. A JSON `null` is rejected — see [`crate::event::subagent`].
854    #[serde(
855        default,
856        deserialize_with = "crate::serde_util::reject_null",
857        skip_serializing_if = "Option::is_none"
858    )]
859    pub subagent_run_id: Option<SubagentRunId>,
860    /// Extra information, open by key. Absent or an object — a JSON `null`
861    /// is rejected. See [`crate::metadata`].
862    #[serde(
863        default,
864        deserialize_with = "crate::serde_util::reject_null",
865        skip_serializing_if = "Option::is_none"
866    )]
867    #[cfg_attr(
868        feature = "schemars",
869        schemars(with = "Option<std::collections::BTreeMap<String, serde_json::Value>>")
870    )]
871    #[cfg_attr(feature = "utoipa", schema(value_type = Option<Object>))]
872    pub metadata: Option<JsonObject>,
873}
874
875/// A message in a thread, discriminated by its `role`.
876#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
877#[serde(tag = "role", rename_all = "lowercase")]
878#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
879#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
880pub enum Message {
881    /// See [`DeveloperMessage`].
882    Developer(DeveloperMessage),
883    /// See [`SystemMessage`].
884    System(SystemMessage),
885    /// See [`AssistantMessage`].
886    Assistant(AssistantMessage),
887    /// See [`UserMessage`].
888    User(UserMessage),
889    /// See [`ToolMessage`].
890    Tool(ToolMessage),
891    /// See [`ActivityMessage`].
892    Activity(ActivityMessage),
893    /// See [`ReasoningMessage`].
894    Reasoning(ReasoningMessage),
895}
896
897impl Message {
898    /// Builds a user message carrying plain text.
899    pub fn user(id: impl Into<MessageId>, content: impl Into<UserContent>) -> Self {
900        Self::User(UserMessage {
901            id: id.into(),
902            content: content.into(),
903            ..Default::default()
904        })
905    }
906
907    /// Builds an assistant message carrying plain text.
908    pub fn assistant(id: impl Into<MessageId>, content: impl Into<String>) -> Self {
909        Self::Assistant(AssistantMessage {
910            id: id.into(),
911            content: Some(content.into()),
912            ..Default::default()
913        })
914    }
915
916    /// Builds a system message.
917    pub fn system(id: impl Into<MessageId>, content: impl Into<String>) -> Self {
918        Self::System(SystemMessage {
919            id: id.into(),
920            content: content.into(),
921            ..Default::default()
922        })
923    }
924
925    /// Builds a developer message.
926    pub fn developer(id: impl Into<MessageId>, content: impl Into<String>) -> Self {
927        Self::Developer(DeveloperMessage {
928            id: id.into(),
929            content: content.into(),
930            ..Default::default()
931        })
932    }
933
934    /// Builds a tool result message.
935    pub fn tool(
936        id: impl Into<MessageId>,
937        tool_call_id: impl Into<ToolCallId>,
938        content: impl Into<ToolContent>,
939    ) -> Self {
940        Self::Tool(ToolMessage {
941            id: id.into(),
942            content: content.into(),
943            tool_call_id: tool_call_id.into(),
944            ..Default::default()
945        })
946    }
947
948    /// The message id, whatever the role.
949    pub const fn id(&self) -> &MessageId {
950        match self {
951            Self::Developer(m) => &m.id,
952            Self::System(m) => &m.id,
953            Self::Assistant(m) => &m.id,
954            Self::User(m) => &m.id,
955            Self::Tool(m) => &m.id,
956            Self::Activity(m) => &m.id,
957            Self::Reasoning(m) => &m.id,
958        }
959    }
960
961    /// The role, whatever the variant.
962    pub const fn role(&self) -> Role {
963        match self {
964            Self::Developer(_) => Role::Developer,
965            Self::System(_) => Role::System,
966            Self::Assistant(_) => Role::Assistant,
967            Self::User(_) => Role::User,
968            Self::Tool(_) => Role::Tool,
969            Self::Activity(_) => Role::Activity,
970            Self::Reasoning(_) => Role::Reasoning,
971        }
972    }
973
974    /// The subagent that produced the message, whatever the role. `None`
975    /// means the parent agent. See [`crate::event::subagent`].
976    pub const fn subagent_run_id(&self) -> Option<&SubagentRunId> {
977        match self {
978            Self::Developer(m) => m.subagent_run_id.as_ref(),
979            Self::System(m) => m.subagent_run_id.as_ref(),
980            Self::Assistant(m) => m.subagent_run_id.as_ref(),
981            Self::User(m) => m.subagent_run_id.as_ref(),
982            Self::Tool(m) => m.subagent_run_id.as_ref(),
983            Self::Activity(m) => m.subagent_run_id.as_ref(),
984            Self::Reasoning(m) => m.subagent_run_id.as_ref(),
985        }
986    }
987
988    /// Sets or clears the subagent the message is attributed to.
989    pub fn set_subagent_run_id(&mut self, subagent_run_id: Option<SubagentRunId>) {
990        match self {
991            Self::Developer(m) => m.subagent_run_id = subagent_run_id,
992            Self::System(m) => m.subagent_run_id = subagent_run_id,
993            Self::Assistant(m) => m.subagent_run_id = subagent_run_id,
994            Self::User(m) => m.subagent_run_id = subagent_run_id,
995            Self::Tool(m) => m.subagent_run_id = subagent_run_id,
996            Self::Activity(m) => m.subagent_run_id = subagent_run_id,
997            Self::Reasoning(m) => m.subagent_run_id = subagent_run_id,
998        }
999    }
1000
1001    /// The message's metadata, whatever the role. See [`crate::metadata`].
1002    pub const fn metadata(&self) -> Option<&JsonObject> {
1003        match self {
1004            Self::Developer(m) => m.metadata.as_ref(),
1005            Self::System(m) => m.metadata.as_ref(),
1006            Self::Assistant(m) => m.metadata.as_ref(),
1007            Self::User(m) => m.metadata.as_ref(),
1008            Self::Tool(m) => m.metadata.as_ref(),
1009            Self::Activity(m) => m.metadata.as_ref(),
1010            Self::Reasoning(m) => m.metadata.as_ref(),
1011        }
1012    }
1013
1014    /// The metadata slot, for a consumer merging an event's metadata into
1015    /// the message it builds — see
1016    /// [`merge_metadata_into`](crate::metadata::merge_metadata_into).
1017    pub fn metadata_mut(&mut self) -> &mut Option<JsonObject> {
1018        match self {
1019            Self::Developer(m) => &mut m.metadata,
1020            Self::System(m) => &mut m.metadata,
1021            Self::Assistant(m) => &mut m.metadata,
1022            Self::User(m) => &mut m.metadata,
1023            Self::Tool(m) => &mut m.metadata,
1024            Self::Activity(m) => &mut m.metadata,
1025            Self::Reasoning(m) => &mut m.metadata,
1026        }
1027    }
1028}
1029
1030macro_rules! message_from {
1031    ($($ty:ident => $variant:ident),* $(,)?) => {
1032        $(
1033            impl From<$ty> for Message {
1034                fn from(value: $ty) -> Self {
1035                    Self::$variant(value)
1036                }
1037            }
1038        )*
1039    };
1040}
1041
1042message_from! {
1043    DeveloperMessage => Developer,
1044    SystemMessage => System,
1045    AssistantMessage => Assistant,
1046    UserMessage => User,
1047    ToolMessage => Tool,
1048    ActivityMessage => Activity,
1049    ReasoningMessage => Reasoning,
1050}