polyc-a2a 2026.8.3

polychrome A2A edge: serves a domain-signed Agent Card and drives message/send tasks onto a turn.
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
//! A2A **v1.0** (`lf.a2a.v1`) wire types — the `ProtoJSON` shape.
//!
//! These mirror the canonical Rust SDK (`a2aproject/a2a-rs`) byte-for-byte so
//! the edge interops with any v1.0 peer:
//!
//! - enums serialize as `ProtoJSON` `SCREAMING_SNAKE` strings
//!   (`TASK_STATE_WORKING`, `ROLE_USER`) — not `working`/`user`;
//! - polymorphic types ([`Part`], [`SendMessageResponse`]) are **field-presence
//!   unions** with NO `kind`/`type` discriminator — the variant is the key that
//!   is present (`{"text":…}`, `{"task":…}`);
//! - every field is **camelCase**.
//!
//! The exact wire is pinned by the golden tests at the bottom of this file.

use std::collections::HashMap;
use std::fmt;

use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64};
use serde::de::{self, IgnoredAny, MapAccess, Visitor};
use serde::ser::SerializeMap;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use serde_json::Value;

/// The author of a [`Message`]. Wire = `ProtoJSON` `ROLE_*`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Role {
    /// Unset (the proto zero value); also what an unknown wire string decodes to.
    #[default]
    Unspecified,
    /// The calling peer / user.
    User,
    /// This agent.
    Agent,
}

impl Role {
    const fn as_wire(self) -> &'static str {
        match self {
            Self::Unspecified => "ROLE_UNSPECIFIED",
            Self::User => "ROLE_USER",
            Self::Agent => "ROLE_AGENT",
        }
    }
}

impl Serialize for Role {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(self.as_wire())
    }
}

impl<'de> Deserialize<'de> for Role {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        // `ProtoJSON` enums are forward-compatible: an unknown (or empty) string
        // decodes to the zero value rather than erroring.
        Ok(match String::deserialize(deserializer)?.as_str() {
            "ROLE_USER" => Self::User,
            "ROLE_AGENT" => Self::Agent,
            _ => Self::Unspecified,
        })
    }
}

/// The A2A task lifecycle state. Wire = `ProtoJSON` `TASK_STATE_*`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum TaskState {
    /// Unset (proto zero); also what an unknown wire string decodes to.
    #[default]
    Unspecified,
    /// Accepted, not yet started.
    Submitted,
    /// The turn is running.
    Working,
    /// Finished successfully.
    Completed,
    /// Finished unsuccessfully.
    Failed,
    /// Cancelled by the caller (note the single `L`, per the proto).
    Canceled,
    /// Paused awaiting a human decision (an approval gate).
    InputRequired,
    /// The agent declined the task.
    Rejected,
    /// Paused awaiting authentication.
    AuthRequired,
}

impl TaskState {
    const fn as_wire(self) -> &'static str {
        match self {
            Self::Unspecified => "TASK_STATE_UNSPECIFIED",
            Self::Submitted => "TASK_STATE_SUBMITTED",
            Self::Working => "TASK_STATE_WORKING",
            Self::Completed => "TASK_STATE_COMPLETED",
            Self::Failed => "TASK_STATE_FAILED",
            Self::Canceled => "TASK_STATE_CANCELED",
            Self::InputRequired => "TASK_STATE_INPUT_REQUIRED",
            Self::Rejected => "TASK_STATE_REJECTED",
            Self::AuthRequired => "TASK_STATE_AUTH_REQUIRED",
        }
    }

    /// Whether this is a terminal state (the task is finished and a stream over
    /// it must close). `INPUT_REQUIRED`/`AUTH_REQUIRED` are interrupted, NOT
    /// terminal.
    #[must_use]
    pub const fn is_terminal(self) -> bool {
        matches!(
            self,
            Self::Completed | Self::Failed | Self::Canceled | Self::Rejected
        )
    }
}

impl Serialize for TaskState {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(self.as_wire())
    }
}

impl<'de> Deserialize<'de> for TaskState {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        Ok(match String::deserialize(deserializer)?.as_str() {
            "TASK_STATE_SUBMITTED" => Self::Submitted,
            "TASK_STATE_WORKING" => Self::Working,
            "TASK_STATE_COMPLETED" => Self::Completed,
            "TASK_STATE_FAILED" => Self::Failed,
            "TASK_STATE_CANCELED" => Self::Canceled,
            "TASK_STATE_INPUT_REQUIRED" => Self::InputRequired,
            "TASK_STATE_REJECTED" => Self::Rejected,
            "TASK_STATE_AUTH_REQUIRED" => Self::AuthRequired,
            _ => Self::Unspecified,
        })
    }
}

/// The content of a [`Part`] — a field-presence union (the variant is the key
/// present on the wire; there is no `kind` discriminator).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PartContent {
    /// A text segment (`{"text": …}`).
    Text(String),
    /// Inline file bytes, base64 (STANDARD) on the wire (`{"raw": …}`).
    Raw(Vec<u8>),
    /// A file by reference (`{"url": …}`).
    Url(String),
    /// Arbitrary structured JSON (`{"data": …}`).
    Data(Value),
}

/// One content part of a [`Message`] or [`Artifact`]. The content union plus
/// flat `filename`/`mediaType` siblings (no nested `file` object).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Part {
    /// The part's content.
    pub content: PartContent,
    /// File name, when this part is a file.
    pub filename: Option<String>,
    /// Media (MIME) type — the wire field is `mediaType`, not `mimeType`.
    pub media_type: Option<String>,
}

impl Part {
    /// A plain text part.
    #[must_use]
    pub fn text(text: impl Into<String>) -> Self {
        Self {
            content: PartContent::Text(text.into()),
            filename: None,
            media_type: None,
        }
    }

    /// The text of a text part (`None` for non-text parts).
    #[must_use]
    pub fn as_text(&self) -> Option<&str> {
        match &self.content {
            PartContent::Text(t) => Some(t),
            _ => None,
        }
    }
}

impl Serialize for Part {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let mut map = serializer.serialize_map(None)?;
        match &self.content {
            PartContent::Text(t) => map.serialize_entry("text", t)?,
            PartContent::Raw(r) => map.serialize_entry("raw", &BASE64.encode(r))?,
            PartContent::Url(u) => map.serialize_entry("url", u)?,
            PartContent::Data(d) => map.serialize_entry("data", d)?,
        }
        if let Some(filename) = &self.filename {
            map.serialize_entry("filename", filename)?;
        }
        if let Some(media_type) = &self.media_type {
            map.serialize_entry("mediaType", media_type)?;
        }
        map.end()
    }
}

impl<'de> Deserialize<'de> for Part {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        struct PartVisitor;
        impl<'de> Visitor<'de> for PartVisitor {
            type Value = Part;
            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.write_str("an A2A Part object with one of text/raw/url/data")
            }
            fn visit_map<M: MapAccess<'de>>(self, mut map: M) -> Result<Part, M::Error> {
                let mut content: Option<PartContent> = None;
                let mut filename = None;
                let mut media_type = None;
                while let Some(key) = map.next_key::<String>()? {
                    match key.as_str() {
                        "text" => content = Some(PartContent::Text(map.next_value()?)),
                        "raw" => {
                            let b64: String = map.next_value()?;
                            let bytes = BASE64.decode(b64).map_err(de::Error::custom)?;
                            content = Some(PartContent::Raw(bytes));
                        }
                        "url" => content = Some(PartContent::Url(map.next_value()?)),
                        "data" => content = Some(PartContent::Data(map.next_value()?)),
                        "filename" => filename = Some(map.next_value()?),
                        "mediaType" => media_type = Some(map.next_value()?),
                        // Forward-compatible: ignore unknown siblings (metadata, …).
                        _ => {
                            map.next_value::<IgnoredAny>()?;
                        }
                    }
                }
                let content = content.ok_or_else(|| {
                    de::Error::custom("Part has no content key (text/raw/url/data)")
                })?;
                Ok(Part {
                    content,
                    filename,
                    media_type,
                })
            }
        }
        deserializer.deserialize_map(PartVisitor)
    }
}

/// An A2A message.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
// `messageId` is the spec wire name; the struct-name prefix is mandated.
#[allow(clippy::struct_field_names)]
pub struct Message {
    /// Stable message id. Tolerated-absent on input; always set on output.
    #[serde(default)]
    pub message_id: String,
    /// The conversation/context id this message belongs to.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub context_id: Option<String>,
    /// The task id this message belongs to.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub task_id: Option<String>,
    /// The author.
    #[serde(default)]
    pub role: Role,
    /// Ordered content parts.
    #[serde(default)]
    pub parts: Vec<Part>,
    /// Free-form metadata.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub metadata: Option<HashMap<String, Value>>,
}

impl Message {
    /// All text parts joined with newlines (non-text parts ignored).
    #[must_use]
    pub fn text(&self) -> String {
        self.parts
            .iter()
            .filter_map(Part::as_text)
            .collect::<Vec<_>>()
            .join("\n")
    }
}

/// A task status snapshot.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TaskStatus {
    /// The lifecycle state.
    #[serde(default)]
    pub state: TaskState,
    /// The agent message attached to this status (the reply, approval prompt, or
    /// failure summary).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub message: Option<Message>,
    /// RFC-3339 UTC instant (ending in `Z`). Optional in v1.0; left unset here
    /// until a date dependency lands (populating it is a trivial follow-up).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub timestamp: Option<String>,
}

/// An A2A task.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Task {
    /// The task id.
    #[serde(default)]
    pub id: String,
    /// The conversation/context id.
    #[serde(default)]
    pub context_id: String,
    /// The current status.
    #[serde(default)]
    pub status: TaskStatus,
    /// Generated outputs.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub artifacts: Option<Vec<Artifact>>,
    /// The message history.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub history: Option<Vec<Message>>,
    /// Free-form metadata.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub metadata: Option<HashMap<String, Value>>,
}

/// A generated output attached to a [`Task`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
// `artifactId` is the spec wire name; the struct-name prefix is mandated.
#[allow(clippy::struct_field_names)]
pub struct Artifact {
    /// Stable artifact id.
    #[serde(default)]
    pub artifact_id: String,
    /// Human-readable name.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Human-readable description.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// The artifact's content parts.
    #[serde(default)]
    pub parts: Vec<Part>,
    /// Free-form metadata.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub metadata: Option<HashMap<String, Value>>,
}

/// The result of `SendMessage` — a field-presence union: `{"task": …}` when the
/// work produced a task, or `{"message": …}` for an immediate message reply.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SendMessageResponse {
    /// The work was tracked as a task.
    Task(Task),
    /// An immediate message reply (no task).
    Message(Message),
}

impl Serialize for SendMessageResponse {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let mut map = serializer.serialize_map(Some(1))?;
        match self {
            Self::Task(task) => map.serialize_entry("task", task)?,
            Self::Message(message) => map.serialize_entry("message", message)?,
        }
        map.end()
    }
}

impl<'de> Deserialize<'de> for SendMessageResponse {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let value = Value::deserialize(deserializer)?;
        if let Some(task) = value.get("task") {
            return Task::deserialize(task.clone())
                .map(Self::Task)
                .map_err(de::Error::custom);
        }
        if let Some(message) = value.get("message") {
            return Message::deserialize(message.clone())
                .map(Self::Message)
                .map_err(de::Error::custom);
        }
        Err(de::Error::custom(
            "SendMessageResponse has neither `task` nor `message`",
        ))
    }
}

/// One `SendStreamingMessage` SSE event's `result` payload.
///
/// A field-presence union like [`SendMessageResponse`]: the variant is the
/// key present on the wire (`{"task":…}` / `{"statusUpdate":…}` /
/// `{"artifactUpdate":…}`).
///
/// A streaming call emits, in order: one [`Self::Task`] (the `submitted`
/// snapshot), zero or more [`Self::ArtifactUpdate`]s (streamed text chunks),
/// then exactly one terminal [`Self::StatusUpdate`] with
/// [`TaskStatusUpdateEvent::is_final`] set, at which point the SSE stream
/// closes.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum StreamResponse {
    /// The initial `submitted` task snapshot.
    Task(Task),
    /// A status transition (`working`, then the terminal/interrupted state).
    StatusUpdate(TaskStatusUpdateEvent),
    /// An incremental artifact chunk (streamed assistant text).
    ArtifactUpdate(TaskArtifactUpdateEvent),
}

impl Serialize for StreamResponse {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let mut map = serializer.serialize_map(Some(1))?;
        match self {
            Self::Task(task) => map.serialize_entry("task", task)?,
            Self::StatusUpdate(update) => map.serialize_entry("statusUpdate", update)?,
            Self::ArtifactUpdate(update) => map.serialize_entry("artifactUpdate", update)?,
        }
        map.end()
    }
}

impl<'de> Deserialize<'de> for StreamResponse {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let value = Value::deserialize(deserializer)?;
        if let Some(task) = value.get("task") {
            return Task::deserialize(task.clone())
                .map(Self::Task)
                .map_err(de::Error::custom);
        }
        if let Some(update) = value.get("statusUpdate") {
            return TaskStatusUpdateEvent::deserialize(update.clone())
                .map(Self::StatusUpdate)
                .map_err(de::Error::custom);
        }
        if let Some(update) = value.get("artifactUpdate") {
            return TaskArtifactUpdateEvent::deserialize(update.clone())
                .map(Self::ArtifactUpdate)
                .map_err(de::Error::custom);
        }
        Err(de::Error::custom(
            "StreamResponse has none of `task`/`statusUpdate`/`artifactUpdate`",
        ))
    }
}

/// A task status transition streamed over `SendStreamingMessage`/
/// `TaskSubscription`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
// `taskId`/`contextId` are the spec wire names; the struct-name prefix is mandated.
#[allow(clippy::struct_field_names)]
pub struct TaskStatusUpdateEvent {
    /// The task this update belongs to.
    pub task_id: String,
    /// The conversation/context id.
    pub context_id: String,
    /// The new status.
    pub status: TaskStatus,
    /// Whether this is the last event in the stream — set on a terminal
    /// (`completed`/`failed`/`canceled`/`rejected`) or interrupted
    /// (`input-required`/`auth-required`) status; `false` for an
    /// intermediate `working` transition.
    #[serde(rename = "final")]
    pub is_final: bool,
}

/// An incremental artifact chunk streamed over `SendStreamingMessage`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
// `taskId`/`contextId` are the spec wire names; the struct-name prefix is mandated.
#[allow(clippy::struct_field_names)]
pub struct TaskArtifactUpdateEvent {
    /// The task this artifact belongs to.
    pub task_id: String,
    /// The conversation/context id.
    pub context_id: String,
    /// The artifact chunk's content.
    pub artifact: Artifact,
    /// Whether `artifact`'s parts append to a previously streamed chunk with
    /// the same `artifactId`, rather than starting a new artifact. Omitted
    /// (treated as `false`) for the first chunk of an artifact.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub append: Option<bool>,
    /// Whether this is the last chunk of `artifact`. Left unset by this edge —
    /// it only knows a chunk was final in hindsight, once the stream has
    /// already closed via the terminal [`TaskStatusUpdateEvent`] — so it never
    /// asserts a value it cannot back up.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_chunk: Option<bool>,
}

#[cfg(test)]
mod tests {
    #![allow(clippy::pedantic, clippy::nursery, missing_docs)]

    use super::*;
    use serde_json::json;

    // Golden conformance: the exact `ProtoJSON` strings a v1.0 peer (and a2a-rs)
    // emit. If any of these change, interop breaks.

    #[test]
    fn role_wire_is_screaming_snake() {
        assert_eq!(
            serde_json::to_string(&Role::User).unwrap(),
            r#""ROLE_USER""#
        );
        assert_eq!(
            serde_json::to_string(&Role::Agent).unwrap(),
            r#""ROLE_AGENT""#
        );
        assert_eq!(
            serde_json::from_str::<Role>(r#""ROLE_AGENT""#).unwrap(),
            Role::Agent
        );
        // Forward-compatible: unknown/empty → Unspecified.
        assert_eq!(
            serde_json::from_str::<Role>(r#""ROLE_FUTURE""#).unwrap(),
            Role::Unspecified
        );
    }

    #[test]
    fn task_state_wire_is_screaming_snake() {
        assert_eq!(
            serde_json::to_string(&TaskState::Working).unwrap(),
            r#""TASK_STATE_WORKING""#
        );
        assert_eq!(
            serde_json::to_string(&TaskState::Completed).unwrap(),
            r#""TASK_STATE_COMPLETED""#
        );
        // Single-L "CANCELED".
        assert_eq!(
            serde_json::to_string(&TaskState::Canceled).unwrap(),
            r#""TASK_STATE_CANCELED""#
        );
        assert_eq!(
            serde_json::to_string(&TaskState::InputRequired).unwrap(),
            r#""TASK_STATE_INPUT_REQUIRED""#
        );
        assert_eq!(
            serde_json::from_str::<TaskState>(r#""TASK_STATE_INPUT_REQUIRED""#).unwrap(),
            TaskState::InputRequired
        );
    }

    #[test]
    fn terminal_states() {
        assert!(TaskState::Completed.is_terminal());
        assert!(TaskState::Canceled.is_terminal());
        assert!(!TaskState::Working.is_terminal());
        assert!(!TaskState::InputRequired.is_terminal());
    }

    #[test]
    fn part_is_field_presence_no_kind() {
        let text = Part::text("hello");
        assert_eq!(
            serde_json::to_value(&text).unwrap(),
            json!({ "text": "hello" })
        );
        // round-trips
        let back: Part = serde_json::from_value(json!({ "text": "hello" })).unwrap();
        assert_eq!(back, text);

        // raw → STANDARD base64, with flat filename/mediaType siblings.
        let raw = Part {
            content: PartContent::Raw(vec![0, 1, 2, 3]),
            filename: Some("x.bin".to_owned()),
            media_type: Some("application/octet-stream".to_owned()),
        };
        assert_eq!(
            serde_json::to_value(&raw).unwrap(),
            json!({ "raw": "AAECAw==", "filename": "x.bin", "mediaType": "application/octet-stream" })
        );

        let data = Part {
            content: PartContent::Data(json!({ "k": 1 })),
            filename: None,
            media_type: None,
        };
        assert_eq!(
            serde_json::to_value(&data).unwrap(),
            json!({ "data": { "k": 1 } })
        );

        // No content key → error.
        assert!(serde_json::from_value::<Part>(json!({ "filename": "x" })).is_err());
    }

    #[test]
    fn message_is_camel_case_no_kind() {
        let msg = Message {
            message_id: "m1".to_owned(),
            context_id: Some("c1".to_owned()),
            task_id: None,
            role: Role::User,
            parts: vec![Part::text("hi")],
            metadata: None,
        };
        let value = serde_json::to_value(&msg).unwrap();
        assert_eq!(
            value,
            json!({
                "messageId": "m1",
                "contextId": "c1",
                "role": "ROLE_USER",
                "parts": [{ "text": "hi" }]
            })
        );
        assert!(value.get("kind").is_none(), "v1.0 messages carry no `kind`");
        assert_eq!(serde_json::from_value::<Message>(value).unwrap(), msg);
    }

    #[test]
    fn task_and_status_shape() {
        let task = Task {
            id: "t1".to_owned(),
            context_id: "c1".to_owned(),
            status: TaskStatus {
                state: TaskState::Completed,
                message: Some(Message {
                    message_id: "r1".to_owned(),
                    context_id: Some("c1".to_owned()),
                    task_id: Some("t1".to_owned()),
                    role: Role::Agent,
                    parts: vec![Part::text("the answer is 42")],
                    metadata: None,
                }),
                timestamp: None,
            },
            artifacts: None,
            history: None,
            metadata: None,
        };
        let value = serde_json::to_value(&task).unwrap();
        assert_eq!(value["id"], "t1");
        assert_eq!(value["contextId"], "c1");
        assert_eq!(value["status"]["state"], "TASK_STATE_COMPLETED");
        assert_eq!(
            value["status"]["message"]["parts"][0]["text"],
            "the answer is 42"
        );
        assert!(value.get("kind").is_none(), "v1.0 tasks carry no `kind`");
        assert_eq!(serde_json::from_value::<Task>(value).unwrap(), task);
    }

    #[test]
    fn send_message_response_is_wrapped_oneof() {
        let task = Task {
            id: "t1".to_owned(),
            context_id: "c1".to_owned(),
            status: TaskStatus {
                state: TaskState::Completed,
                message: None,
                timestamp: None,
            },
            artifacts: None,
            history: None,
            metadata: None,
        };
        let resp = SendMessageResponse::Task(task.clone());
        let value = serde_json::to_value(&resp).unwrap();
        assert_eq!(value["task"]["id"], "t1");
        assert!(value.get("message").is_none());
        assert_eq!(
            serde_json::from_value::<SendMessageResponse>(value).unwrap(),
            resp
        );
    }

    // Golden conformance for the streaming wire types (`#371`): pins the exact
    // shape a `SendStreamingMessage` SSE event's `result` takes.

    #[test]
    fn status_update_event_is_camel_case_with_final_keyword() {
        let update = TaskStatusUpdateEvent {
            task_id: "t1".to_owned(),
            context_id: "c1".to_owned(),
            status: TaskStatus {
                state: TaskState::Working,
                message: None,
                timestamp: None,
            },
            is_final: false,
        };
        let value = serde_json::to_value(&update).unwrap();
        assert_eq!(
            value,
            json!({
                "taskId": "t1",
                "contextId": "c1",
                "status": { "state": "TASK_STATE_WORKING" },
                "final": false,
            })
        );
        assert_eq!(
            serde_json::from_value::<TaskStatusUpdateEvent>(value).unwrap(),
            update
        );
    }

    #[test]
    fn artifact_update_event_omits_absent_append_and_last_chunk() {
        let update = TaskArtifactUpdateEvent {
            task_id: "t1".to_owned(),
            context_id: "c1".to_owned(),
            artifact: Artifact {
                artifact_id: "a1".to_owned(),
                name: None,
                description: None,
                parts: vec![Part::text("chunk one")],
                metadata: None,
            },
            append: None,
            last_chunk: None,
        };
        let value = serde_json::to_value(&update).unwrap();
        assert_eq!(
            value,
            json!({
                "taskId": "t1",
                "contextId": "c1",
                "artifact": { "artifactId": "a1", "parts": [{ "text": "chunk one" }] },
            })
        );
        assert!(value.get("append").is_none());
        assert!(value.get("lastChunk").is_none());
        assert_eq!(
            serde_json::from_value::<TaskArtifactUpdateEvent>(value).unwrap(),
            update
        );

        // A subsequent chunk sets `append: true`.
        let next = TaskArtifactUpdateEvent {
            append: Some(true),
            ..update
        };
        assert_eq!(serde_json::to_value(&next).unwrap()["append"], true);
    }

    #[test]
    fn stream_response_is_wrapped_oneof_over_all_three_variants() {
        let task = Task {
            id: "t1".to_owned(),
            context_id: "c1".to_owned(),
            status: TaskStatus::default(),
            artifacts: None,
            history: None,
            metadata: None,
        };
        let task_value = serde_json::to_value(StreamResponse::Task(task.clone())).unwrap();
        assert_eq!(task_value["task"]["id"], "t1");
        assert!(task_value.get("statusUpdate").is_none());
        assert!(task_value.get("artifactUpdate").is_none());
        assert_eq!(
            serde_json::from_value::<StreamResponse>(task_value).unwrap(),
            StreamResponse::Task(task)
        );

        let status = TaskStatusUpdateEvent {
            task_id: "t1".to_owned(),
            context_id: "c1".to_owned(),
            status: TaskStatus {
                state: TaskState::Completed,
                message: None,
                timestamp: None,
            },
            is_final: true,
        };
        let status_value =
            serde_json::to_value(StreamResponse::StatusUpdate(status.clone())).unwrap();
        assert_eq!(status_value["statusUpdate"]["final"], true);
        assert_eq!(
            serde_json::from_value::<StreamResponse>(status_value).unwrap(),
            StreamResponse::StatusUpdate(status)
        );

        let artifact_update = TaskArtifactUpdateEvent {
            task_id: "t1".to_owned(),
            context_id: "c1".to_owned(),
            artifact: Artifact {
                artifact_id: "a1".to_owned(),
                name: None,
                description: None,
                parts: vec![Part::text("hi")],
                metadata: None,
            },
            append: None,
            last_chunk: None,
        };
        let artifact_value =
            serde_json::to_value(StreamResponse::ArtifactUpdate(artifact_update.clone())).unwrap();
        assert_eq!(artifact_value["artifactUpdate"]["taskId"], "t1");
        assert_eq!(
            serde_json::from_value::<StreamResponse>(artifact_value).unwrap(),
            StreamResponse::ArtifactUpdate(artifact_update)
        );

        assert!(
            serde_json::from_value::<StreamResponse>(json!({})).is_err(),
            "an empty object matches none of the three variants"
        );
    }

    #[test]
    fn decodes_protojson_omitted_default_fields() {
        // A strict ProtoJSON peer omits zero-valued fields; we must still decode
        // them to their proto zero rather than failing on "missing field".
        let task: Task = serde_json::from_value(json!({ "id": "t" })).unwrap();
        assert_eq!(task.context_id, "");
        assert_eq!(task.status.state, TaskState::Unspecified);
        assert!(task.artifacts.is_none());

        let msg: Message = serde_json::from_value(json!({ "messageId": "m" })).unwrap();
        assert_eq!(msg.role, Role::Unspecified);
        assert!(msg.parts.is_empty());
    }
}