ag-ui 1.0.0

Rust SDK for AG-UI 1.0 with protocol types, SSE, a server runtime for hosting agents, and a client runtime for consuming them.
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
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
//! 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,
            deserialize_with = "crate::serde_util::reject_null",
            skip_serializing_if = "Option::is_none"
        )]
        mime_type: Option<String>,
    },
    /// An opaque provider-issued file handle, not a URL to fetch.
    File {
        /// The handle exactly as the provider issued it.
        value: String,
        /// Issuing provider, when known.
        #[serde(
            default,
            deserialize_with = "crate::serde_util::reject_null",
            skip_serializing_if = "Option::is_none"
        )]
        provider: Option<String>,
        /// MIME type, when known.
        #[serde(
            rename = "mimeType",
            default,
            deserialize_with = "crate::serde_util::reject_null",
            skip_serializing_if = "Option::is_none"
        )]
        mime_type: Option<String>,
    },
}

/// A plain-text content part.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct TextInputContent {
    /// Optional identifier for this part within its message.
    #[serde(
        default,
        deserialize_with = "crate::serde_util::reject_null",
        skip_serializing_if = "Option::is_none"
    )]
    pub id: Option<String>,
    /// The text.
    pub text: String,
    /// Producer-defined information about this part.
    #[serde(
        default,
        deserialize_with = "crate::serde_util::reject_null",
        skip_serializing_if = "crate::serde_util::is_none_or_null"
    )]
    pub metadata: Option<Value>,
}

/// 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 {
    /// Optional identifier for this part within its message.
    #[serde(
        default,
        deserialize_with = "crate::serde_util::reject_null",
        skip_serializing_if = "Option::is_none"
    )]
    pub id: Option<String>,
    /// Where the bytes are.
    pub source: InputContentSource,
    /// Producer-defined extras (dimensions, page counts, alt text, …).
    #[serde(
        default,
        deserialize_with = "crate::serde_util::reject_null",
        skip_serializing_if = "crate::serde_util::is_none_or_null"
    )]
    pub metadata: Option<Value>,
}

impl MediaInputContent {
    /// Builds a media part from a source, with no metadata.
    pub fn new(source: InputContentSource) -> Self {
        Self {
            id: None,
            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()
    }

    /// The 1.0 media part this legacy part stands for: its inline data, or
    /// else its URL, under the modality its MIME type names, the file name
    /// kept as `metadata.filename`. `None` when it carries only an `id`,
    /// which no 1.0 source can express.
    #[cfg(any(feature = "client", feature = "axum"))]
    fn upgraded(&self) -> Option<InputContent> {
        let mime_type = self.mime_type.clone();
        let filled = |value: &Option<String>| value.clone().filter(|value| !value.is_empty());
        let source = if let Some(value) = filled(&self.data) {
            InputContentSource::Data { value, mime_type }
        } else {
            InputContentSource::Url {
                value: filled(&self.url)?,
                mime_type: Some(mime_type),
            }
        };
        let media = MediaInputContent {
            id: None,
            source,
            metadata: filled(&self.filename)
                .map(|filename| serde_json::json!({ "filename": filename })),
        };
        let modality = self.mime_type.split_once('/').map(|(kind, _)| kind);
        Some(match modality {
            Some(kind) if kind.eq_ignore_ascii_case("image") => InputContent::Image(media),
            Some(kind) if kind.eq_ignore_ascii_case("audio") => InputContent::Audio(media),
            Some(kind) if kind.eq_ignore_ascii_case("video") => InputContent::Video(media),
            _ => InputContent::Document(media),
        })
    }
}

/// Rewrites the legacy `binary` parts of a request's messages as the 1.0
/// media parts they stand for. AG-UI 1.0 retired the shape: a consumer
/// translates it rather than send what a 1.0 producer strips.
///
/// A legacy part that merely mirrors a media part already in the same message
/// is dropped. An id-only part is left for schema enforcement to remove with a warning.
#[cfg(feature = "client")]
pub(crate) fn upgrade_legacy_content(messages: &mut [Message]) {
    for message in messages {
        let parts = match message {
            Message::User(user) => match &mut user.content {
                UserContent::Parts(parts) => parts,
                UserContent::Text(_) => continue,
            },
            Message::Tool(tool) => match &mut tool.content {
                ToolContent::Parts(parts) => parts,
                ToolContent::Text(_) => continue,
            },
            _ => continue,
        };
        if !parts
            .iter()
            .any(|part| matches!(part, InputContent::Binary(_)))
        {
            continue;
        }
        let original = std::mem::take(parts);
        for part in &original {
            let InputContent::Binary(binary) = part else {
                parts.push(part.clone());
                continue;
            };
            match binary.upgraded() {
                // Matched against the parts as they arrived, so two legacy
                // parts with the same payload stay two.
                Some(media) if original.iter().any(|other| mirrors(other, &media, binary)) => {}
                Some(media) => parts.push(media),
                None => parts.push(part.clone()),
            }
        }
    }
}

/// The same translation on a wire event, before the boundary enforces the
/// schema, which would drop the part as unrecognised: the content of the
/// messages `MESSAGES_SNAPSHOT` and the `RUN_STARTED` input echo carry, and of
/// a `TOOL_CALL_RESULT`. Each translation is a warning naming the part.
#[cfg(feature = "client")]
pub(crate) fn upgrade_legacy_event_content(
    event: &mut Value,
    tag: &str,
    warnings: &mut Vec<String>,
) {
    let (messages, at) = match tag {
        "TOOL_CALL_RESULT" => {
            return upgrade_wire_parts(event.get_mut("content"), "/content", warnings);
        }
        "MESSAGES_SNAPSHOT" => (event.get_mut("messages"), "/messages"),
        "RUN_STARTED" => (event.pointer_mut("/input/messages"), "/input/messages"),
        _ => return,
    };
    upgrade_wire_messages(messages, at, warnings);
}

#[cfg(any(feature = "client", feature = "axum"))]
pub(crate) fn upgrade_wire_messages(
    messages: Option<&mut Value>,
    at: &str,
    warnings: &mut Vec<String>,
) {
    for (index, message) in messages
        .and_then(Value::as_array_mut)
        .into_iter()
        .flatten()
        .enumerate()
    {
        if matches!(
            message.get("role").and_then(Value::as_str),
            Some("user" | "tool")
        ) && message.get("content").is_some_and(Value::is_array)
        {
            let at = format!("{at}/{index}/content");
            upgrade_wire_parts(message.get_mut("content"), &at, warnings);
        }
    }
}

/// One content list on the wire. A part that is not a well-formed legacy
/// part is left for enforcement to judge.
#[cfg(any(feature = "client", feature = "axum"))]
fn upgrade_wire_parts(content: Option<&mut Value>, at: &str, warnings: &mut Vec<String>) {
    let Some(parts) = content.and_then(Value::as_array_mut) else {
        return;
    };
    let legacy = |part: &Value| -> Option<BinaryInputContent> {
        (part.get("type").and_then(Value::as_str) == Some("binary"))
            .then(|| serde_json::from_value(part.clone()).ok())
            .flatten()
    };
    if !parts.iter().any(|part| legacy(part).is_some()) {
        return;
    }
    let original = std::mem::take(parts);
    // What the list already holds in 1.0 form, for the mirror check.
    let modern: Vec<InputContent> = original
        .iter()
        .filter(|part| legacy(part).is_none())
        .filter_map(|part| serde_json::from_value(part.clone()).ok())
        .collect();
    for (index, part) in original.iter().enumerate() {
        let translated = legacy(part).and_then(|binary| {
            let media = binary.upgraded()?;
            Some((serde_json::to_value(&media).ok()?, media, binary))
        });
        let Some((wire, media, binary)) = translated else {
            parts.push(part.clone());
            continue;
        };
        let modality = wire.get("type").and_then(Value::as_str).unwrap_or("media");
        if modern.iter().any(|other| mirrors(other, &media, &binary)) {
            warnings.push(format!(
                "dropped retired binary content part at {at}/{index}: the {modality} part \
                 beside it carries the same payload"
            ));
        } else {
            warnings.push(format!(
                "translated retired binary content part at {at}/{index} to {modality}"
            ));
            parts.push(wire);
        }
    }
}

/// Whether `part` is the media part `media` was converted to, file name
/// included when the legacy part had one.
#[cfg(any(feature = "client", feature = "axum"))]
fn mirrors(part: &InputContent, media: &InputContent, legacy: &BinaryInputContent) -> bool {
    let (part, media) = match (part, media) {
        (InputContent::Image(part), InputContent::Image(media))
        | (InputContent::Audio(part), InputContent::Audio(media))
        | (InputContent::Video(part), InputContent::Video(media))
        | (InputContent::Document(part), InputContent::Document(media)) => (part, media),
        _ => return false,
    };
    let kept_name = part
        .metadata
        .as_ref()
        .and_then(|metadata| metadata.get("filename"))
        .and_then(Value::as_str);
    let same_mime = |a: &str, b: &str| {
        let (kind_a, params_a) = a.split_once(';').unwrap_or((a, ""));
        let (kind_b, params_b) = b.split_once(';').unwrap_or((b, ""));
        kind_a.eq_ignore_ascii_case(kind_b) && params_a == params_b
    };
    // A URL may omit MIME, while a retired binary part always carries it.
    // Discard the mirror only when the modern attachment retains that fact.
    let same_source = match (&part.source, &media.source) {
        (
            InputContentSource::Url {
                value: a,
                mime_type: Some(mime_a),
            },
            InputContentSource::Url {
                value: b,
                mime_type: Some(mime_b),
            },
        )
        | (
            InputContentSource::Data {
                value: a,
                mime_type: mime_a,
            },
            InputContentSource::Data {
                value: b,
                mime_type: mime_b,
            },
        ) => a == b && same_mime(mime_a, mime_b),
        _ => false,
    };
    same_source
        && legacy
            .filename
            .as_deref()
            .filter(|filename| !filename.is_empty())
            .is_none_or(|filename| kept_name == Some(filename))
}

/// 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(),
            ..Default::default()
        })
    }
}

/// 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)
    }
}

/// A tool result as plain text or an ordered list of text and media 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 ToolContent {
    /// Plain text, including structured data serialized by the tool.
    Text(String),
    /// Multimodal parts in their original order.
    Parts(Vec<InputContent>),
}

impl ToolContent {
    /// Borrows the payload when it is plain text.
    pub fn as_text(&self) -> Option<&str> {
        match self {
            Self::Text(text) => Some(text),
            Self::Parts(_) => None,
        }
    }

    /// Returns text portions, ignoring media parts.
    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 ToolContent {
    fn default() -> Self {
        Self::Text(String::new())
    }
}

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

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

impl From<Vec<InputContent>> for ToolContent {
    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, 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,
    /// Plain text or ordered multimodal parts returned by the tool.
    pub content: ToolContent,
    /// 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<ToolContent>,
    ) -> 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,
}