rig-a2a 0.47.8

Serve Rig agents over the Agent2Agent (A2A) protocol and call remote A2A agents as Rig tools, built on the official A2A Rust SDK.
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
//! A2A v0.3 compatibility, for peers that have not moved to v1.0 yet (such as
//! Strands Agents 1.x, which pins `a2a-sdk<0.4`).
//!
//! Serving: [`router`] answers v0.3 JSON-RPC (`message/send`,
//! `message/stream`, `tasks/get`, `tasks/cancel`) by translating each call to
//! the v1.0 request handler the v1.0 bindings use, so both versions share one
//! task store and one conversation history. The server publishes a v0.3 agent
//! card ([`card`]) under the same prefix, so a v0.3 client is pointed at
//! `{base}/v03`.
//!
//! Calling: [`send`] and [`stream`] post `message/send` and `message/stream`
//! to a v0.3 agent and read the answers as v1.0 events.
//!
//! The v0.3 wire shapes differ from v1.0 in names, not meaning: parts carry a
//! `kind` (`text`, `file`, `data`), states and roles are lowercase words, and
//! every object names its `kind`.

use std::sync::Arc;

use a2a::{
    A2AError, AgentCard, Artifact, CancelTaskRequest, GetTaskRequest, Message, Part, PartContent,
    Role, SendMessageConfiguration, SendMessageRequest, SendMessageResponse, StreamResponse, Task,
    TaskArtifactUpdateEvent, TaskState, TaskStatus, TaskStatusUpdateEvent,
};
use a2a_server::{DefaultRequestHandler, RequestHandler, ServiceParams};
use axum::extract::{Request, State};
use axum::http::{HeaderMap, HeaderValue};
use axum::middleware::{self, Next};
use axum::response::sse::{Event, Sse};
use axum::response::{IntoResponse, Response};
use axum::routing::post;
use axum::{Json, Router};
use base64::Engine;
use base64::engine::general_purpose::STANDARD as BASE64;
use futures::StreamExt;
use futures::stream::BoxStream;

use crate::client::read_capped;
use crate::server::{EXTENSIONS_HEADER, V03_EXTENSIONS_HEADER, activated_extensions};
use serde_json::{Value, json};

/// Where the v0.3 surface is mounted under the server's base URL.
pub const V03_PATH: &str = "/v03";

const INVALID_PARAMS: i32 = -32602;
const METHOD_NOT_FOUND: i32 = -32601;

// ---------------------------------------------------------------- serving --

/// The v0.3 JSON-RPC endpoint, at `/` relative to where it is nested. The
/// v0.3 card is routed by the server, outside the auth guard. `declared` is
/// the URIs of the extensions the card declares.
pub(crate) fn router(handler: Arc<DefaultRequestHandler>, declared: Arc<[String]>) -> Router {
    Router::new()
        .route("/", post(rpc))
        .with_state(handler)
        .layer(middleware::from_fn_with_state(declared, extensions))
}

/// Reads activation from the v0.3 `X-A2A-Extensions` header and echoes the
/// activated declared extensions in that header. The shared handler checks
/// activation only in the v1.0 header, so the v0.3 values are copied into it.
async fn extensions(
    State(declared): State<Arc<[String]>>,
    mut request: Request,
    next: Next,
) -> Response {
    let activated = activated_extensions(request.headers(), &V03_EXTENSIONS_HEADER, &declared);
    let copies: Vec<HeaderValue> = request
        .headers()
        .get_all(V03_EXTENSIONS_HEADER)
        .iter()
        .cloned()
        .collect();
    for value in copies {
        request.headers_mut().append(EXTENSIONS_HEADER, value);
    }
    let mut response = next.run(request).await;
    if let Ok(value) = HeaderValue::from_str(&activated.join(", "))
        && !activated.is_empty()
    {
        response.headers_mut().insert(V03_EXTENSIONS_HEADER, value);
    }
    response
}

/// The v0.3 agent card for a v1.0 one, served at `url`.
pub(crate) fn card(card: &AgentCard, url: &str, bearer: bool) -> Value {
    let skills: Vec<Value> = card
        .skills
        .iter()
        .map(|skill| {
            json!({
                "id": skill.id,
                "name": skill.name,
                "description": skill.description,
                "tags": skill.tags,
                "examples": skill.examples,
            })
        })
        .collect();
    let mut v03 = json!({
        "name": card.name,
        "description": card.description,
        "url": url,
        "version": card.version,
        "protocolVersion": "0.3.0",
        "preferredTransport": "JSONRPC",
        "capabilities": {
            "streaming": card.capabilities.streaming.unwrap_or(false),
            "pushNotifications": false,
        },
        "defaultInputModes": card.default_input_modes,
        "defaultOutputModes": card.default_output_modes,
        "skills": skills,
    });
    // The v0.3 card lists extensions in the same shape as v1.0 (uri, description,
    // required, params), under `capabilities`.
    let extensions = card
        .capabilities
        .extensions
        .as_deref()
        .filter(|extensions| !extensions.is_empty())
        .and_then(|extensions| serde_json::to_value(extensions).ok());
    if let (Some(capabilities), Some(extensions)) = (
        v03.get_mut("capabilities").and_then(Value::as_object_mut),
        extensions,
    ) {
        capabilities.insert("extensions".to_owned(), extensions);
    }
    with_present(
        v03,
        [
            (
                "securitySchemes",
                bearer.then(|| json!({"bearer": {"type": "http", "scheme": "bearer"}})),
            ),
            ("security", bearer.then(|| json!([{"bearer": []}]))),
        ],
    )
}

async fn rpc(
    State(handler): State<Arc<DefaultRequestHandler>>,
    headers: HeaderMap,
    Json(request): Json<Value>,
) -> Response {
    let id = request.get("id").cloned().unwrap_or(Value::Null);
    let params = service_params(&headers);
    let body = request.get("params").unwrap_or(&Value::Null);
    let method = request.get("method").and_then(Value::as_str);
    let result = match method.unwrap_or_default() {
        "message/send" => match send_request(body) {
            Ok(req) => handler
                .send_message(&params, req)
                .await
                .map(|response| match response {
                    SendMessageResponse::Task(task) => task_json(&task),
                    SendMessageResponse::Message(message) => message_json(&message),
                }),
            Err(error) => Err(error),
        },
        "message/stream" => {
            let stream = match send_request(body) {
                Ok(req) => handler.send_streaming_message(&params, req).await,
                Err(error) => Err(error),
            };
            return match stream {
                Ok(events) => Sse::new(events.map(move |event| {
                    let frame = match event {
                        Ok(event) => ok(&id, event_json(&event)),
                        Err(error) => err(&id, error.code, &error.message),
                    };
                    Ok::<_, std::convert::Infallible>(Event::default().data(frame.to_string()))
                }))
                .into_response(),
                Err(error) => Json(err(&id, error.code, &error.message)).into_response(),
            };
        }
        "tasks/get" => match task_id(body) {
            Ok(id) => handler
                .get_task(
                    &params,
                    GetTaskRequest {
                        id,
                        history_length: body["historyLength"].as_i64().map(|n| n as i32),
                        tenant: None,
                    },
                )
                .await
                .map(|task| task_json(&task)),
            Err(error) => Err(error),
        },
        "tasks/cancel" => match task_id(body) {
            Ok(id) => handler
                .cancel_task(
                    &params,
                    CancelTaskRequest {
                        id,
                        metadata: None,
                        tenant: None,
                    },
                )
                .await
                .map(|task| task_json(&task)),
            Err(error) => Err(error),
        },
        other => Err(A2AError::new(
            METHOD_NOT_FOUND,
            format!("method `{other}` not found"),
        )),
    };
    Json(match result {
        Ok(result) => ok(&id, result),
        Err(error) => err(&id, error.code, &error.message),
    })
    .into_response()
}

/// Request headers as the v1.0 handler reads them: lowercase names.
fn service_params(headers: &HeaderMap) -> ServiceParams {
    let mut params = ServiceParams::new();
    for (name, value) in headers {
        if let Ok(value) = value.to_str() {
            params
                .entry(name.as_str().to_owned())
                .or_default()
                .push(value.to_owned());
        }
    }
    params
}

fn send_request(params: &Value) -> Result<SendMessageRequest, A2AError> {
    let message = message_from_json(&params["message"])?;
    // v0.3 waits for the task to finish unless told `blocking: false`.
    let return_immediately = params
        .pointer("/configuration/blocking")
        .and_then(Value::as_bool)
        .map(|blocking| !blocking);
    Ok(SendMessageRequest {
        message,
        configuration: Some(SendMessageConfiguration {
            accepted_output_modes: None,
            task_push_notification_config: None,
            history_length: None,
            return_immediately,
        }),
        metadata: None,
        tenant: None,
    })
}

fn task_id(params: &Value) -> Result<String, A2AError> {
    params["id"]
        .as_str()
        .map(str::to_owned)
        .ok_or_else(|| invalid("`params.id` is required"))
}

fn ok(id: &Value, result: Value) -> Value {
    json!({"jsonrpc": "2.0", "id": id, "result": result})
}

fn err(id: &Value, code: i32, message: &str) -> Value {
    json!({"jsonrpc": "2.0", "id": id, "error": {"code": code, "message": message}})
}

fn invalid(message: impl Into<String>) -> A2AError {
    A2AError::new(INVALID_PARAMS, message)
}

// ------------------------------------------------------- v1.0 -> v0.3 JSON --

fn event_json(event: &StreamResponse) -> Value {
    match event {
        StreamResponse::Task(task) => task_json(task),
        StreamResponse::Message(message) => message_json(message),
        StreamResponse::StatusUpdate(update) => json!({
            "kind": "status-update",
            "taskId": update.task_id,
            "contextId": update.context_id,
            "status": status_json(&update.status),
            "final": update.status.state.is_terminal(),
        }),
        StreamResponse::ArtifactUpdate(update) => json!({
            "kind": "artifact-update",
            "taskId": update.task_id,
            "contextId": update.context_id,
            "artifact": artifact_json(&update.artifact),
            "append": update.append,
            "lastChunk": update.last_chunk,
        }),
    }
}

fn task_json(task: &Task) -> Value {
    let json = json!({
        "kind": "task",
        "id": task.id,
        "contextId": task.context_id,
        "status": status_json(&task.status),
    });
    let artifacts = task
        .artifacts
        .as_ref()
        .map(|artifacts| artifacts.iter().map(artifact_json).collect());
    let history = task
        .history
        .as_ref()
        .map(|history| history.iter().map(message_json).collect());
    with_present(json, [("artifacts", artifacts), ("history", history)])
}

fn status_json(status: &TaskStatus) -> Value {
    with_present(
        json!({"state": state_name(&status.state)}),
        [
            ("message", status.message.as_ref().map(message_json)),
            (
                "timestamp",
                status.timestamp.map(|at| json!(at.to_rfc3339())),
            ),
        ],
    )
}

fn artifact_json(artifact: &Artifact) -> Value {
    json!({
        "artifactId": artifact.artifact_id,
        "name": artifact.name,
        "description": artifact.description,
        "parts": artifact.parts.iter().map(part_json).collect::<Vec<_>>(),
    })
}

fn message_json(message: &Message) -> Value {
    let json = json!({
        "kind": "message",
        "messageId": message.message_id,
        "role": if message.role == Role::User { "user" } else { "agent" },
        "parts": message.parts.iter().map(part_json).collect::<Vec<_>>(),
    });
    with_present(
        json,
        [
            ("contextId", message.context_id.as_ref().map(|id| json!(id))),
            ("taskId", message.task_id.as_ref().map(|id| json!(id))),
        ],
    )
}

fn part_json(part: &Part) -> Value {
    let file = |source: (&str, Value)| {
        let file = with_present(
            json!({ source.0: source.1 }),
            [
                (
                    "mimeType",
                    part.media_type.as_ref().map(|media| json!(media)),
                ),
                ("name", part.filename.as_ref().map(|name| json!(name))),
            ],
        );
        json!({"kind": "file", "file": file})
    };
    match &part.content {
        PartContent::Text(text) => json!({"kind": "text", "text": text}),
        PartContent::Data(data) => json!({"kind": "data", "data": data}),
        PartContent::Raw(bytes) => file(("bytes", json!(BASE64.encode(bytes)))),
        PartContent::Url(url) => file(("uri", json!(url))),
    }
}

/// `object` with each of `fields` that has a value: v0.3 leaves an absent
/// field out rather than sending `null`.
fn with_present<const N: usize>(mut object: Value, fields: [(&str, Option<Value>); N]) -> Value {
    if let Value::Object(map) = &mut object {
        map.extend(
            fields
                .into_iter()
                .filter_map(|(name, value)| Some((name.to_owned(), value?))),
        );
    }
    object
}

pub(crate) fn state_name(state: &TaskState) -> &'static str {
    match state {
        TaskState::Submitted => "submitted",
        TaskState::Working => "working",
        TaskState::Completed => "completed",
        TaskState::Failed => "failed",
        TaskState::Canceled => "canceled",
        TaskState::InputRequired => "input-required",
        TaskState::Rejected => "rejected",
        TaskState::AuthRequired => "auth-required",
        _ => "unknown",
    }
}

fn state_from_name(name: &str) -> Option<TaskState> {
    Some(match name {
        "submitted" => TaskState::Submitted,
        "working" => TaskState::Working,
        "completed" => TaskState::Completed,
        "failed" => TaskState::Failed,
        "canceled" => TaskState::Canceled,
        "input-required" => TaskState::InputRequired,
        "rejected" => TaskState::Rejected,
        "auth-required" => TaskState::AuthRequired,
        _ => return None,
    })
}

// ------------------------------------------------------- v0.3 JSON -> v1.0 --

fn message_from_json(json: &Value) -> Result<Message, A2AError> {
    let role = match json["role"].as_str() {
        Some("user") => Role::User,
        Some("agent") => Role::Agent,
        _ => return Err(invalid("`message.role` must be `user` or `agent`")),
    };
    let parts = json["parts"]
        .as_array()
        .ok_or_else(|| invalid("`message.parts` must be an array"))?
        .iter()
        .map(part_from_json)
        .collect::<Result<Vec<_>, _>>()?;
    let mut message = Message::new(role, parts);
    if let Some(id) = json["messageId"].as_str() {
        message.message_id = id.to_owned();
    }
    message.context_id = json["contextId"].as_str().map(str::to_owned);
    message.task_id = json["taskId"].as_str().map(str::to_owned);
    Ok(message)
}

fn part_from_json(json: &Value) -> Result<Part, A2AError> {
    let (content, media_type, filename) = match json["kind"].as_str() {
        Some("text") => {
            let text = json["text"]
                .as_str()
                .ok_or_else(|| invalid("a text part needs `text`"))?;
            (PartContent::Text(text.to_owned()), None, None)
        }
        Some("data") => (PartContent::Data(json["data"].clone()), None, None),
        Some("file") => {
            let file = &json["file"];
            let content = if let Some(bytes) = file["bytes"].as_str() {
                PartContent::Raw(
                    BASE64
                        .decode(bytes)
                        .map_err(|e| invalid(format!("file bytes are not base64: {e}")))?,
                )
            } else if let Some(uri) = file["uri"].as_str() {
                PartContent::Url(uri.to_owned())
            } else {
                return Err(invalid("a file part needs `file.bytes` or `file.uri`"));
            };
            let media_type = file["mimeType"].as_str().map(str::to_owned);
            (
                content,
                media_type,
                file["name"].as_str().map(str::to_owned),
            )
        }
        other => return Err(invalid(format!("unknown part kind {other:?}"))),
    };
    let mut part = Part::text("");
    part.content = content;
    part.media_type = media_type;
    part.filename = filename;
    Ok(part)
}

// ---------------------------------------------------------------- calling --

/// Post `message/send` to a v0.3 agent and read its answer as a v1.0 task or message.
pub(crate) async fn send(
    http: &reqwest::Client,
    url: &str,
    bearer: Option<&str>,
    extensions: &[String],
    message: &Message,
) -> Result<StreamResponse, crate::RemoteError> {
    let params = json!({"message": message_json(message), "configuration": {"blocking": true}});
    let response = call(http, url, bearer, extensions, "message/send", params).await?;
    let Some(body) = read_capped(response, MAX_REPLY_BYTES).await? else {
        return Err(A2AError::new(
            INVALID_PARAMS,
            format!("reply longer than {MAX_REPLY_BYTES} bytes"),
        )
        .into());
    };
    let frame: Value = serde_json::from_slice(&body)
        .map_err(|e| A2AError::new(INVALID_PARAMS, format!("bad reply: {e}")))?;
    Ok(response_from_frame(&frame)?)
}

/// Post `message/stream` to a v0.3 agent and read its server-sent events as
/// v1.0 events.
pub(crate) async fn stream(
    http: &reqwest::Client,
    url: &str,
    bearer: Option<&str>,
    extensions: &[String],
    message: &Message,
) -> Result<BoxStream<'static, Result<StreamResponse, crate::RemoteError>>, crate::RemoteError> {
    let params = json!({"message": message_json(message)});
    let response = call(http, url, bearer, extensions, "message/stream", params).await?;
    let events = response
        .headers()
        .get(reqwest::header::CONTENT_TYPE)
        .and_then(|value| value.to_str().ok())
        .is_some_and(|value| value.starts_with("text/event-stream"));
    if !events {
        // A refusal, such as a missing required extension, comes back as one
        // JSON-RPC error, not as events. Surface it rather than an empty stream.
        let Some(body) = read_capped(response, MAX_REPLY_BYTES).await? else {
            return Err(A2AError::new(
                INVALID_PARAMS,
                format!("reply longer than {MAX_REPLY_BYTES} bytes"),
            )
            .into());
        };
        let frame: Value = serde_json::from_slice(&body)
            .map_err(|e| A2AError::new(INVALID_PARAMS, format!("bad reply: {e}")))?;
        let event = response_from_frame(&frame)?;
        return Ok(
            futures::stream::once(std::future::ready(Ok::<_, crate::RemoteError>(event))).boxed(),
        );
    }
    Ok(async_stream::try_stream! {
        let mut bytes = response.bytes_stream();
        let mut framer = SseFramer::default();
        while let Some(chunk) = bytes.next().await {
            for data in framer.push(&chunk?)? {
                let frame: Value = serde_json::from_str(&data)
                    .map_err(|e| A2AError::new(INVALID_PARAMS, format!("bad SSE frame: {e}")))?;
                yield response_from_frame(&frame)?;
            }
        }
    }
    .boxed())
}

/// Largest reply a v0.3 agent may send to `message/send`.
const MAX_REPLY_BYTES: usize = 16 * 1024 * 1024;

/// Largest event a v0.3 agent may send before its blank line. A longer one
/// ends the stream with an error instead of growing the buffer.
const MAX_PENDING_EVENT_BYTES: usize = 16 * 1024 * 1024;

/// Cuts a server-sent event stream into the data payloads of its events.
#[derive(Default)]
struct SseFramer {
    /// Bytes after the last complete event, without carriage returns.
    pending: Vec<u8>,
    /// How much of `pending` has already been searched for a blank line.
    scanned: usize,
}

impl SseFramer {
    /// Add one chunk of the stream; the data of each event it completes.
    fn push(&mut self, chunk: &[u8]) -> Result<Vec<String>, A2AError> {
        // JSON escapes carriage returns, so dropping them normalizes CRLF framing.
        self.pending
            .extend(chunk.iter().filter(|&&byte| byte != b'\r'));
        let mut events = Vec::new();
        loop {
            let from = self.scanned;
            let blank = self
                .pending
                .get(from..)
                .and_then(|tail| tail.windows(2).position(|pair| pair == b"\n\n"));
            match blank {
                Some(at) => {
                    let block: Vec<u8> = self.pending.drain(..from + at + 2).collect();
                    self.scanned = 0;
                    events.extend(sse_data(&block));
                }
                None => {
                    // The last byte may be the first half of a blank line.
                    self.scanned = self.pending.len().saturating_sub(1);
                    break;
                }
            }
        }
        if self.pending.len() > MAX_PENDING_EVENT_BYTES {
            return Err(A2AError::new(
                INVALID_PARAMS,
                format!("SSE event longer than {MAX_PENDING_EVENT_BYTES} bytes"),
            ));
        }
        Ok(events)
    }
}

async fn call(
    http: &reqwest::Client,
    url: &str,
    bearer: Option<&str>,
    extensions: &[String],
    method: &str,
    params: Value,
) -> Result<reqwest::Response, crate::RemoteError> {
    let body = json!({"jsonrpc": "2.0", "id": 1, "method": method, "params": params});
    let mut request = http.post(url).json(&body);
    if let Some(token) = bearer {
        request = request.bearer_auth(token);
    }
    if !extensions.is_empty() {
        request = request.header(V03_EXTENSIONS_HEADER, extensions.join(", "));
    }
    #[cfg(feature = "otel")]
    {
        let mut headers = HeaderMap::new();
        rig_otel::inject(&mut headers);
        request = request.headers(headers);
    }
    Ok(request.send().await?.error_for_status()?)
}

/// The `data:` lines of one server-sent event, joined; `None` for an event without data.
fn sse_data(block: &[u8]) -> Option<String> {
    let text = String::from_utf8_lossy(block);
    let lines: Vec<&str> = text
        .lines()
        .filter_map(|line| line.strip_prefix("data:"))
        .map(|data| data.strip_prefix(' ').unwrap_or(data))
        .collect();
    (!lines.is_empty()).then(|| lines.join("\n"))
}

fn response_from_frame(frame: &Value) -> Result<StreamResponse, A2AError> {
    if let Some(error) = frame.get("error") {
        // A code outside i32 from a remote agent falls back to the generic internal error.
        let code = error["code"]
            .as_i64()
            .and_then(|code| i32::try_from(code).ok())
            .unwrap_or(-32603);
        return Err(A2AError::new(
            code,
            error["message"].as_str().unwrap_or("unknown error"),
        ));
    }
    response_from_json(&frame["result"])
}

/// A v0.3 result or event as the v1.0 event it means.
fn response_from_json(json: &Value) -> Result<StreamResponse, A2AError> {
    let field = |name: &str| {
        json[name]
            .as_str()
            .map(str::to_owned)
            .ok_or_else(|| invalid(format!("`{name}` is required")))
    };
    Ok(match json["kind"].as_str() {
        Some("message") => StreamResponse::Message(message_from_json(json)?),
        Some("task") => StreamResponse::Task(Task {
            id: field("id")?,
            context_id: field("contextId")?,
            status: status_from_json(&json["status"])?,
            artifacts: match json["artifacts"].as_array() {
                Some(artifacts) => Some(
                    artifacts
                        .iter()
                        .map(artifact_from_json)
                        .collect::<Result<_, _>>()?,
                ),
                None => None,
            },
            history: None,
            metadata: None,
        }),
        Some("status-update") => StreamResponse::StatusUpdate(TaskStatusUpdateEvent {
            task_id: field("taskId")?,
            context_id: field("contextId")?,
            status: status_from_json(&json["status"])?,
            metadata: None,
        }),
        Some("artifact-update") => StreamResponse::ArtifactUpdate(TaskArtifactUpdateEvent {
            task_id: field("taskId")?,
            context_id: field("contextId")?,
            artifact: artifact_from_json(&json["artifact"])?,
            append: json["append"].as_bool(),
            last_chunk: json["lastChunk"].as_bool(),
            metadata: None,
        }),
        other => return Err(invalid(format!("unknown result kind {other:?}"))),
    })
}

fn status_from_json(json: &Value) -> Result<TaskStatus, A2AError> {
    Ok(TaskStatus {
        state: json["state"]
            .as_str()
            .and_then(state_from_name)
            .unwrap_or(TaskState::Unspecified),
        message: match json.get("message") {
            Some(message) if message.is_object() => Some(message_from_json(message)?),
            _ => None,
        },
        timestamp: json["timestamp"]
            .as_str()
            .and_then(|at| chrono::DateTime::parse_from_rfc3339(at).ok())
            .map(|at| at.with_timezone(&chrono::Utc)),
    })
}

fn artifact_from_json(json: &Value) -> Result<Artifact, A2AError> {
    Ok(Artifact {
        artifact_id: json["artifactId"].as_str().unwrap_or_default().to_owned(),
        name: json["name"].as_str().map(str::to_owned),
        description: json["description"].as_str().map(str::to_owned),
        parts: json["parts"]
            .as_array()
            .into_iter()
            .flatten()
            .map(part_from_json)
            .collect::<Result<_, _>>()?,
        metadata: None,
        extensions: None,
    })
}

#[cfg(test)]
mod tests;