ag-ui 0.3.0

A Rust SDK for the AG-UI protocol: protocol types and wire encoding, a server runtime for hosting an agent, and a client runtime for consuming one. Working toward becoming the official AG-UI Rust SDK; not affiliated with the AG-UI protocol organisation today.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
//! The message union and its multimodal content parts.

use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::JsonObject;
use crate::ids::{MessageId, SubagentRunId, ToolCallId};
use crate::tool::ToolCall;

/// Every role the protocol defines.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub enum Role {
    /// Out-of-band instructions from the application developer.
    Developer,
    /// System prompt.
    System,
    /// Model output.
    Assistant,
    /// End-user input.
    User,
    /// The result of a tool call.
    Tool,
    /// A structured progress update rendered by the client.
    Activity,
    /// Model reasoning / chain-of-thought.
    Reasoning,
}

impl Role {
    /// The role string as it appears on the wire.
    pub const fn as_str(&self) -> &'static str {
        match self {
            Self::Developer => "developer",
            Self::System => "system",
            Self::Assistant => "assistant",
            Self::User => "user",
            Self::Tool => "tool",
            Self::Activity => "activity",
            Self::Reasoning => "reasoning",
        }
    }
}

impl std::fmt::Display for Role {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Where the bytes of a multimodal part live.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "lowercase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub enum InputContentSource {
    /// Inline data, typically base64.
    Data {
        /// The encoded payload.
        value: String,
        /// MIME type of the payload, for example `image/png`.
        #[serde(rename = "mimeType")]
        mime_type: String,
    },
    /// A URL the consumer fetches itself.
    Url {
        /// The URL.
        value: String,
        /// MIME type, when the producer knows it.
        #[serde(rename = "mimeType", default, skip_serializing_if = "Option::is_none")]
        mime_type: Option<String>,
    },
}

/// A plain-text content part.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct TextInputContent {
    /// The text.
    pub text: String,
}

/// An image, audio, video or document content part.
///
/// The four modalities share a shape, so they share a struct; which one it is
/// is carried by the [`InputContent`] variant.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct MediaInputContent {
    /// Where the bytes are.
    pub source: InputContentSource,
    /// Producer-defined extras (dimensions, page counts, alt text, …).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Value>,
}

impl MediaInputContent {
    /// Builds a media part from a source, with no metadata.
    pub fn new(source: InputContentSource) -> Self {
        Self {
            source,
            metadata: None,
        }
    }
}

/// The legacy `binary` content part.
///
/// Superseded by the modality-specific parts, but still accepted: at least one
/// of `id`, `url` or `data` must be set. That constraint is a runtime rule in
/// the upstream schema and is not encoded in this type — see
/// [`BinaryInputContent::has_payload`].
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct BinaryInputContent {
    /// MIME type of the payload.
    pub mime_type: String,
    /// Reference to a previously uploaded blob.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
    /// URL to fetch the payload from.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,
    /// Inline payload, typically base64.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub data: Option<String>,
    /// Original file name, for display.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub filename: Option<String>,
}

impl BinaryInputContent {
    /// Whether the part carries a payload in any of the three accepted forms.
    pub fn has_payload(&self) -> bool {
        self.id.is_some() || self.url.is_some() || self.data.is_some()
    }
}

/// One part of a multimodal user message.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "lowercase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub enum InputContent {
    /// Text.
    Text(TextInputContent),
    /// An image.
    Image(MediaInputContent),
    /// An audio clip.
    Audio(MediaInputContent),
    /// A video clip.
    Video(MediaInputContent),
    /// A document, for example a PDF.
    Document(MediaInputContent),
    /// The legacy catch-all binary part.
    Binary(BinaryInputContent),
}

impl InputContent {
    /// Builds a text part.
    pub fn text(text: impl Into<String>) -> Self {
        Self::Text(TextInputContent { text: text.into() })
    }
}

/// The body of a user message: either a bare string or an ordered list of
/// multimodal parts.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub enum UserContent {
    /// Plain text.
    Text(String),
    /// Multimodal parts.
    Parts(Vec<InputContent>),
}

impl UserContent {
    /// The text, when the content is a plain string.
    ///
    /// `None` for multimodal content, even when every part of it happens to be
    /// text: this borrows, and joining parts cannot. Reach for
    /// [`UserContent::to_text`] when any text will do.
    pub fn as_text(&self) -> Option<&str> {
        match self {
            Self::Text(text) => Some(text),
            Self::Parts(_) => None,
        }
    }

    /// Every text part, in order, joined with newlines.
    ///
    /// Non-text parts are dropped rather than described: an agent that does not
    /// handle images wants the caption, not a placeholder it has to strip.
    ///
    /// ```
    /// use ag_ui::{InputContent, InputContentSource, MediaInputContent, UserContent};
    ///
    /// let plain = UserContent::from("what is the weather?");
    /// assert_eq!(plain.as_text(), Some("what is the weather?"));
    /// assert_eq!(plain.to_text(), "what is the weather?");
    ///
    /// let image = MediaInputContent::new(InputContentSource::Url {
    ///     value: "https://example.com/cat.png".into(),
    ///     mime_type: None,
    /// });
    /// let mixed = UserContent::from(vec![
    ///     InputContent::text("what is this?"),
    ///     InputContent::Image(image),
    ///     InputContent::text("be brief"),
    /// ]);
    /// assert_eq!(mixed.as_text(), None);
    /// assert_eq!(mixed.to_text(), "what is this?\nbe brief");
    /// ```
    pub fn to_text(&self) -> String {
        match self {
            Self::Text(text) => text.clone(),
            Self::Parts(parts) => parts
                .iter()
                .filter_map(|part| match part {
                    InputContent::Text(part) => Some(part.text.as_str()),
                    _ => None,
                })
                .collect::<Vec<_>>()
                .join("\n"),
        }
    }
}

impl Default for UserContent {
    fn default() -> Self {
        Self::Text(String::new())
    }
}

impl From<String> for UserContent {
    fn from(value: String) -> Self {
        Self::Text(value)
    }
}

impl From<&str> for UserContent {
    fn from(value: &str) -> Self {
        Self::Text(value.to_owned())
    }
}

impl From<Vec<InputContent>> for UserContent {
    fn from(value: Vec<InputContent>) -> Self {
        Self::Parts(value)
    }
}

/// Out-of-band instructions from the application developer.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct DeveloperMessage {
    /// Message id.
    pub id: MessageId,
    /// The instructions.
    pub content: String,
    /// Optional display name for the author.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Opaque provider payload for zero-data-retention modes.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub encrypted_value: Option<String>,
    /// The subagent that produced this message; absent means the parent
    /// agent. A JSON `null` is rejected — see [`crate::event::subagent`].
    #[serde(
        default,
        deserialize_with = "crate::serde_util::reject_null",
        skip_serializing_if = "Option::is_none"
    )]
    pub subagent_run_id: Option<SubagentRunId>,
    /// Extra information, open by key. Absent or an object — a JSON `null`
    /// is rejected. See [`crate::metadata`].
    #[serde(
        default,
        deserialize_with = "crate::serde_util::reject_null",
        skip_serializing_if = "Option::is_none"
    )]
    #[cfg_attr(
        feature = "schemars",
        schemars(with = "Option<std::collections::BTreeMap<String, serde_json::Value>>")
    )]
    #[cfg_attr(feature = "utoipa", schema(value_type = Option<Object>))]
    pub metadata: Option<JsonObject>,
}

/// The system prompt.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct SystemMessage {
    /// Message id.
    pub id: MessageId,
    /// The prompt.
    pub content: String,
    /// Optional display name for the author.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Opaque provider payload for zero-data-retention modes.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub encrypted_value: Option<String>,
    /// The subagent that produced this message; absent means the parent
    /// agent. A JSON `null` is rejected — see [`crate::event::subagent`].
    #[serde(
        default,
        deserialize_with = "crate::serde_util::reject_null",
        skip_serializing_if = "Option::is_none"
    )]
    pub subagent_run_id: Option<SubagentRunId>,
    /// Extra information, open by key. Absent or an object — a JSON `null`
    /// is rejected. See [`crate::metadata`].
    #[serde(
        default,
        deserialize_with = "crate::serde_util::reject_null",
        skip_serializing_if = "Option::is_none"
    )]
    #[cfg_attr(
        feature = "schemars",
        schemars(with = "Option<std::collections::BTreeMap<String, serde_json::Value>>")
    )]
    #[cfg_attr(feature = "utoipa", schema(value_type = Option<Object>))]
    pub metadata: Option<JsonObject>,
}

/// Model output, optionally requesting tool calls.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct AssistantMessage {
    /// Message id.
    pub id: MessageId,
    /// The reply text. Absent when the turn is tool calls only.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub content: Option<String>,
    /// Optional display name for the author.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Opaque provider payload for zero-data-retention modes.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub encrypted_value: Option<String>,
    /// Tool calls the assistant wants executed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tool_calls: Option<Vec<ToolCall>>,
    /// The subagent that produced this message; absent means the parent
    /// agent. A JSON `null` is rejected — see [`crate::event::subagent`].
    #[serde(
        default,
        deserialize_with = "crate::serde_util::reject_null",
        skip_serializing_if = "Option::is_none"
    )]
    pub subagent_run_id: Option<SubagentRunId>,
    /// Extra information, open by key. Absent or an object — a JSON `null`
    /// is rejected. See [`crate::metadata`].
    #[serde(
        default,
        deserialize_with = "crate::serde_util::reject_null",
        skip_serializing_if = "Option::is_none"
    )]
    #[cfg_attr(
        feature = "schemars",
        schemars(with = "Option<std::collections::BTreeMap<String, serde_json::Value>>")
    )]
    #[cfg_attr(feature = "utoipa", schema(value_type = Option<Object>))]
    pub metadata: Option<JsonObject>,
}

/// End-user input, possibly multimodal.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct UserMessage {
    /// Message id.
    pub id: MessageId,
    /// Text or multimodal parts.
    pub content: UserContent,
    /// Optional display name for the author.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Opaque provider payload for zero-data-retention modes.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub encrypted_value: Option<String>,
    /// The subagent that produced this message; absent means the parent
    /// agent. A JSON `null` is rejected — see [`crate::event::subagent`].
    #[serde(
        default,
        deserialize_with = "crate::serde_util::reject_null",
        skip_serializing_if = "Option::is_none"
    )]
    pub subagent_run_id: Option<SubagentRunId>,
    /// Extra information, open by key. Absent or an object — a JSON `null`
    /// is rejected. See [`crate::metadata`].
    #[serde(
        default,
        deserialize_with = "crate::serde_util::reject_null",
        skip_serializing_if = "Option::is_none"
    )]
    #[cfg_attr(
        feature = "schemars",
        schemars(with = "Option<std::collections::BTreeMap<String, serde_json::Value>>")
    )]
    #[cfg_attr(feature = "utoipa", schema(value_type = Option<Object>))]
    pub metadata: Option<JsonObject>,
}

/// The result of a tool call, fed back to the model.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct ToolMessage {
    /// Message id.
    pub id: MessageId,
    /// The result, already rendered to a string.
    pub content: String,
    /// The call this result answers.
    pub tool_call_id: ToolCallId,
    /// Set when the tool failed; `content` then holds whatever partial output
    /// there was.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
    /// Opaque provider payload for zero-data-retention modes.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub encrypted_value: Option<String>,
    /// The subagent that *executed* the call; absent means the parent agent.
    /// Attributed independently of the call it answers — see
    /// [`ToolCallResultEvent`](crate::event::ToolCallResultEvent). A JSON
    /// `null` is rejected.
    #[serde(
        default,
        deserialize_with = "crate::serde_util::reject_null",
        skip_serializing_if = "Option::is_none"
    )]
    pub subagent_run_id: Option<SubagentRunId>,
    /// Extra information, open by key. Absent or an object — a JSON `null`
    /// is rejected. See [`crate::metadata`].
    #[serde(
        default,
        deserialize_with = "crate::serde_util::reject_null",
        skip_serializing_if = "Option::is_none"
    )]
    #[cfg_attr(
        feature = "schemars",
        schemars(with = "Option<std::collections::BTreeMap<String, serde_json::Value>>")
    )]
    #[cfg_attr(feature = "utoipa", schema(value_type = Option<Object>))]
    pub metadata: Option<JsonObject>,
}

/// A structured progress update the client renders as it likes.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct ActivityMessage {
    /// Message id.
    pub id: MessageId,
    /// Client-defined activity discriminator, for example `"web_search"`.
    pub activity_type: String,
    /// The activity payload.
    #[cfg_attr(
        feature = "schemars",
        schemars(with = "std::collections::BTreeMap<String, serde_json::Value>")
    )]
    #[cfg_attr(feature = "utoipa", schema(value_type = Object))]
    pub content: JsonObject,
    /// The subagent that produced this message; absent means the parent
    /// agent. A JSON `null` is rejected — see [`crate::event::subagent`].
    #[serde(
        default,
        deserialize_with = "crate::serde_util::reject_null",
        skip_serializing_if = "Option::is_none"
    )]
    pub subagent_run_id: Option<SubagentRunId>,
    /// Extra information, open by key. Absent or an object — a JSON `null`
    /// is rejected. See [`crate::metadata`].
    #[serde(
        default,
        deserialize_with = "crate::serde_util::reject_null",
        skip_serializing_if = "Option::is_none"
    )]
    #[cfg_attr(
        feature = "schemars",
        schemars(with = "Option<std::collections::BTreeMap<String, serde_json::Value>>")
    )]
    #[cfg_attr(feature = "utoipa", schema(value_type = Option<Object>))]
    pub metadata: Option<JsonObject>,
}

/// Model reasoning, shown separately from the reply.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct ReasoningMessage {
    /// Message id.
    pub id: MessageId,
    /// The reasoning text. Empty when the provider only returns an encrypted
    /// blob.
    pub content: String,
    /// Opaque provider payload for zero-data-retention modes.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub encrypted_value: Option<String>,
    /// The subagent that produced this message; absent means the parent
    /// agent. A JSON `null` is rejected — see [`crate::event::subagent`].
    #[serde(
        default,
        deserialize_with = "crate::serde_util::reject_null",
        skip_serializing_if = "Option::is_none"
    )]
    pub subagent_run_id: Option<SubagentRunId>,
    /// Extra information, open by key. Absent or an object — a JSON `null`
    /// is rejected. See [`crate::metadata`].
    #[serde(
        default,
        deserialize_with = "crate::serde_util::reject_null",
        skip_serializing_if = "Option::is_none"
    )]
    #[cfg_attr(
        feature = "schemars",
        schemars(with = "Option<std::collections::BTreeMap<String, serde_json::Value>>")
    )]
    #[cfg_attr(feature = "utoipa", schema(value_type = Option<Object>))]
    pub metadata: Option<JsonObject>,
}

/// A message in a thread, discriminated by its `role`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "role", rename_all = "lowercase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub enum Message {
    /// See [`DeveloperMessage`].
    Developer(DeveloperMessage),
    /// See [`SystemMessage`].
    System(SystemMessage),
    /// See [`AssistantMessage`].
    Assistant(AssistantMessage),
    /// See [`UserMessage`].
    User(UserMessage),
    /// See [`ToolMessage`].
    Tool(ToolMessage),
    /// See [`ActivityMessage`].
    Activity(ActivityMessage),
    /// See [`ReasoningMessage`].
    Reasoning(ReasoningMessage),
}

impl Message {
    /// Builds a user message carrying plain text.
    pub fn user(id: impl Into<MessageId>, content: impl Into<UserContent>) -> Self {
        Self::User(UserMessage {
            id: id.into(),
            content: content.into(),
            ..Default::default()
        })
    }

    /// Builds an assistant message carrying plain text.
    pub fn assistant(id: impl Into<MessageId>, content: impl Into<String>) -> Self {
        Self::Assistant(AssistantMessage {
            id: id.into(),
            content: Some(content.into()),
            ..Default::default()
        })
    }

    /// Builds a system message.
    pub fn system(id: impl Into<MessageId>, content: impl Into<String>) -> Self {
        Self::System(SystemMessage {
            id: id.into(),
            content: content.into(),
            ..Default::default()
        })
    }

    /// Builds a developer message.
    pub fn developer(id: impl Into<MessageId>, content: impl Into<String>) -> Self {
        Self::Developer(DeveloperMessage {
            id: id.into(),
            content: content.into(),
            ..Default::default()
        })
    }

    /// Builds a tool result message.
    pub fn tool(
        id: impl Into<MessageId>,
        tool_call_id: impl Into<ToolCallId>,
        content: impl Into<String>,
    ) -> Self {
        Self::Tool(ToolMessage {
            id: id.into(),
            content: content.into(),
            tool_call_id: tool_call_id.into(),
            ..Default::default()
        })
    }

    /// The message id, whatever the role.
    pub const fn id(&self) -> &MessageId {
        match self {
            Self::Developer(m) => &m.id,
            Self::System(m) => &m.id,
            Self::Assistant(m) => &m.id,
            Self::User(m) => &m.id,
            Self::Tool(m) => &m.id,
            Self::Activity(m) => &m.id,
            Self::Reasoning(m) => &m.id,
        }
    }

    /// The role, whatever the variant.
    pub const fn role(&self) -> Role {
        match self {
            Self::Developer(_) => Role::Developer,
            Self::System(_) => Role::System,
            Self::Assistant(_) => Role::Assistant,
            Self::User(_) => Role::User,
            Self::Tool(_) => Role::Tool,
            Self::Activity(_) => Role::Activity,
            Self::Reasoning(_) => Role::Reasoning,
        }
    }

    /// The subagent that produced the message, whatever the role. `None`
    /// means the parent agent. See [`crate::event::subagent`].
    pub const fn subagent_run_id(&self) -> Option<&SubagentRunId> {
        match self {
            Self::Developer(m) => m.subagent_run_id.as_ref(),
            Self::System(m) => m.subagent_run_id.as_ref(),
            Self::Assistant(m) => m.subagent_run_id.as_ref(),
            Self::User(m) => m.subagent_run_id.as_ref(),
            Self::Tool(m) => m.subagent_run_id.as_ref(),
            Self::Activity(m) => m.subagent_run_id.as_ref(),
            Self::Reasoning(m) => m.subagent_run_id.as_ref(),
        }
    }

    /// Sets or clears the subagent the message is attributed to.
    pub fn set_subagent_run_id(&mut self, subagent_run_id: Option<SubagentRunId>) {
        match self {
            Self::Developer(m) => m.subagent_run_id = subagent_run_id,
            Self::System(m) => m.subagent_run_id = subagent_run_id,
            Self::Assistant(m) => m.subagent_run_id = subagent_run_id,
            Self::User(m) => m.subagent_run_id = subagent_run_id,
            Self::Tool(m) => m.subagent_run_id = subagent_run_id,
            Self::Activity(m) => m.subagent_run_id = subagent_run_id,
            Self::Reasoning(m) => m.subagent_run_id = subagent_run_id,
        }
    }

    /// The message's metadata, whatever the role. See [`crate::metadata`].
    pub const fn metadata(&self) -> Option<&JsonObject> {
        match self {
            Self::Developer(m) => m.metadata.as_ref(),
            Self::System(m) => m.metadata.as_ref(),
            Self::Assistant(m) => m.metadata.as_ref(),
            Self::User(m) => m.metadata.as_ref(),
            Self::Tool(m) => m.metadata.as_ref(),
            Self::Activity(m) => m.metadata.as_ref(),
            Self::Reasoning(m) => m.metadata.as_ref(),
        }
    }

    /// The metadata slot, for a consumer merging an event's metadata into
    /// the message it builds — see
    /// [`merge_metadata_into`](crate::metadata::merge_metadata_into).
    pub fn metadata_mut(&mut self) -> &mut Option<JsonObject> {
        match self {
            Self::Developer(m) => &mut m.metadata,
            Self::System(m) => &mut m.metadata,
            Self::Assistant(m) => &mut m.metadata,
            Self::User(m) => &mut m.metadata,
            Self::Tool(m) => &mut m.metadata,
            Self::Activity(m) => &mut m.metadata,
            Self::Reasoning(m) => &mut m.metadata,
        }
    }
}

macro_rules! message_from {
    ($($ty:ident => $variant:ident),* $(,)?) => {
        $(
            impl From<$ty> for Message {
                fn from(value: $ty) -> Self {
                    Self::$variant(value)
                }
            }
        )*
    };
}

message_from! {
    DeveloperMessage => Developer,
    SystemMessage => System,
    AssistantMessage => Assistant,
    UserMessage => User,
    ToolMessage => Tool,
    ActivityMessage => Activity,
    ReasoningMessage => Reasoning,
}