adk-server 3.0.0

HTTP server for ADK-Rust agents: REST and SSE, A2A v1.0, background runs and cron, approvals, and the AWP agent edge
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
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
use crate::a2a::{
    A2aClient, Part as A2aPart, Role, TaskArtifactUpdateEvent, TaskStatusUpdateEvent, UpdateEvent,
};
use adk_core::{Agent, Content, Event, EventStream, InvocationContext, Part, Result};
use async_trait::async_trait;
use std::sync::Arc;

/// Configuration for a remote A2A agent
#[derive(Clone)]
pub struct RemoteA2aConfig {
    /// Name of the agent
    pub name: String,
    /// Description of the agent
    pub description: String,
    /// Base URL of the remote agent, such as `http://localhost:8080`.
    ///
    /// The agent card is fetched from `{agent_url}/.well-known/agent-card.json`,
    /// falling back to `{agent_url}/.well-known/agent.json` when that returns 404.
    pub agent_url: String,
    /// Whether to use streaming for communication.
    /// If `None`, the agent uses streaming if the remote agent supports it.
    pub streaming: Option<bool>,
    /// Mints the bearer token sent to the remote agent, for the running agent's
    /// [`ActingContext`](adk_core::ActingContext) and with `agent_url` as the resource.
    /// `None` sends no credential.
    pub credential_broker: Option<Arc<dyn adk_core::CredentialBroker>>,
    /// Scopes requested from the [`credential_broker`](Self::credential_broker).
    pub credential_scopes: Vec<String>,
    /// Origins besides `agent_url`'s own that the agent card may name as its endpoint;
    /// see [`check_card_endpoint`](crate::a2a::client::check_card_endpoint). Empty by
    /// default, so a card naming another origin is refused.
    pub allowed_endpoint_origins: Vec<String>,
}

/// Mints a token for `acting` at `resource` with `scopes`.
async fn brokered_token(
    broker: &dyn adk_core::CredentialBroker,
    acting: &adk_core::ActingContext,
    resource: &str,
    scopes: &[String],
) -> Result<adk_core::ScopedToken> {
    let resource = adk_core::resource_indicator(resource)?;
    broker.token_for(acting, &resource, scopes).await
}

/// An agent that communicates with a remote A2A agent
pub struct RemoteA2aAgent {
    config: RemoteA2aConfig,
}

impl RemoteA2aAgent {
    pub fn new(config: RemoteA2aConfig) -> Self {
        Self { config }
    }

    pub fn builder(name: impl Into<String>) -> RemoteA2aAgentBuilder {
        RemoteA2aAgentBuilder::new(name)
    }
}

#[async_trait]
impl Agent for RemoteA2aAgent {
    fn name(&self) -> &str {
        &self.config.name
    }

    fn description(&self) -> &str {
        &self.config.description
    }

    fn sub_agents(&self) -> &[Arc<dyn Agent>] {
        &[]
    }

    async fn run(&self, ctx: Arc<dyn InvocationContext>) -> Result<EventStream> {
        let url = self.config.agent_url.clone();
        let invocation_id = ctx.invocation_id().to_string();
        let agent_name = self.config.name.clone();
        let config_streaming = self.config.streaming;
        let broker = self.config.credential_broker.clone();
        let scopes = self.config.credential_scopes.clone();
        let allowed_origins = self.config.allowed_endpoint_origins.clone();
        let acting = ctx.acting_context();

        // Get user content from context
        let user_content = get_user_content_from_context(ctx.as_ref());

        let stream = async_stream::stream! {
            // Create A2A client from a card whose endpoint is on an expected origin
            let mut client = match A2aClient::resolve_agent_card_allowing(&url, &allowed_origins).await {
                Ok(card) => A2aClient::new(card),
                Err(e) => {
                    yield Ok(create_error_event(&invocation_id, &agent_name, &e.to_string()));
                    return;
                }
            };
            // The token's audience is the configured agent URL, so a card pointing the
            // endpoint at another host cannot receive it.
            if let Some(broker) = broker.as_deref() {
                match brokered_token(broker, &acting, &url, &scopes).await {
                    Ok(token) => client = client.with_credential(token),
                    Err(e) => {
                        yield Ok(create_error_event(&invocation_id, &agent_name, &e.to_string()));
                        return;
                    }
                }
            }

            // Determine if we should use streaming
            let use_streaming = config_streaming.unwrap_or(client.agent_card().capabilities.streaming);

            // Build message from user content
            let message = build_a2a_message(user_content);

            if use_streaming {
                // Send streaming message
                match client.send_streaming_message(message).await {
                    Ok(mut event_stream) => {
                        use futures::StreamExt;
                        while let Some(result) = event_stream.next().await {
                            match result {
                                Ok(update_event) => {
                                    if let Some(event) = convert_update_event(&invocation_id, &agent_name, update_event) {
                                        yield Ok(event);
                                    }
                                }
                                Err(e) => {
                                    yield Ok(create_error_event(&invocation_id, &agent_name, &e.to_string()));
                                    return;
                                }
                            }
                        }
                    }
                    Err(e) => {
                        yield Ok(create_error_event(&invocation_id, &agent_name, &e.to_string()));
                    }
                }
            } else {
                // Send non-streaming message
                match client.send_message(message).await {
                    Ok(rpc_response) => {
                        if let Some(result) = rpc_response.result {
                            match serde_json::from_value::<crate::a2a::Task>(result) {
                                Ok(task) => {
                                    for event in convert_task_to_events(&invocation_id, &agent_name, task) {
                                        yield Ok(event);
                                    }
                                }
                                Err(e) => {
                                    yield Ok(create_error_event(&invocation_id, &agent_name, &format!("failed to parse response: {e}")));
                                }
                            }
                        } else if let Some(error) = rpc_response.error {
                            yield Ok(create_error_event(&invocation_id, &agent_name, &format!("RPC error: {} ({})", error.message, error.code)));
                        }
                    }
                    Err(e) => {
                        yield Ok(create_error_event(&invocation_id, &agent_name, &e.to_string()));
                    }
                }
            }
        };

        Ok(Box::pin(stream))
    }
}

/// Builder for RemoteA2aAgent
pub struct RemoteA2aAgentBuilder {
    name: String,
    description: String,
    agent_url: Option<String>,
    streaming: Option<bool>,
    credential_broker: Option<Arc<dyn adk_core::CredentialBroker>>,
    credential_scopes: Vec<String>,
    allowed_endpoint_origins: Vec<String>,
}

impl RemoteA2aAgentBuilder {
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            description: String::new(),
            agent_url: None,
            streaming: None,
            credential_broker: None,
            credential_scopes: Vec::new(),
            allowed_endpoint_origins: Vec::new(),
        }
    }

    /// Accepts an agent card endpoint on `origin`, such as `https://rpc.example.com`, in
    /// addition to the agent URL's own origin.
    ///
    /// See [`RemoteA2aConfig::allowed_endpoint_origins`].
    pub fn allow_endpoint_origin(mut self, origin: impl Into<String>) -> Self {
        self.allowed_endpoint_origins.push(origin.into());
        self
    }

    /// Authenticates to the remote agent with a token from `broker`, minted for the
    /// running agent's acting context with the agent URL as the resource.
    ///
    /// See [`RemoteA2aConfig::credential_broker`].
    pub fn credential_broker(
        mut self,
        broker: Arc<dyn adk_core::CredentialBroker>,
        scopes: Vec<String>,
    ) -> Self {
        self.credential_broker = Some(broker);
        self.credential_scopes = scopes;
        self
    }

    pub fn description(mut self, description: impl Into<String>) -> Self {
        self.description = description.into();
        self
    }

    pub fn agent_url(mut self, url: impl Into<String>) -> Self {
        self.agent_url = Some(url.into());
        self
    }

    /// Set whether to use streaming. If not set, auto-detects from agent capabilities.
    pub fn streaming(mut self, streaming: bool) -> Self {
        self.streaming = Some(streaming);
        self
    }

    pub fn build(self) -> Result<RemoteA2aAgent> {
        let agent_url = self
            .agent_url
            .ok_or_else(|| adk_core::AdkError::agent("RemoteA2aAgent requires agent_url"))?;

        Ok(RemoteA2aAgent::new(RemoteA2aConfig {
            name: self.name,
            description: self.description,
            agent_url,
            streaming: self.streaming,
            credential_broker: self.credential_broker,
            credential_scopes: self.credential_scopes,
            allowed_endpoint_origins: self.allowed_endpoint_origins,
        }))
    }
}

// Helper functions

fn get_user_content_from_context(ctx: &dyn InvocationContext) -> Option<String> {
    let content = ctx.user_content();
    for part in &content.parts {
        if let Part::Text { text } = part {
            return Some(text.clone());
        }
    }
    None
}

fn build_a2a_message(content: Option<String>) -> crate::a2a::Message {
    let text = content.unwrap_or_default();
    crate::a2a::Message::builder()
        .role(Role::User)
        .parts(vec![A2aPart::text(text)])
        .message_id(uuid::Uuid::new_v4().to_string())
        .build()
}

fn convert_update_event(
    invocation_id: &str,
    agent_name: &str,
    update: UpdateEvent,
) -> Option<Event> {
    match update {
        UpdateEvent::TaskArtifactUpdate(artifact_event) => {
            let parts: Vec<Part> = artifact_event
                .artifact
                .parts
                .iter()
                .filter_map(|p| match p {
                    A2aPart::Text { text, .. } => Some(Part::Text { text: text.clone() }),
                    _ => None,
                })
                .collect();

            if parts.is_empty() {
                return None;
            }

            let mut event = Event::new(invocation_id.to_string());
            event.author = agent_name.to_string();
            event.llm_response.content = Some(Content { role: "model".to_string(), parts });
            event.llm_response.partial = !artifact_event.last_chunk;
            Some(event)
        }
        UpdateEvent::TaskStatusUpdate(status_event) => {
            // Only create event for final status updates with messages
            if status_event.final_update
                && let Some(msg) = status_event.status.message
            {
                let mut event = Event::new(invocation_id.to_string());
                event.author = agent_name.to_string();
                event.llm_response.content = Some(Content {
                    role: "model".to_string(),
                    parts: vec![Part::Text { text: msg }],
                });
                event.llm_response.turn_complete = true;
                return Some(event);
            }
            None
        }
    }
}

fn create_error_event(invocation_id: &str, agent_name: &str, error: &str) -> Event {
    let mut event = Event::new(invocation_id.to_string());
    event.author = agent_name.to_string();
    event.llm_response.error_message = Some(error.to_string());
    event.llm_response.turn_complete = true;
    event
}

/// Converts a non-streaming A2A Task response into a sequence of ADK Events.
fn convert_task_to_events(
    invocation_id: &str,
    agent_name: &str,
    task: crate::a2a::Task,
) -> Vec<Event> {
    let mut events = Vec::new();

    // 1. Yield events for artifacts
    if let Some(artifacts) = task.artifacts {
        for artifact in artifacts {
            let update = UpdateEvent::TaskArtifactUpdate(TaskArtifactUpdateEvent {
                task_id: task.id.clone(),
                context_id: task.context_id.clone(),
                artifact,
                append: false,
                last_chunk: true,
            });
            if let Some(event) = convert_update_event(invocation_id, agent_name, update) {
                events.push(event);
            }
        }
    }

    // 2. Yield events for history (agent messages)
    if let Some(history) = task.history {
        for msg in history {
            if msg.role == Role::Agent {
                let parts: Vec<Part> = msg
                    .parts
                    .iter()
                    .filter_map(|p| match p {
                        A2aPart::Text { text, .. } => Some(Part::Text { text: text.clone() }),
                        _ => None,
                    })
                    .collect();

                if !parts.is_empty() {
                    let mut event = Event::new(invocation_id.to_string());
                    event.author = agent_name.to_string();
                    event.llm_response.content = Some(Content { role: "model".to_string(), parts });
                    event.llm_response.turn_complete = false;
                    events.push(event);
                }
            }
        }
    }

    // 3. Yield final status event
    let update = UpdateEvent::TaskStatusUpdate(TaskStatusUpdateEvent {
        task_id: task.id,
        context_id: task.context_id,
        status: task.status,
        final_update: true,
    });
    if let Some(event) = convert_update_event(invocation_id, agent_name, update) {
        events.push(event);
    }

    events
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_builder() {
        let agent = RemoteA2aAgent::builder("test")
            .description("Test agent")
            .agent_url("http://localhost:8080")
            .build()
            .unwrap();

        assert_eq!(agent.name(), "test");
        assert_eq!(agent.description(), "Test agent");
    }

    #[test]
    fn test_builder_missing_url() {
        let result = RemoteA2aAgent::builder("test").build();
        assert!(result.is_err());
    }

    #[test]
    fn test_builder_streaming_option() {
        let agent = RemoteA2aAgent::builder("test")
            .agent_url("http://localhost:8080")
            .streaming(true)
            .build()
            .unwrap();

        assert_eq!(agent.config.streaming, Some(true));
    }

    #[test]
    fn test_builder_streaming_default_is_none() {
        let agent =
            RemoteA2aAgent::builder("test").agent_url("http://localhost:8080").build().unwrap();

        assert_eq!(agent.config.streaming, None);
    }

    #[test]
    fn test_convert_task_to_events_with_artifacts_and_history() {
        use crate::a2a::{Artifact, Message, Task, TaskState, TaskStatus};

        let task = Task {
            id: "task-123".to_string(),
            context_id: Some("ctx-456".to_string()),
            status: TaskStatus { state: TaskState::Completed, message: Some("Done".to_string()) },
            artifacts: Some(vec![Artifact {
                artifact_id: "art-1".to_string(),
                name: Some("result".to_string()),
                description: None,
                parts: vec![A2aPart::text("artifact content".to_string())],
                metadata: None,
                extensions: None,
            }]),
            history: Some(vec![
                Message::builder()
                    .role(Role::Agent)
                    .parts(vec![A2aPart::text("Hello from agent".to_string())])
                    .build(),
            ]),
        };

        let events = convert_task_to_events("inv-1", "remote-agent", task);

        // Should have 3 events: artifact, history message, final status
        assert_eq!(events.len(), 3);

        // Artifact event
        assert_eq!(events[0].author, "remote-agent");
        let content = events[0].llm_response.content.as_ref().unwrap();
        assert_eq!(content.parts[0], Part::Text { text: "artifact content".to_string() });

        // History event
        assert_eq!(events[1].author, "remote-agent");
        let content = events[1].llm_response.content.as_ref().unwrap();
        assert_eq!(content.parts[0], Part::Text { text: "Hello from agent".to_string() });
        assert!(!events[1].llm_response.turn_complete);

        // Final status event
        assert_eq!(events[2].author, "remote-agent");
        assert!(events[2].llm_response.turn_complete);
    }

    #[test]
    fn test_convert_task_to_events_empty_task() {
        use crate::a2a::{Task, TaskState, TaskStatus};

        let task = Task {
            id: "task-empty".to_string(),
            context_id: None,
            status: TaskStatus { state: TaskState::Completed, message: None },
            artifacts: None,
            history: None,
        };

        let events = convert_task_to_events("inv-1", "agent", task);

        // A completed task with no message and no artifacts produces no events
        // because convert_update_event only emits for final_update with a message
        assert!(events.is_empty());
    }

    #[test]
    fn test_convert_task_to_events_status_with_message() {
        use crate::a2a::{Task, TaskState, TaskStatus};

        let task = Task {
            id: "task-msg".to_string(),
            context_id: None,
            status: TaskStatus {
                state: TaskState::Completed,
                message: Some("All done".to_string()),
            },
            artifacts: None,
            history: None,
        };

        let events = convert_task_to_events("inv-1", "agent", task);

        assert_eq!(events.len(), 1);
        assert!(events[0].llm_response.turn_complete);
        let content = events[0].llm_response.content.as_ref().unwrap();
        assert_eq!(content.parts[0], Part::Text { text: "All done".to_string() });
    }
}

// ── A2A v1.0.0 Remote Agent ─────────────────────────────────────────────────

#[cfg(feature = "a2a-v1")]
pub mod v1_remote {
    //! V1.0.0 remote agent wrapper.
    //!
    //! Implements the ADK [`Agent`] trait by communicating with a remote A2A
    //! v1.0.0 agent. Parses the v1 [`AgentCard`] structure including
    //! `supportedInterfaces`, selects the best interface URL (preferring
    //! JSONRPC over HTTP+JSON), and uses [`A2aV1Client`] which sends the
    //! `A2A-Version: 1.0` header on all requests.

    use crate::a2a::client::v1_client::A2aV1Client;
    use a2a_protocol_types::responses::SendMessageResponse;
    use a2a_protocol_types::{AgentCard, AgentInterface};
    use adk_core::{Agent, Content, Event, EventStream, InvocationContext, Part, Result};
    use async_trait::async_trait;
    use std::sync::Arc;

    /// Configuration for a v1.0.0 remote A2A agent.
    #[derive(Clone)]
    pub struct RemoteA2aV1Config {
        /// Name of the agent.
        pub name: String,
        /// Description of the agent.
        pub description: String,
        /// The v1.0.0 agent card describing the remote agent.
        pub agent_card: AgentCard,
        /// Whether to stream the remote's replies. `None` streams when the run does
        /// (`RunConfig::streaming_mode` is not `None`); either way, only when the card says
        /// the agent streams.
        pub streaming: Option<bool>,
        /// Mints the bearer token sent to the remote agent, for the running agent's
        /// [`ActingContext`](adk_core::ActingContext) and with the selected interface
        /// URL as the resource. `None` sends no credential.
        pub credential_broker: Option<Arc<dyn adk_core::CredentialBroker>>,
        /// Scopes requested from the [`credential_broker`](Self::credential_broker).
        pub credential_scopes: Vec<String>,
        /// Sent with every message: `historyLength`, accepted output modes, a push config
        /// (adk-go's `MessageSendConfig`).
        pub send_configuration: Option<a2a_protocol_types::params::SendMessageConfiguration>,
        /// Callbacks, converters and options around each turn; see [`RemoteAgentHooks`].
        pub hooks: RemoteAgentHooks,
    }

    /// Runs before or after the agent's turn, as an `LlmAgent`'s agent callbacks do: content
    /// it returns is the turn's answer (before) or one more event (after).
    pub type AgentCallback = Arc<
        dyn Fn(
                Arc<dyn adk_core::CallbackContext>,
            ) -> futures::future::BoxFuture<'static, Result<Option<Content>>>
            + Send
            + Sync,
    >;

    /// May change the message before it is sent; an event it returns is the turn's answer
    /// instead of the remote's, and no request is made.
    pub type BeforeRequestCallback = Arc<
        dyn Fn(&dyn InvocationContext, &mut a2a_protocol_types::Message) -> Result<Option<Event>>
            + Send
            + Sync,
    >;

    /// Sees each event of the turn; an event it returns replaces it. An error ends the turn.
    pub type AfterRequestCallback =
        Arc<dyn Fn(&dyn InvocationContext, &Event) -> Result<Option<Event>> + Send + Sync>;

    /// Turns one of the remote's updates into the event it stands for, replacing the default
    /// conversion; `None` produces no event.
    pub type EventConverter = Arc<
        dyn Fn(&a2a_protocol_types::events::StreamResponse) -> Result<Option<Event>> + Send + Sync,
    >;

    /// Turns one of the remote's parts into an ADK part; `None` leaves it out.
    pub type FromWirePart =
        Arc<dyn Fn(&a2a_protocol_types::Part) -> Result<Option<Part>> + Send + Sync>;

    /// Turns one of the session's parts into the part sent to the remote; `None` leaves it
    /// out.
    pub type ToWirePart =
        Arc<dyn Fn(&Part) -> Result<Option<a2a_protocol_types::Part>> + Send + Sync>;

    /// Ends a remote task the turn left unfinished, instead of the default cancel.
    pub type RemoteTaskCleanup =
        Arc<dyn Fn(String) -> futures::future::BoxFuture<'static, ()> + Send + Sync>;

    /// Gives the remote's agent card for each turn, instead of the config's fixed card.
    pub type CardProvider =
        Arc<dyn Fn() -> futures::future::BoxFuture<'static, Result<AgentCard>> + Send + Sync>;

    /// Callbacks, converters and options around a remote agent's turns, as adk-go's remote
    /// agent config offers them. All are optional.
    #[derive(Clone, Default)]
    pub struct RemoteAgentHooks {
        before_agent: Vec<AgentCallback>,
        after_agent: Vec<AgentCallback>,
        before_request: Vec<BeforeRequestCallback>,
        after_request: Vec<AfterRequestCallback>,
        event_converter: Option<EventConverter>,
        from_wire_part: Option<FromWirePart>,
        to_wire_part: Option<ToWirePart>,
        remote_task_cleanup: Option<RemoteTaskCleanup>,
        card_provider: Option<CardProvider>,
        allow_transfer_to_agent: bool,
    }

    impl RemoteAgentHooks {
        /// Runs `callback` before each turn, after the run's plugins; see [`AgentCallback`].
        #[must_use]
        pub fn before_agent(mut self, callback: AgentCallback) -> Self {
            self.before_agent.push(callback);
            self
        }

        /// Runs `callback` after each turn, after the run's plugins; see [`AgentCallback`].
        #[must_use]
        pub fn after_agent(mut self, callback: AgentCallback) -> Self {
            self.after_agent.push(callback);
            self
        }

        /// Runs `callback` before each request; see [`BeforeRequestCallback`].
        #[must_use]
        pub fn before_request(mut self, callback: BeforeRequestCallback) -> Self {
            self.before_request.push(callback);
            self
        }

        /// Runs `callback` on each event of a turn; see [`AfterRequestCallback`].
        #[must_use]
        pub fn after_request(mut self, callback: AfterRequestCallback) -> Self {
            self.after_request.push(callback);
            self
        }

        /// Converts the remote's updates with `converter`; see [`EventConverter`].
        #[must_use]
        pub fn event_converter(mut self, converter: EventConverter) -> Self {
            self.event_converter = Some(converter);
            self
        }

        /// Converts the remote's parts with `converter`; see [`FromWirePart`].
        #[must_use]
        pub fn from_wire_part(mut self, converter: FromWirePart) -> Self {
            self.from_wire_part = Some(converter);
            self
        }

        /// Converts the parts sent to the remote with `converter`; see [`ToWirePart`].
        #[must_use]
        pub fn to_wire_part(mut self, converter: ToWirePart) -> Self {
            self.to_wire_part = Some(converter);
            self
        }

        /// Ends unfinished remote tasks with `cleanup` instead of cancelling them.
        #[must_use]
        pub fn remote_task_cleanup(mut self, cleanup: RemoteTaskCleanup) -> Self {
            self.remote_task_cleanup = Some(cleanup);
            self
        }

        /// Reads the agent card from `provider` for each turn.
        #[must_use]
        pub fn card_provider(mut self, provider: CardProvider) -> Self {
            self.card_provider = Some(provider);
            self
        }

        /// Follows the remote's `adk_transfer_to_agent`: an update that names an agent
        /// transfers the conversation to it, as adk-go's `AllowTransferToAgent` does. Off by
        /// default.
        #[must_use]
        pub fn allow_transfer_to_agent(mut self, allow: bool) -> Self {
            self.allow_transfer_to_agent = allow;
            self
        }
    }

    impl RemoteA2aV1Config {
        /// A config for the agent `name` behind `agent_card`, described by the card, that
        /// streams when the run does and the card allows it.
        pub fn new(name: impl Into<String>, agent_card: AgentCard) -> Self {
            Self {
                name: name.into(),
                description: agent_card.description.clone(),
                agent_card,
                streaming: None,
                credential_broker: None,
                credential_scopes: Vec::new(),
                send_configuration: None,
                hooks: RemoteAgentHooks::default(),
            }
        }
    }

    /// An agent that communicates with a remote A2A v1.0.0 agent.
    ///
    /// Selects the best interface URL from the agent card's
    /// `supportedInterfaces` (preferring JSONRPC, falling back to HTTP+JSON)
    /// and delegates to [`A2aV1Client`] for protocol-level communication.
    pub struct RemoteA2aV1Agent {
        config: RemoteA2aV1Config,
    }

    impl RemoteA2aV1Agent {
        /// Creates a new v1 remote agent from the given configuration.
        pub fn new(config: RemoteA2aV1Config) -> Self {
            Self { config }
        }

        /// Creates a remote agent named `name` for the A2A v1 agent at `base_url`, from the
        /// card it serves at `/.well-known/agent-card.json`. The card's description becomes
        /// the agent's, and streaming follows the card.
        ///
        /// # Errors
        ///
        /// Returns an error when the card cannot be fetched or names an endpoint on
        /// another origin; see [`A2aV1Client::resolve_agent_card`].
        pub async fn from_url(
            name: impl Into<String>,
            base_url: &str,
        ) -> std::result::Result<Self, crate::a2a::client::v1_client::V1ClientError> {
            let agent_card = A2aV1Client::resolve_agent_card(base_url).await?;
            Ok(Self::new(RemoteA2aV1Config::new(name, agent_card)))
        }

        /// Selects the best A2A v1 interface from the agent card.
        ///
        /// Prefers JSONRPC, falls back to HTTP+JSON, and never picks an interface for an
        /// earlier protocol version; see [`v1_interface`](crate::a2a::client::v1_client::v1_interface).
        pub fn select_interface(card: &AgentCard) -> Option<&AgentInterface> {
            use crate::a2a::client::v1_client::v1_interface;
            v1_interface(card, "JSONRPC").or_else(|| v1_interface(card, "HTTP+JSON"))
        }
    }

    #[async_trait]
    impl Agent for RemoteA2aV1Agent {
        fn name(&self) -> &str {
            &self.config.name
        }

        fn description(&self) -> &str {
            &self.config.description
        }

        fn sub_agents(&self) -> &[Arc<dyn Agent>] {
            &[]
        }

        async fn cancel_remote_task(
            &self,
            task_id: &str,
            acting: &adk_core::ActingContext,
        ) -> Result<()> {
            let card = &self.config.agent_card;
            let interface = Self::select_interface(card).ok_or_else(|| {
                adk_core::AdkError::agent("no supported interface found in agent card")
            })?;
            let mut client = A2aV1Client::with_retry(
                card.clone(),
                crate::a2a::client::v1_client::RetryConfig { max_retries: 0, ..Default::default() },
            );
            if let Some(broker) = self.config.credential_broker.as_deref() {
                let token = super::brokered_token(
                    broker,
                    acting,
                    &interface.url,
                    &self.config.credential_scopes,
                )
                .await?;
                client = client.with_credential(token);
            }
            let cancelled = if interface.protocol_binding == "HTTP+JSON" {
                client.cancel_task_rest(task_id).await
            } else {
                client.cancel_task(task_id).await
            };
            cancelled.map(drop).map_err(|error| {
                adk_core::AdkError::agent(format!("cancel remote task {task_id}: {error}"))
            })
        }

        async fn run(&self, ctx: Arc<dyn InvocationContext>) -> Result<EventStream> {
            let turn = self.turn(ctx.clone());
            let hooks = self.config.hooks.clone();
            let plugins = ctx.run_config().invocation_hooks.clone();
            let invocation_id = ctx.invocation_id().to_string();
            let agent_name = self.config.name.clone();
            let stream = async_stream::stream! {
                use futures::StreamExt;
                let answer = |content: Content| {
                    let mut event = Event::new(invocation_id.clone());
                    event.author = agent_name.clone();
                    event.llm_response.content = Some(content);
                    event
                };
                let callback_ctx = ctx.clone() as Arc<dyn adk_core::CallbackContext>;

                // Before the turn: the run's plugins, then the agent's own callbacks.
                let mut early = None;
                for plugin in &plugins {
                    match plugin.before_agent(callback_ctx.clone()).await {
                        Ok(Some(content)) => { early = Some(content); break; }
                        Ok(None) => {}
                        Err(error) => { yield Err(error); return; }
                    }
                }
                if early.is_none() {
                    for callback in &hooks.before_agent {
                        match callback(callback_ctx.clone()).await {
                            Ok(Some(content)) => { early = Some(content); break; }
                            Ok(None) => {}
                            Err(error) => { yield Err(error); return; }
                        }
                    }
                }

                if let Some(content) = early {
                    yield Ok(answer(content));
                } else {
                    let mut turn = turn;
                    'events: while let Some(item) = turn.next().await {
                        let mut event = match item {
                            Ok(event) => event,
                            Err(error) => { yield Err(error); return; }
                        };
                        for callback in &hooks.after_request {
                            match callback(ctx.as_ref(), &event) {
                                Ok(Some(replacement)) => { event = replacement; break; }
                                Ok(None) => {}
                                Err(error) => {
                                    yield Ok(create_v1_error_event(&invocation_id, &agent_name, &error.to_string()));
                                    break 'events;
                                }
                            }
                        }
                        yield Ok(event);
                    }
                }

                // After the turn: the run's plugins, then the agent's own callbacks.
                for plugin in &plugins {
                    match plugin.after_agent(callback_ctx.clone()).await {
                        Ok(Some(content)) => { yield Ok(answer(content)); return; }
                        Ok(None) => {}
                        Err(error) => { yield Err(error); return; }
                    }
                }
                for callback in &hooks.after_agent {
                    match callback(callback_ctx.clone()).await {
                        Ok(Some(content)) => { yield Ok(answer(content)); return; }
                        Ok(None) => {}
                        Err(error) => { yield Err(error); return; }
                    }
                }
            };
            Ok(Box::pin(stream))
        }
    }

    impl RemoteA2aV1Agent {
        /// The agent's turn with the remote, without its agent callbacks: see
        /// [`Agent::run`].
        fn turn(&self, ctx: Arc<dyn InvocationContext>) -> EventStream {
            let card = self.config.agent_card.clone();
            let hooks = self.config.hooks.clone();
            let invocation_id = ctx.invocation_id().to_string();
            let agent_name = self.config.name.clone();
            let branch = ctx.branch().to_string();
            let broker = self.config.credential_broker.clone();
            let scopes = self.config.credential_scopes.clone();
            let send_configuration = self.config.send_configuration.clone();
            let acting = ctx.acting_context();
            // As adk-go: stream when the run streams and the card says the agent can; a
            // configured `streaming` overrides the run, never the card.
            let run_streams = ctx.run_config().streaming_mode != adk_core::StreamingMode::None;
            let streaming = self.config.streaming.unwrap_or(run_streams);

            // The remote conversation this agent continues, and a remote task waiting on it.
            let keys = RemoteKeys::for_agent(&agent_name);
            let state = ctx.session().state();
            let remote_context = state.get(&keys.context_id).and_then(string_value);
            let remote_task = state.get(&keys.task_id).and_then(string_value);
            let outgoing = outgoing_turn(ctx.as_ref(), &agent_name, hooks.to_wire_part.as_ref());
            let turn_ctx = ctx.clone();

            let stream = async_stream::stream! {
                // The card for this turn: from the provider, when the agent has one.
                let card = match &hooks.card_provider {
                    Some(provider) => match provider().await {
                        Ok(card) => card,
                        Err(e) => {
                            yield Ok(create_v1_error_event(&invocation_id, &agent_name, &format!("agent card resolution failed: {e}")));
                            return;
                        }
                    },
                    None => card,
                };
                let use_streaming = streaming && card.capabilities.streaming == Some(true);

                // Nothing new for the remote since its last reply: no request, as adk-go.
                if outgoing.parts.is_empty() {
                    let mut event = Event::new(invocation_id.clone());
                    event.author = agent_name.clone();
                    event.branch = branch.clone();
                    yield Ok(event);
                    return;
                }

                // Verify we have a usable interface
                let interface = match Self::select_interface(&card) {
                    Some(i) => i.clone(),
                    None => {
                        yield Ok(create_v1_error_event(
                            &invocation_id,
                            &agent_name,
                            "no supported interface found in agent card (need JSONRPC or HTTP+JSON)",
                        ));
                        return;
                    }
                };

                // A SendMessage that times out may still have started a task, so it is never
                // sent twice: no automatic retries, as adk-go.
                let mut client = A2aV1Client::with_retry(
                    card.clone(),
                    crate::a2a::client::v1_client::RetryConfig {
                        max_retries: 0,
                        ..Default::default()
                    },
                );
                if let Some(broker) = broker.as_deref() {
                    match super::brokered_token(broker, &acting, &interface.url, &scopes).await {
                        Ok(token) => client = client.with_credential(token),
                        Err(e) => {
                            yield Ok(create_v1_error_event(&invocation_id, &agent_name, &e.to_string()));
                            return;
                        }
                    }
                }

                let client = Arc::new(client);
                let rest = interface.protocol_binding == "HTTP+JSON";
                // Cancels the remote task if the turn ends before the task does.
                let mut cleanup =
                    RemoteTaskCleanupGuard::new(client.clone(), rest, hooks.remote_task_cleanup.clone());

                // The waiting remote task continues only with an answer to one of its calls;
                // any other message starts a new task in the same context.
                let task_id = remote_task.filter(|_| outgoing.answers_own_call);
                let mut message = build_v1_message(outgoing.parts, remote_context, task_id);
                for callback in &hooks.before_request {
                    match callback(turn_ctx.as_ref(), &mut message) {
                        Ok(Some(event)) => {
                            yield Ok(event);
                            return;
                        }
                        Ok(None) => {}
                        Err(e) => {
                            yield Ok(create_v1_error_event(&invocation_id, &agent_name, &e.to_string()));
                            return;
                        }
                    }
                }

                if use_streaming {
                    // The remote's updates as they arrive. A stream that stops before a final
                    // status is reported as an error.
                    match client.stream_message_with(message, send_configuration.as_ref()).await {
                        Ok(mut updates) => {
                            use futures::StreamExt;

                            let mut finished = false;
                            let mut remote = RemoteEvents::new(&invocation_id, &agent_name).with_hooks(&hooks);
                            while let Some(update) = updates.next().await {
                                let stream_response = match update {
                                    Ok(update) => update,
                                    Err(e) => {
                                        yield Ok(create_v1_error_event(&invocation_id, &agent_name, &e.to_string()));
                                        return;
                                    }
                                };
                                cleanup.observe(&stream_response);
                                if ends_stream(&stream_response) {
                                    finished = true;
                                    let mut events = remote.handle(&stream_response);
                                    let last = events.pop().unwrap_or_else(|| remote.new_event());
                                    for event in events {
                                        yield Ok(event);
                                    }
                                    yield Ok(end_turn(last, &stream_response, &keys));
                                    // The server closes the stream here (A2A §3.1.2). Read to its
                                    // end so the connection closes cleanly, but not for long.
                                    let drain = async { while updates.next().await.is_some() {} };
                                    let _ = tokio::time::timeout(std::time::Duration::from_secs(2), drain).await;
                                    break;
                                }
                                for event in remote.handle(&stream_response) {
                                    yield Ok(event);
                                }
                            }

                            if !finished {
                                yield Ok(create_v1_error_event(
                                    &invocation_id,
                                    &agent_name,
                                    &crate::a2a::client::truncated_stream_error().to_string(),
                                ));
                            }
                        }
                        Err(e) => {
                            yield Ok(create_v1_error_event(
                                &invocation_id,
                                &agent_name,
                                &format!("failed to send streaming message: {e}"),
                            ));
                        }
                    }
                } else {
                    // Send non-streaming message, over the binding the card offers.
                    let sent = if rest {
                        client.send_message_rest_with(message, send_configuration.as_ref()).await
                    } else {
                        client.send_message_with(message, send_configuration.as_ref()).await
                    };
                    match sent {
                        Ok(SendMessageResponse::Message(reply)) => {
                            // The agent answered directly, without a task.
                            let resp = a2a_protocol_types::events::StreamResponse::Message(reply);
                            cleanup.observe(&resp);
                            let mut remote = RemoteEvents::new(&invocation_id, &agent_name).with_hooks(&hooks);
                            let event = remote.handle(&resp).pop().unwrap_or_else(|| remote.new_event());
                            yield Ok(end_turn(event, &resp, &keys));
                        }
                        Ok(SendMessageResponse::Task(task)) => {
                            // One event for the task: its artifacts and status message.
                            let resp = a2a_protocol_types::events::StreamResponse::Task(task);
                            cleanup.observe(&resp);
                            let mut remote = RemoteEvents::new(&invocation_id, &agent_name).with_hooks(&hooks);
                            let event = remote.handle(&resp).pop().unwrap_or_else(|| remote.new_event());
                            yield Ok(end_turn(event, &resp, &keys));
                        }
                        Ok(_) => {
                            yield Ok(create_v1_error_event(
                                &invocation_id,
                                &agent_name,
                                "unsupported SendMessage result: neither a task nor a message",
                            ));
                        }
                        Err(e) => {
                            yield Ok(create_v1_error_event(
                                &invocation_id,
                                &agent_name,
                                &format!("failed to send message: {e}"),
                            ));
                        }
                    }
                }
            };

            Box::pin(stream)
        }
    }

    /// Session state keys under which an agent keeps its remote conversation.
    struct RemoteKeys {
        /// The remote `contextId` the agent continues.
        context_id: String,
        /// The remote task waiting on this side, while there is one.
        task_id: String,
    }

    impl RemoteKeys {
        fn for_agent(agent_name: &str) -> Self {
            Self {
                context_id: format!("a2a_remote:{agent_name}:context_id"),
                task_id: format!("a2a_remote:{agent_name}:task_id"),
            }
        }
    }

    fn string_value(value: serde_json::Value) -> Option<String> {
        value.as_str().filter(|s| !s.is_empty()).map(str::to_string)
    }

    /// What one turn sends the remote agent.
    struct OutgoingTurn {
        parts: Vec<a2a_protocol_types::Part>,
        /// Whether the turn answers a call the remote made through this agent, which
        /// continues the remote task waiting on it.
        answers_own_call: bool,
    }

    /// What this turn sends, as adk-go's remote agent builds it: the session since this
    /// agent's last reply (the person's messages, and other agents' turns as the context the
    /// session renders them as). An answer to a call the remote made through this agent goes
    /// as a function response; any other function response goes as the text
    /// `Tool <name> returned: <json>`, since the remote never asked for it. With nothing new
    /// since the last reply the turn is empty, and the turn's own user content seeds it only
    /// when the session holds nothing for this agent yet. Each part goes out in the shape
    /// every A2A v1 SDK reads; see [`outgoing_part`].
    fn outgoing_turn(
        ctx: &dyn InvocationContext,
        agent_name: &str,
        to_wire: Option<&ToWirePart>,
    ) -> OutgoingTurn {
        let outgoing_part = |part: &Part| match to_wire {
            Some(convert) => convert(part).ok().flatten(),
            None => outgoing_part(part),
        };
        let history = ctx.session().conversation_history_with_context(agent_name, ctx.branch());
        let since_reply =
            history.iter().rposition(|content| content.role == "model").map_or(0, |i| i + 1);
        // This agent's own turns are the history's model contents (other agents' turns are
        // rendered as context): the calls in them are the ones the remote made.
        let own_calls: std::collections::HashSet<String> = history
            .iter()
            .filter(|content| content.role == "model")
            .flat_map(|content| &content.parts)
            .filter_map(|part| match part {
                Part::FunctionCall { id: Some(id), .. } => Some(id.clone()),
                _ => None,
            })
            .collect();
        let mut answers_own_call = false;
        let mut parts = Vec::new();
        for part in history[since_reply..].iter().flat_map(|content| &content.parts) {
            match part {
                Part::FunctionResponse { function_response, id, .. }
                    if !id.as_ref().is_some_and(|id| own_calls.contains(id)) =>
                {
                    let result = serde_json::to_string(&function_response.response)
                        .unwrap_or_else(|_| "<unserializable>".to_string());
                    let name = if function_response.name.is_empty() {
                        "<unnamed>"
                    } else {
                        function_response.name.as_str()
                    };
                    parts.push(a2a_protocol_types::Part::text(format!(
                        "Tool {name} returned: {result}"
                    )));
                }
                Part::FunctionResponse { .. } => {
                    answers_own_call = true;
                    parts.extend(outgoing_part(part));
                }
                other => parts.extend(outgoing_part(other)),
            }
        }
        if parts.is_empty() && history.is_empty() {
            parts = ctx.user_content().parts.iter().filter_map(outgoing_part).collect();
        }
        OutgoingTurn { parts, answers_own_call }
    }

    /// Cancels the remote task a turn started when the turn ends before the task does: the
    /// caller stopped reading, the stream broke, or the remote returned a task still at work.
    /// A task that ended, or waits on this side, is left alone. The cancel runs on its own
    /// for at most 5 seconds, as adk-go's remote agent sends it.
    struct RemoteTaskCleanupGuard {
        client: Arc<A2aV1Client>,
        rest: bool,
        task_id: Option<String>,
        settled: bool,
        custom: Option<RemoteTaskCleanup>,
    }

    impl RemoteTaskCleanupGuard {
        fn new(client: Arc<A2aV1Client>, rest: bool, custom: Option<RemoteTaskCleanup>) -> Self {
            Self { client, rest, task_id: None, settled: false, custom }
        }

        /// Records the remote task an update names, and whether it ended or waits.
        fn observe(&mut self, response: &a2a_protocol_types::events::StreamResponse) {
            use a2a_protocol_types::events::StreamResponse;
            let (task_id, state) = match response {
                StreamResponse::Task(task) => (Some(&task.id.0), Some(task.status.state)),
                StreamResponse::StatusUpdate(update) => {
                    (Some(&update.task_id.0), Some(update.status.state))
                }
                StreamResponse::ArtifactUpdate(update) => (Some(&update.task_id.0), None),
                StreamResponse::Message(_) => {
                    self.settled = true;
                    (None, None)
                }
                _ => (None, None),
            };
            if let Some(task_id) = task_id {
                self.task_id = Some(task_id.clone());
            }
            if state.is_some_and(is_final_state) {
                self.settled = true;
            }
        }
    }

    impl Drop for RemoteTaskCleanupGuard {
        fn drop(&mut self) {
            if self.settled {
                return;
            }
            let Some(task_id) = self.task_id.take() else { return };
            let Ok(runtime) = tokio::runtime::Handle::try_current() else { return };
            if let Some(custom) = self.custom.clone() {
                runtime.spawn(custom(task_id));
                return;
            }
            let (client, rest) = (self.client.clone(), self.rest);
            runtime.spawn(async move {
                let cancel = async {
                    if rest {
                        client.cancel_task_rest(&task_id).await.map(drop)
                    } else {
                        client.cancel_task(&task_id).await.map(drop)
                    }
                };
                match tokio::time::timeout(std::time::Duration::from_secs(5), cancel).await {
                    Ok(Ok(())) => {}
                    Ok(Err(error)) => tracing::warn!(%task_id, %error, "failed to cancel task"),
                    Err(_) => tracing::warn!(%task_id, "failed to cancel task: timed out"),
                }
            });
        }
    }

    /// An ADK part as A2A sends it:
    /// - text as text;
    /// - inline data and files as raw bytes and URLs;
    /// - function calls and responses as data parts tagged `adk_type`, the shape
    ///   adk-python, adk-go and adk-server read, so an answer to a remote long-running call
    ///   resumes it.
    ///
    /// Thinking and provider items stay here.
    fn outgoing_part(part: &Part) -> Option<a2a_protocol_types::Part> {
        use crate::a2a::v1::convert::{
            media_part_to_wire, tagged_function_call_part, tagged_function_response_part,
        };
        match part {
            Part::Text { text } if !text.trim().is_empty() => {
                Some(a2a_protocol_types::Part::text(text.clone()))
            }
            Part::Thinking { thinking, .. } if !thinking.trim().is_empty() => {
                let mut wire = a2a_protocol_types::Part::text(thinking.clone());
                wire.metadata = Some(
                    serde_json::json!({ crate::a2a::v1::convert::ADK_THOUGHT_METADATA_KEY: true }),
                );
                Some(wire)
            }
            Part::FunctionCall { name, args, id, .. } => {
                Some(tagged_function_call_part(name, args, id.as_deref(), false))
            }
            Part::FunctionResponse { function_response, id, .. } => {
                Some(tagged_function_response_part(
                    &function_response.name,
                    &function_response.response,
                    id.as_deref(),
                ))
            }
            other => media_part_to_wire(other),
        }
    }

    /// Builds the v1 `Message` for a turn. `context_id` continues the remote conversation,
    /// and `task_id` continues a remote task waiting on this side.
    fn build_v1_message(
        parts: Vec<a2a_protocol_types::Part>,
        context_id: Option<String>,
        task_id: Option<String>,
    ) -> a2a_protocol_types::Message {
        let parts = if parts.is_empty() { vec![a2a_protocol_types::Part::text("")] } else { parts };
        a2a_protocol_types::Message {
            id: a2a_protocol_types::MessageId::new(uuid::Uuid::new_v4().to_string()),
            role: a2a_protocol_types::MessageRole::User,
            parts,
            task_id: task_id.map(a2a_protocol_types::TaskId::new),
            context_id: context_id.map(a2a_protocol_types::ContextId::new),
            reference_task_ids: None,
            extensions: None,
            metadata: None,
        }
    }

    /// Turns one remote turn's A2A events into ADK events, as adk-go's remote agent does
    /// (`adka2a.ToSessionEvent` and its run processor):
    ///
    /// - an artifact update is a model event with every part of the artifact, partial when
    ///   the server marks it `adk_partial`, otherwise when it appends or is not the last
    ///   chunk (`lastChunk` absent means false, as A2A servers omit it); the server's reset
    ///   of its temporary partial artifact (`adk_partial` with `lastChunk`) is dropped;
    /// - chunks without `adk_partial` are joined per artifact into one complete event when
    ///   their last chunk or the terminal status arrives, so the session keeps the whole
    ///   answer; a `Task` snapshot starts over;
    /// - a status message before the task ends is the remote's reasoning: partial thoughts;
    /// - a final status carries its message, the calls the remote waits on as long-running
    ///   calls, and for `FAILED` the error text (the first part, marked
    ///   `adk_is_error_message`, or `a2a task failed`);
    /// - every event carries the remote task and context (`a2a:task_id`,
    ///   `a2a:context_id` in its metadata), and the update's `adk_escalate`,
    ///   `adk_error_code`, usage, citations and custom metadata.
    struct RemoteEvents {
        invocation_id: String,
        agent_name: String,
        /// Chunks joined by artifact ID, in the order they were last updated.
        aggregations: Vec<(String, Aggregation)>,
        converter: Option<EventConverter>,
        from_wire: Option<FromWirePart>,
        allow_transfer: bool,
    }

    #[derive(Default)]
    struct Aggregation {
        parts: Vec<Part>,
        citations: Vec<adk_core::CitationSource>,
        custom: std::collections::HashMap<String, String>,
        usage: Option<adk_core::UsageMetadata>,
    }

    impl RemoteEvents {
        fn new(invocation_id: &str, agent_name: &str) -> Self {
            Self {
                invocation_id: invocation_id.to_string(),
                agent_name: agent_name.to_string(),
                aggregations: Vec::new(),
                converter: None,
                from_wire: None,
                allow_transfer: false,
            }
        }

        /// Converts as `hooks` say: their event and part converters, and transfers.
        fn with_hooks(mut self, hooks: &RemoteAgentHooks) -> Self {
            self.converter = hooks.event_converter.clone();
            self.from_wire = hooks.from_wire_part.clone();
            self.allow_transfer = hooks.allow_transfer_to_agent;
            self
        }

        /// The ADK events `response` produces, in order.
        fn handle(&mut self, response: &a2a_protocol_types::events::StreamResponse) -> Vec<Event> {
            use a2a_protocol_types::events::StreamResponse;
            let event = match &self.converter {
                Some(convert) => match convert(response) {
                    Ok(event) => event,
                    Err(error) => Some(create_v1_error_event(
                        &self.invocation_id,
                        &self.agent_name,
                        &format!("failed to convert a2aEvent: {error}"),
                    )),
                },
                None => self.to_event(response),
            };
            let event = event.map(|mut event| {
                if self.allow_transfer
                    && let Some(agent) = transfer_target(response)
                {
                    event.actions.transfer_to_agent = Some(agent);
                }
                event
            });
            if partial_flag(response).is_some() {
                return event.into_iter().collect();
            }
            match response {
                StreamResponse::StatusUpdate(update) if is_final_state(update.status.state) => {
                    let mut events: Vec<Event> = std::mem::take(&mut self.aggregations)
                        .into_iter()
                        .map(|(_, aggregation)| self.joined(aggregation))
                        .collect();
                    events.extend(event);
                    events
                }
                StreamResponse::Task(_) => {
                    self.aggregations.clear();
                    event.into_iter().collect()
                }
                StreamResponse::ArtifactUpdate(update) => {
                    let Some(mut event) = event else { return Vec::new() };
                    let id = update.artifact.id.0.clone();
                    let last_chunk = update.last_chunk.unwrap_or(false);
                    if update.append != Some(true) {
                        self.aggregations.retain(|(existing, _)| *existing != id);
                        if last_chunk {
                            event.llm_response.partial = false;
                            return vec![event];
                        }
                    }
                    let mut aggregation = self
                        .aggregations
                        .iter()
                        .position(|(existing, _)| *existing == id)
                        .map(|index| self.aggregations.remove(index).1)
                        .unwrap_or_default();
                    aggregate(&mut aggregation, &event);
                    if !last_chunk {
                        self.aggregations.push((id, aggregation));
                        return vec![event];
                    }
                    let joined = self.joined(aggregation);
                    vec![event, joined]
                }
                _ => event.into_iter().collect(),
            }
        }

        fn joined(&self, aggregation: Aggregation) -> Event {
            let mut event = self.new_event();
            event.llm_response.content =
                Some(Content { role: "model".to_string(), parts: aggregation.parts });
            if !aggregation.citations.is_empty() {
                event.llm_response.citation_metadata =
                    Some(adk_core::CitationMetadata { citation_sources: aggregation.citations });
            }
            event.llm_response.usage_metadata = aggregation.usage;
            event.provider_metadata = aggregation.custom;
            event
        }

        fn new_event(&self) -> Event {
            let mut event = Event::new(self.invocation_id.clone());
            event.author = self.agent_name.clone();
            event
        }

        /// The event one A2A update stands for, if any (adk-go's `ToSessionEvent`).
        fn to_event(&self, response: &a2a_protocol_types::events::StreamResponse) -> Option<Event> {
            use a2a_protocol_types::events::StreamResponse;
            use a2a_protocol_types::task::TaskState;
            match response {
                StreamResponse::Task(task) => {
                    let mut parts = Vec::new();
                    for artifact in task.artifacts.iter().flatten() {
                        parts.extend(adk_parts(&artifact.parts, self.from_wire.as_ref()));
                    }
                    let status = status_message(
                        task.status.state,
                        task.status.message.as_ref(),
                        self.from_wire.as_ref(),
                    );
                    parts.extend(status.parts);
                    let final_state = is_final_state(task.status.state);
                    if parts.is_empty() && !final_state {
                        return None;
                    }
                    let mut event = self.new_event();
                    if !parts.is_empty() {
                        if waits(task.status.state) {
                            event.long_running_tool_ids =
                                long_running_ids(&parts, &task_parts(task));
                        }
                        event.llm_response.content =
                            Some(Content { role: "model".to_string(), parts });
                    }
                    event.llm_response.error_message = status.error;
                    apply_metadata(
                        &mut event,
                        task.metadata.as_ref(),
                        None,
                        Some((&task.id.0, &task.context_id.0)),
                    );
                    event.llm_response.turn_complete = final_state;
                    Some(event)
                }
                StreamResponse::Message(message) => {
                    let parts = adk_parts(&message.parts, self.from_wire.as_ref());
                    let mut event = self.new_event();
                    if !parts.is_empty() {
                        let role = if message.role == a2a_protocol_types::MessageRole::User {
                            "user"
                        } else {
                            "model"
                        };
                        event.llm_response.content =
                            Some(Content { role: role.to_string(), parts });
                    }
                    let ids = message
                        .task_id
                        .as_ref()
                        .map(|t| t.0.as_str())
                        .zip(message.context_id.as_ref().map(|c| c.0.as_str()));
                    apply_metadata(&mut event, message.metadata.as_ref(), None, ids);
                    event.llm_response.turn_complete = true;
                    Some(event)
                }
                StreamResponse::ArtifactUpdate(update) => {
                    let partial_flag = partial_flag(response);
                    let last_chunk = update.last_chunk.unwrap_or(false);
                    if update.artifact.parts.is_empty()
                        || (partial_flag == Some(true) && last_chunk)
                    {
                        return None;
                    }
                    let parts = adk_parts(&update.artifact.parts, self.from_wire.as_ref());
                    if parts.is_empty() {
                        return None;
                    }
                    let mut event = self.new_event();
                    event.long_running_tool_ids = long_running_ids(&parts, &update.artifact.parts);
                    event.llm_response.content = Some(Content { role: "model".to_string(), parts });
                    apply_metadata(
                        &mut event,
                        update.metadata.as_ref(),
                        update.artifact.metadata.as_ref(),
                        Some((&update.task_id.0, &update.context_id.0)),
                    );
                    event.llm_response.partial =
                        partial_flag.unwrap_or(update.append == Some(true) || !last_chunk);
                    Some(event)
                }
                StreamResponse::StatusUpdate(update) => {
                    let ids = Some((update.task_id.0.as_str(), update.context_id.0.as_str()));
                    if is_final_state(update.status.state) {
                        let status = status_message(
                            update.status.state,
                            update.status.message.as_ref(),
                            self.from_wire.as_ref(),
                        );
                        let mut event = self.new_event();
                        let wire_parts = update
                            .status
                            .message
                            .as_ref()
                            .map(|m| m.parts.clone())
                            .unwrap_or_default();
                        event.long_running_tool_ids = long_running_ids(&status.parts, &wire_parts);
                        if !status.parts.is_empty() {
                            event.llm_response.content =
                                Some(Content { role: "model".to_string(), parts: status.parts });
                        }
                        event.llm_response.error_message = status.error;
                        apply_metadata(&mut event, update.metadata.as_ref(), None, ids);
                        event.llm_response.turn_complete = true;
                        return Some(event);
                    }
                    let message = update.status.message.as_ref()?;
                    let mut parts = adk_parts(&message.parts, self.from_wire.as_ref());
                    if parts.is_empty() {
                        return None;
                    }
                    // Progress the remote reports while it works is its reasoning.
                    for part in &mut parts {
                        if let Part::Text { text } = part {
                            *part =
                                Part::Thinking { thinking: std::mem::take(text), signature: None };
                        }
                    }
                    let mut event = self.new_event();
                    event.llm_response.content = Some(Content { role: "model".to_string(), parts });
                    apply_metadata(&mut event, update.metadata.as_ref(), None, ids);
                    event.llm_response.partial = true;
                    event.llm_response.turn_complete = false;
                    let _ = TaskState::Working;
                    Some(event)
                }
                _ => None,
            }
        }
    }

    /// The `adk_partial` flag of an update, when the server set one.
    fn partial_flag(response: &a2a_protocol_types::events::StreamResponse) -> Option<bool> {
        use a2a_protocol_types::events::StreamResponse;
        let metadata = match response {
            StreamResponse::ArtifactUpdate(update) => update.metadata.as_ref(),
            StreamResponse::StatusUpdate(update) => update.metadata.as_ref(),
            StreamResponse::Task(task) => task.metadata.as_ref(),
            StreamResponse::Message(message) => message.metadata.as_ref(),
            _ => None,
        };
        metadata
            .and_then(|metadata| metadata.get(crate::a2a::v1::convert::ADK_PARTIAL_METADATA_KEY))
            .and_then(serde_json::Value::as_bool)
    }

    /// Adds `event`'s content and metadata to a chunk aggregation: adjacent text of the same
    /// kind (answer or thought) joins into one part.
    fn aggregate(aggregation: &mut Aggregation, event: &Event) {
        for part in event.content().into_iter().flat_map(|content| &content.parts) {
            match (part, aggregation.parts.last_mut()) {
                (Part::Text { text }, Some(Part::Text { text: last })) => last.push_str(text),
                (Part::Thinking { thinking, .. }, Some(Part::Thinking { thinking: last, .. })) => {
                    last.push_str(thinking);
                }
                (part, _) => aggregation.parts.push(part.clone()),
            }
        }
        if let Some(citations) = &event.llm_response.citation_metadata {
            aggregation.citations.extend(citations.citation_sources.iter().cloned());
        }
        aggregation.custom.extend(event.provider_metadata.clone());
        if event.llm_response.usage_metadata.is_some() {
            aggregation.usage = event.llm_response.usage_metadata.clone();
        }
    }

    /// The agent an update transfers to (`adk_transfer_to_agent` in its own metadata).
    fn transfer_target(response: &a2a_protocol_types::events::StreamResponse) -> Option<String> {
        use a2a_protocol_types::events::StreamResponse;
        let metadata = match response {
            StreamResponse::ArtifactUpdate(update) => update.metadata.as_ref(),
            StreamResponse::StatusUpdate(update) => update.metadata.as_ref(),
            StreamResponse::Task(task) => task.metadata.as_ref(),
            StreamResponse::Message(message) => message.metadata.as_ref(),
            _ => None,
        };
        metadata
            .and_then(|meta| {
                meta.get(crate::a2a::v1::processor::ADK_TRANSFER_TO_AGENT_METADATA_KEY)
            })
            .and_then(serde_json::Value::as_str)
            .filter(|agent| !agent.is_empty())
            .map(str::to_owned)
    }

    /// Whether a task in `state` ends the remote turn: it ended, or it waits on its caller.
    fn is_final_state(state: a2a_protocol_types::task::TaskState) -> bool {
        use a2a_protocol_types::task::TaskState;
        matches!(
            state,
            TaskState::Completed
                | TaskState::Failed
                | TaskState::Canceled
                | TaskState::Rejected
                | TaskState::InputRequired
                | TaskState::AuthRequired
        )
    }

    fn waits(state: a2a_protocol_types::task::TaskState) -> bool {
        matches!(
            state,
            a2a_protocol_types::task::TaskState::InputRequired
                | a2a_protocol_types::task::TaskState::AuthRequired
        )
    }

    /// The ADK parts of A2A parts, without the ones that cannot be read and empty text.
    fn adk_parts(
        parts: &[a2a_protocol_types::Part],
        from_wire: Option<&FromWirePart>,
    ) -> Vec<Part> {
        parts
            .iter()
            .filter_map(|part| match from_wire {
                Some(convert) => convert(part).ok().flatten(),
                None => crate::a2a::v1::convert::wire_part_to_adk(part).ok(),
            })
            .filter(|part| !matches!(part, Part::Text { text } if text.is_empty()))
            .collect()
    }

    /// The wire parts of a task's artifacts and status message, in the order
    /// [`RemoteEvents::to_event`] converts them.
    fn task_parts(task: &a2a_protocol_types::Task) -> Vec<a2a_protocol_types::Part> {
        let mut parts: Vec<_> =
            task.artifacts.iter().flatten().flat_map(|artifact| artifact.parts.clone()).collect();
        parts.extend(task.status.message.iter().flat_map(|message| message.parts.clone()));
        parts
    }

    /// The IDs of the calls among `parts` that the server marks `adk_is_long_running`.
    fn long_running_ids(parts: &[Part], wire: &[a2a_protocol_types::Part]) -> Vec<String> {
        let marked: std::collections::HashSet<String> = wire
            .iter()
            .filter(|part| {
                part.metadata
                    .as_ref()
                    .and_then(|meta| {
                        meta.get(crate::a2a::v1::convert::ADK_LONG_RUNNING_METADATA_KEY)
                    })
                    .and_then(serde_json::Value::as_bool)
                    == Some(true)
            })
            .filter_map(|part| match &part.content {
                a2a_protocol_types::PartContent::Data(data) => {
                    data.get("id").and_then(serde_json::Value::as_str).map(str::to_owned)
                }
                _ => None,
            })
            .collect();
        parts
            .iter()
            .filter_map(|part| match part {
                Part::FunctionCall { id: Some(id), .. } if marked.contains(id) => Some(id.clone()),
                _ => None,
            })
            .collect()
    }

    /// A status message's content, and the error text of a `FAILED` status.
    struct StatusMessage {
        parts: Vec<Part>,
        error: Option<String>,
    }

    fn status_message(
        state: a2a_protocol_types::task::TaskState,
        message: Option<&a2a_protocol_types::Message>,
        from_wire: Option<&FromWirePart>,
    ) -> StatusMessage {
        let failed = state == a2a_protocol_types::task::TaskState::Failed;
        let Some(message) = message else {
            return StatusMessage {
                parts: Vec::new(),
                error: failed.then(|| "a2a task failed".to_string()),
            };
        };
        let mut wire = message.parts.as_slice();
        let mut error = None;
        if failed
            && let Some(first) = wire.first()
            && let Some(text) = first.text_content().filter(|t| !t.is_empty())
        {
            error = Some(text.to_string());
            let marked = first
                .metadata
                .as_ref()
                .and_then(|meta| meta.get(crate::a2a::v1::convert::ADK_ERROR_MESSAGE_METADATA_KEY))
                .and_then(serde_json::Value::as_bool)
                == Some(true);
            if marked {
                wire = &wire[1..];
            }
        }
        if failed && error.is_none() {
            error = Some("a2a task failed".to_string());
        }
        StatusMessage { parts: adk_parts(wire, from_wire), error }
    }

    /// Reads an update's ADK metadata into `event`, as adk-go's `processA2AMeta`: the
    /// artifact's metadata over the update's, then citations, usage, custom metadata (with
    /// the remote task and context as `a2a:task_id` and `a2a:context_id`), the error code,
    /// and escalation from the update's own metadata.
    fn apply_metadata(
        event: &mut Event,
        update_meta: Option<&serde_json::Value>,
        artifact_meta: Option<&serde_json::Value>,
        ids: Option<(&str, &str)>,
    ) {
        use crate::a2a::v1::processor::{
            ADK_CITATION_METADATA_KEY, ADK_CUSTOM_METADATA_KEY, ADK_ERROR_CODE_METADATA_KEY,
            ADK_ESCALATE_METADATA_KEY, ADK_USAGE_METADATA_KEY,
        };
        let mut meta =
            update_meta.and_then(serde_json::Value::as_object).cloned().unwrap_or_default();
        if let Some(artifact) = artifact_meta.and_then(serde_json::Value::as_object) {
            meta.extend(artifact.clone());
        }
        if let Some(citations) = meta
            .get(ADK_CITATION_METADATA_KEY)
            .and_then(|c| c.get("citations"))
            .and_then(serde_json::Value::as_array)
        {
            let sources = citations
                .iter()
                .map(|citation| {
                    let text = |key: &str| {
                        citation.get(key).and_then(serde_json::Value::as_str).map(str::to_owned)
                    };
                    let index = |key: &str| {
                        citation.get(key).and_then(serde_json::Value::as_i64).map(|v| v as i32)
                    };
                    adk_core::CitationSource {
                        uri: text("uri"),
                        title: text("title"),
                        start_index: index("startIndex"),
                        end_index: index("endIndex"),
                        license: text("license"),
                        publication_date: text("publicationDate"),
                    }
                })
                .collect();
            event.llm_response.citation_metadata =
                Some(adk_core::CitationMetadata { citation_sources: sources });
        }
        if let Some(usage) = meta.get(ADK_USAGE_METADATA_KEY) {
            let count =
                |key: &str| usage.get(key).and_then(serde_json::Value::as_i64).map(|v| v as i32);
            event.llm_response.usage_metadata = Some(adk_core::UsageMetadata {
                prompt_token_count: count("promptTokenCount").unwrap_or_default(),
                candidates_token_count: count("candidatesTokenCount").unwrap_or_default(),
                total_token_count: count("totalTokenCount").unwrap_or_default(),
                cache_read_input_token_count: count("cachedContentTokenCount"),
                thinking_token_count: count("thoughtsTokenCount"),
                ..Default::default()
            });
        }
        if let Some((task_id, context_id)) = ids {
            event.provider_metadata.insert(A2A_TASK_ID_KEY.to_string(), task_id.to_string());
            event.provider_metadata.insert(A2A_CONTEXT_ID_KEY.to_string(), context_id.to_string());
        }
        if let Some(custom) =
            meta.get(ADK_CUSTOM_METADATA_KEY).and_then(serde_json::Value::as_object)
        {
            for (key, value) in custom {
                let value = value.as_str().map_or_else(|| value.to_string(), str::to_owned);
                event.provider_metadata.insert(key.clone(), value);
            }
        }
        if let Some(code) =
            meta.get(ADK_ERROR_CODE_METADATA_KEY).and_then(serde_json::Value::as_str)
        {
            event.llm_response.error_code = Some(code.to_string());
        }
        let escalate = update_meta
            .and_then(|meta| meta.get(ADK_ESCALATE_METADATA_KEY))
            .and_then(serde_json::Value::as_bool)
            == Some(true);
        event.actions.escalate = escalate;
    }

    /// Event metadata key of the remote task an event came from, as adk-go names it.
    pub const A2A_TASK_ID_KEY: &str = "a2a:task_id";
    /// Event metadata key of the remote context an event came from, as adk-go names it.
    pub const A2A_CONTEXT_ID_KEY: &str = "a2a:context_id";

    /// Ends a remote turn on `event`: saves the remote conversation in session state for
    /// the next turn. The remote task is kept only while it waits on this side.
    fn end_turn(
        mut event: Event,
        resp: &a2a_protocol_types::events::StreamResponse,
        keys: &RemoteKeys,
    ) -> Event {
        use a2a_protocol_types::events::StreamResponse;

        event.llm_response.turn_complete = true;
        let (context_id, task_id, state) = match resp {
            StreamResponse::StatusUpdate(update) => (
                Some(update.context_id.0.clone()),
                Some(update.task_id.0.clone()),
                Some(update.status.state),
            ),
            StreamResponse::Task(task) => {
                (Some(task.context_id.0.clone()), Some(task.id.0.clone()), Some(task.status.state))
            }
            StreamResponse::Message(message) => {
                (message.context_id.as_ref().map(|c| c.0.clone()), None, None)
            }
            _ => (None, None, None),
        };
        let waiting = state.is_some_and(waits);
        if let Some(context_id) = context_id {
            event.actions.state_delta.insert(keys.context_id.clone(), context_id.into());
        }
        let task_id = task_id.filter(|_| waiting);
        event.actions.state_delta.insert(
            keys.task_id.clone(),
            task_id.map_or(serde_json::Value::Null, serde_json::Value::String),
        );
        event
    }

    /// Whether `response` is the last of its stream: a direct message, or a task or status
    /// in a state the task stops in.
    fn ends_stream(response: &a2a_protocol_types::events::StreamResponse) -> bool {
        use a2a_protocol_types::events::StreamResponse;
        match response {
            StreamResponse::StatusUpdate(update) => is_final_state(update.status.state),
            StreamResponse::Task(task) => is_final_state(task.status.state),
            StreamResponse::Message(_) => true,
            _ => false,
        }
    }

    /// Creates an error event for the v1 remote agent.
    fn create_v1_error_event(invocation_id: &str, agent_name: &str, error: &str) -> Event {
        let mut event = Event::new(invocation_id.to_string());
        event.author = agent_name.to_string();
        event.llm_response.error_message = Some(error.to_string());
        event.llm_response.turn_complete = true;
        event
    }

    #[cfg(test)]
    mod tests {
        use super::*;
        use a2a_protocol_types::{AgentCapabilities, AgentInterface, AgentSkill};

        fn make_test_card() -> AgentCard {
            AgentCard {
                name: "test-v1-agent".to_string(),
                url: Some("http://localhost:9999".to_string()),
                description: "A test v1 agent".to_string(),
                version: "1.0.0".to_string(),
                supported_interfaces: vec![
                    AgentInterface {
                        url: "http://localhost:9999/a2a".to_string(),
                        protocol_binding: "JSONRPC".to_string(),
                        protocol_version: "1.0".to_string(),
                        tenant: None,
                    },
                    AgentInterface {
                        url: "http://localhost:9999/rest".to_string(),
                        protocol_binding: "HTTP+JSON".to_string(),
                        protocol_version: "1.0".to_string(),
                        tenant: None,
                    },
                ],
                default_input_modes: vec!["text/plain".to_string()],
                default_output_modes: vec!["text/plain".to_string()],
                skills: vec![AgentSkill {
                    id: "echo".to_string(),
                    name: "Echo".to_string(),
                    description: "Echoes input".to_string(),
                    tags: vec![],
                    examples: None,
                    input_modes: None,
                    output_modes: None,
                    security_requirements: None,
                }],
                capabilities: AgentCapabilities::default(),
                provider: None,
                icon_url: None,
                documentation_url: None,
                security_schemes: None,
                security_requirements: None,
                signatures: None,
            }
        }

        #[test]
        fn select_interface_prefers_jsonrpc() {
            let card = make_test_card();
            let selected = RemoteA2aV1Agent::select_interface(&card).unwrap();
            assert_eq!(selected.protocol_binding, "JSONRPC");
            assert_eq!(selected.url, "http://localhost:9999/a2a");
        }

        #[test]
        fn select_interface_falls_back_to_http_json() {
            let mut card = make_test_card();
            card.supported_interfaces.retain(|i| i.protocol_binding != "JSONRPC");
            let selected = RemoteA2aV1Agent::select_interface(&card).unwrap();
            assert_eq!(selected.protocol_binding, "HTTP+JSON");
            assert_eq!(selected.url, "http://localhost:9999/rest");
        }

        #[test]
        fn select_interface_returns_none_for_unsupported() {
            let mut card = make_test_card();
            card.supported_interfaces = vec![AgentInterface {
                url: "grpc://localhost:9999".to_string(),
                protocol_binding: "GRPC".to_string(),
                protocol_version: "1.0".to_string(),
                tenant: None,
            }];
            assert!(RemoteA2aV1Agent::select_interface(&card).is_none());
        }

        #[test]
        fn select_interface_returns_none_for_empty() {
            let mut card = make_test_card();
            card.supported_interfaces = vec![];
            assert!(RemoteA2aV1Agent::select_interface(&card).is_none());
        }

        #[test]
        fn new_agent_stores_config() {
            let card = make_test_card();
            let agent = RemoteA2aV1Agent::new(RemoteA2aV1Config {
                name: "my-agent".to_string(),
                description: "My remote agent".to_string(),
                agent_card: card,
                // The wire default: let the card decide rather than forcing a mode.
                streaming: None,
                credential_broker: None,
                credential_scopes: Vec::new(),
                send_configuration: None,
                hooks: Default::default(),
            });
            assert_eq!(agent.name(), "my-agent");
            assert_eq!(agent.description(), "My remote agent");
        }

        #[test]
        fn agent_has_no_sub_agents() {
            let card = make_test_card();
            let agent = RemoteA2aV1Agent::new(RemoteA2aV1Config {
                name: "test".to_string(),
                description: "test".to_string(),
                agent_card: card,
                // The wire default: let the card decide rather than forcing a mode.
                streaming: None,
                credential_broker: None,
                credential_scopes: Vec::new(),
                send_configuration: None,
                hooks: Default::default(),
            });
            assert!(agent.sub_agents().is_empty());
        }

        #[test]
        fn build_v1_message_with_content() {
            let msg = build_v1_message(vec![a2a_protocol_types::Part::text("hello")], None, None);
            assert_eq!(msg.role, a2a_protocol_types::MessageRole::User);
            assert_eq!(msg.parts.len(), 1);
            assert_eq!(msg.parts[0].text_content(), Some("hello"));
            assert!(msg.context_id.is_none() && msg.task_id.is_none());
        }

        #[test]
        fn build_v1_message_without_content() {
            let msg = build_v1_message(Vec::new(), None, None);
            assert_eq!(msg.parts[0].text_content(), Some(""));
        }

        #[test]
        fn a_message_continues_the_remote_conversation_and_its_waiting_task() {
            let msg = build_v1_message(
                vec![a2a_protocol_types::Part::text("again")],
                Some("ctx-7".to_string()),
                Some("task-7".to_string()),
            );
            assert_eq!(msg.context_id.unwrap().0, "ctx-7");
            assert_eq!(msg.task_id.unwrap().0, "task-7");
        }

        #[test]
        fn answers_and_media_go_out_in_the_shape_every_sdk_reads() {
            let answer = outgoing_part(&Part::FunctionResponse {
                function_response: adk_core::FunctionResponseData::new(
                    "request_approval",
                    serde_json::json!({"status": "approved"}),
                ),
                id: Some("call-1".to_string()),
                annotations: None,
            })
            .unwrap();
            assert_eq!(
                serde_json::to_value(&answer).unwrap(),
                serde_json::json!({
                    "data": {"id": "call-1", "name": "request_approval", "response": {"status": "approved"}},
                    "metadata": {"adk_type": "function_response"}
                })
            );
            let image = outgoing_part(&Part::InlineData {
                mime_type: "image/png".to_string(),
                data: vec![1, 2, 3],
                uri: None,
                annotations: None,
            })
            .unwrap();
            assert_eq!(image.media_type.as_deref(), Some("image/png"));
            let thought =
                outgoing_part(&Part::Thinking { thinking: "hm".into(), signature: None }).unwrap();
            assert_eq!(thought.text_content(), Some("hm"));
            assert_eq!(thought.metadata.unwrap()["adk_thought"], true, "a thought stays a thought");
        }

        #[test]
        fn a_waiting_remote_ends_the_turn_on_its_pending_call_and_keeps_its_task() {
            use crate::a2a::v1::convert::{
                tagged_function_call_part, tagged_function_response_part,
            };
            use a2a_protocol_types::events::{StreamResponse, TaskStatusUpdateEvent};
            use a2a_protocol_types::task::{ContextId, TaskId, TaskState, TaskStatus};

            let mut status = TaskStatus::new(TaskState::InputRequired);
            status.message = Some(a2a_protocol_types::Message {
                id: a2a_protocol_types::MessageId::new("m"),
                role: a2a_protocol_types::MessageRole::Agent,
                parts: vec![
                    tagged_function_call_part(
                        "request_approval",
                        &serde_json::json!({"amount": 5}),
                        Some("call-1"),
                        true,
                    ),
                    tagged_function_response_part(
                        "request_approval",
                        &serde_json::json!({"status": "pending"}),
                        Some("call-1"),
                    ),
                ],
                task_id: None,
                context_id: None,
                reference_task_ids: None,
                extensions: None,
                metadata: None,
            });
            let resp = StreamResponse::StatusUpdate(TaskStatusUpdateEvent {
                task_id: TaskId::new("task-1"),
                context_id: ContextId::new("ctx-1"),
                status,
                metadata: None,
            });
            let keys = RemoteKeys::for_agent("remote");
            let event = finish(&resp, &keys);

            assert!(event.llm_response.turn_complete);
            assert_eq!(event.long_running_tool_ids, vec!["call-1".to_string()]);
            let parts = &event.llm_response.content.as_ref().unwrap().parts;
            assert!(
                matches!(&parts[0], Part::FunctionCall { name, .. } if name == "request_approval")
            );
            assert_eq!(event.actions.state_delta[&keys.context_id], "ctx-1");
            assert_eq!(event.actions.state_delta[&keys.task_id], "task-1");

            // A finished remote task is not kept.
            let done = StreamResponse::StatusUpdate(TaskStatusUpdateEvent {
                task_id: TaskId::new("task-1"),
                context_id: ContextId::new("ctx-1"),
                status: TaskStatus::new(TaskState::Completed),
                metadata: None,
            });
            let event = finish(&done, &keys);
            assert_eq!(event.actions.state_delta[&keys.context_id], "ctx-1");
            assert!(event.actions.state_delta[&keys.task_id].is_null());
        }

        /// The event a remote turn ends on, as the agent's run builds it.
        fn finish(resp: &a2a_protocol_types::events::StreamResponse, keys: &RemoteKeys) -> Event {
            let mut remote = RemoteEvents::new("inv", "remote");
            let event = remote.handle(resp).pop().unwrap_or_else(|| remote.new_event());
            end_turn(event, resp, keys)
        }

        #[test]
        fn stream_payloads_parse_bare_wrapped_and_error_forms() {
            use a2a_protocol_types::events::StreamResponse;
            use a2a_protocol_types::task::{ContextId, TaskId, TaskState, TaskStatus};

            let update =
                StreamResponse::StatusUpdate(a2a_protocol_types::events::TaskStatusUpdateEvent {
                    task_id: TaskId::new("t1"),
                    context_id: ContextId::new("c1"),
                    status: TaskStatus::new(TaskState::InputRequired),
                    metadata: None,
                });
            let bare = serde_json::to_string(&update).unwrap();
            let wrapped =
                serde_json::json!({"jsonrpc": "2.0", "id": 1, "result": update}).to_string();
            use crate::a2a::client::v1_client::{V1ClientError, parse_stream_payload};
            for data in [bare, wrapped] {
                let parsed = parse_stream_payload(&data).unwrap().unwrap();
                assert!(ends_stream(&parsed));
            }

            let error = r#"{"jsonrpc":"2.0","id":1,"error":{"code":-32603,"message":"boom"}}"#;
            assert!(matches!(
                parse_stream_payload(error).unwrap(),
                Err(V1ClientError::JsonRpc { code: -32603, ref message, .. }) if message == "boom"
            ));
            assert!(parse_stream_payload("not json").is_none());
        }

        #[test]
        fn working_and_artifact_updates_do_not_end_a_stream() {
            use a2a_protocol_types::events::StreamResponse;
            use a2a_protocol_types::task::{ContextId, TaskId, TaskState, TaskStatus};

            let working =
                StreamResponse::StatusUpdate(a2a_protocol_types::events::TaskStatusUpdateEvent {
                    task_id: TaskId::new("t1"),
                    context_id: ContextId::new("c1"),
                    status: TaskStatus::new(TaskState::Working),
                    metadata: None,
                });
            assert!(!ends_stream(&working));
            let artifact = StreamResponse::ArtifactUpdate(
                a2a_protocol_types::events::TaskArtifactUpdateEvent {
                    task_id: TaskId::new("t1"),
                    context_id: ContextId::new("c1"),
                    artifact: a2a_protocol_types::artifact::Artifact::new(
                        a2a_protocol_types::ArtifactId::new("a1"),
                        vec![a2a_protocol_types::Part::text("hi")],
                    ),
                    append: None,
                    last_chunk: Some(true),
                    metadata: None,
                },
            );
            assert!(!ends_stream(&artifact));
        }

        #[test]
        fn convert_status_update_with_message() {
            use a2a_protocol_types::events::TaskStatusUpdateEvent;
            use a2a_protocol_types::task::{ContextId, TaskId, TaskState, TaskStatus};

            let mut status = TaskStatus::new(TaskState::Completed);
            status.message = Some(a2a_protocol_types::Message {
                id: a2a_protocol_types::MessageId::new("msg-1"),
                role: a2a_protocol_types::MessageRole::Agent,
                parts: vec![a2a_protocol_types::Part::text("done!")],
                task_id: None,
                context_id: None,
                reference_task_ids: None,
                extensions: None,
                metadata: None,
            });

            let status_event = TaskStatusUpdateEvent {
                task_id: TaskId::new("task-1"),
                context_id: ContextId::new("ctx-1"),
                status,
                metadata: None,
            };

            let resp = a2a_protocol_types::events::StreamResponse::StatusUpdate(status_event);
            let event = RemoteEvents::new("inv-1", "agent-1").to_event(&resp).unwrap();

            assert_eq!(event.author, "agent-1");
            assert!(event.llm_response.turn_complete);
            let content = event.llm_response.content.unwrap();
            assert_eq!(content.parts.len(), 1);
            match &content.parts[0] {
                Part::Text { text } => assert_eq!(text, "done!"),
                _ => panic!("expected text part"),
            }
        }

        #[test]
        fn convert_status_update_terminal_without_message() {
            use a2a_protocol_types::events::TaskStatusUpdateEvent;
            use a2a_protocol_types::task::{ContextId, TaskId, TaskState, TaskStatus};

            let status_event = TaskStatusUpdateEvent {
                task_id: TaskId::new("task-1"),
                context_id: ContextId::new("ctx-1"),
                status: TaskStatus::new(TaskState::Failed),
                metadata: None,
            };

            let resp = a2a_protocol_types::events::StreamResponse::StatusUpdate(status_event);
            let event = RemoteEvents::new("inv-1", "agent-1").to_event(&resp).unwrap();

            assert!(event.llm_response.turn_complete);
            assert!(event.llm_response.content.is_none());
        }

        #[test]
        fn a_failed_status_message_is_the_remote_error() {
            use a2a_protocol_types::events::TaskStatusUpdateEvent;
            use a2a_protocol_types::task::{ContextId, TaskId, TaskState, TaskStatus};

            let failed = |parts: Vec<a2a_protocol_types::Part>| {
                let mut status = TaskStatus::new(TaskState::Failed);
                status.message = Some(a2a_protocol_types::Message {
                    id: a2a_protocol_types::MessageId::new("status-msg-1"),
                    role: a2a_protocol_types::MessageRole::Agent,
                    parts,
                    task_id: None,
                    context_id: None,
                    reference_task_ids: None,
                    extensions: None,
                    metadata: None,
                });
                a2a_protocol_types::events::StreamResponse::StatusUpdate(TaskStatusUpdateEvent {
                    task_id: TaskId::new("task-1"),
                    context_id: ContextId::new("ctx-1"),
                    status,
                    metadata: None,
                })
            };

            // An ADK server marks its error text: it is the error, not model output.
            let marked = failed(vec![
                crate::a2a::v1::convert::error_message_part("Internal error: agent error: boom"),
                a2a_protocol_types::Part::text("partial answer"),
            ]);
            let event = RemoteEvents::new("inv-1", "agent-1").to_event(&marked).unwrap();
            assert_eq!(
                event.llm_response.error_message.as_deref(),
                Some("Internal error: agent error: boom")
            );
            let texts: Vec<_> =
                event.content().unwrap().parts.iter().filter_map(Part::text).collect();
            assert_eq!(texts, ["partial answer"], "the rest of the message is content");
            assert!(event.llm_response.turn_complete);

            // Unmarked, the first text is still the error and stays in the content, as
            // adk-go reads it; with no message the error is generic.
            let unmarked = failed(vec![a2a_protocol_types::Part::text("boom")]);
            let event = RemoteEvents::new("inv-1", "agent-1").to_event(&unmarked).unwrap();
            assert_eq!(event.llm_response.error_message.as_deref(), Some("boom"));
            assert_eq!(event.content().unwrap().parts.len(), 1);
        }

        fn artifact_update(
            id: &str,
            text: &str,
            append: Option<bool>,
            last_chunk: Option<bool>,
            metadata: Option<serde_json::Value>,
        ) -> a2a_protocol_types::events::StreamResponse {
            a2a_protocol_types::events::StreamResponse::ArtifactUpdate(
                a2a_protocol_types::events::TaskArtifactUpdateEvent {
                    task_id: a2a_protocol_types::TaskId::new("task-1"),
                    context_id: a2a_protocol_types::ContextId::new("ctx-1"),
                    artifact: a2a_protocol_types::Artifact::new(
                        a2a_protocol_types::ArtifactId::new(id),
                        vec![a2a_protocol_types::Part::text(text)],
                    ),
                    append,
                    last_chunk,
                    metadata,
                },
            )
        }

        fn completed() -> a2a_protocol_types::events::StreamResponse {
            a2a_protocol_types::events::StreamResponse::StatusUpdate(
                a2a_protocol_types::events::TaskStatusUpdateEvent {
                    task_id: a2a_protocol_types::TaskId::new("task-1"),
                    context_id: a2a_protocol_types::ContextId::new("ctx-1"),
                    status: a2a_protocol_types::TaskStatus::new(
                        a2a_protocol_types::TaskState::Completed,
                    ),
                    metadata: None,
                },
            )
        }

        fn stored_text(events: &[Event]) -> Vec<String> {
            events
                .iter()
                .filter(|event| !event.llm_response.partial)
                .filter_map(|event| event.content())
                .map(|content| content.parts.iter().filter_map(Part::text).collect())
                .filter(|text: &String| !text.is_empty())
                .collect()
        }

        #[test]
        fn chunks_from_a_go_server_are_partial_and_join_into_one_answer() {
            // a2a-go leaves `lastChunk` out when it is false.
            let mut remote = RemoteEvents::new("inv", "remote");
            let mut events = Vec::new();
            events.extend(remote.handle(&artifact_update("a", "Hel", None, None, None)));
            events.extend(remote.handle(&artifact_update("a", "lo", Some(true), None, None)));
            events.extend(remote.handle(&completed()));

            assert!(events[0].llm_response.partial && events[1].llm_response.partial);
            assert_eq!(stored_text(&events), ["Hello"], "the session keeps the whole answer once");
        }

        #[test]
        fn a_last_chunk_closes_its_artifacts_answer() {
            let mut remote = RemoteEvents::new("inv", "remote");
            let mut events = Vec::new();
            events.extend(remote.handle(&artifact_update("a", "one ", None, Some(false), None)));
            events.extend(remote.handle(&artifact_update(
                "a",
                "two",
                Some(true),
                Some(true),
                None,
            )));
            events.extend(remote.handle(&completed()));
            assert_eq!(stored_text(&events), ["one two"]);
        }

        #[test]
        fn an_adk_servers_partial_artifact_and_its_reset_are_not_stored() {
            let partial = Some(serde_json::json!({"adk_partial": true}));
            let answer = Some(serde_json::json!({"adk_partial": false}));
            let mut remote = RemoteEvents::new("inv", "remote");
            let mut events = Vec::new();
            events.extend(remote.handle(&artifact_update(
                "tmp",
                "Hel",
                Some(false),
                None,
                partial.clone(),
            )));
            events.extend(remote.handle(&artifact_update(
                "main",
                "Hello",
                Some(false),
                None,
                answer,
            )));
            // The server empties its temporary artifact before the final status.
            let reset = a2a_protocol_types::events::StreamResponse::ArtifactUpdate(
                a2a_protocol_types::events::TaskArtifactUpdateEvent {
                    task_id: a2a_protocol_types::TaskId::new("task-1"),
                    context_id: a2a_protocol_types::ContextId::new("ctx-1"),
                    artifact: a2a_protocol_types::Artifact::new(
                        a2a_protocol_types::ArtifactId::new("tmp"),
                        vec![a2a_protocol_types::Part::data(serde_json::json!({}))],
                    ),
                    append: Some(false),
                    last_chunk: Some(true),
                    metadata: partial,
                },
            );
            assert!(remote.handle(&reset).is_empty(), "the reset is dropped");
            events.extend(remote.handle(&completed()));
            assert_eq!(stored_text(&events), ["Hello"]);
        }

        #[test]
        fn a_transfer_the_remote_names_is_followed_only_when_allowed() {
            use a2a_protocol_types::task::{TaskState, TaskStatus};
            let done = a2a_protocol_types::events::StreamResponse::StatusUpdate(
                a2a_protocol_types::events::TaskStatusUpdateEvent {
                    task_id: a2a_protocol_types::TaskId::new("task-1"),
                    context_id: a2a_protocol_types::ContextId::new("ctx-1"),
                    status: TaskStatus::new(TaskState::Completed),
                    metadata: Some(serde_json::json!({"adk_transfer_to_agent": "billing"})),
                },
            );
            let ignored = RemoteEvents::new("inv", "remote").handle(&done);
            assert_eq!(ignored.last().unwrap().actions.transfer_to_agent, None, "off by default");
            let hooks = RemoteAgentHooks::default().allow_transfer_to_agent(true);
            let followed = RemoteEvents::new("inv", "remote").with_hooks(&hooks).handle(&done);
            assert_eq!(
                followed.last().unwrap().actions.transfer_to_agent.as_deref(),
                Some("billing")
            );
        }

        #[test]
        fn progress_before_the_task_ends_is_the_remotes_reasoning() {
            use a2a_protocol_types::task::{TaskState, TaskStatus};
            let mut status = TaskStatus::new(TaskState::Working);
            status.message = Some(a2a_protocol_types::Message {
                id: a2a_protocol_types::MessageId::new("m"),
                role: a2a_protocol_types::MessageRole::Agent,
                parts: vec![a2a_protocol_types::Part::text("looking it up")],
                task_id: None,
                context_id: None,
                reference_task_ids: None,
                extensions: None,
                metadata: None,
            });
            let working = a2a_protocol_types::events::StreamResponse::StatusUpdate(
                a2a_protocol_types::events::TaskStatusUpdateEvent {
                    task_id: a2a_protocol_types::TaskId::new("task-1"),
                    context_id: a2a_protocol_types::ContextId::new("ctx-1"),
                    status,
                    metadata: Some(
                        serde_json::json!({"adk_escalate": true, "adk_error_code": "E1"}),
                    ),
                },
            );
            let event = RemoteEvents::new("inv", "remote").to_event(&working).unwrap();
            assert!(event.llm_response.partial && !event.llm_response.turn_complete);
            assert!(
                matches!(&event.content().unwrap().parts[0], Part::Thinking { thinking, .. } if thinking == "looking it up")
            );
            assert!(event.actions.escalate);
            assert_eq!(event.llm_response.error_code.as_deref(), Some("E1"));
            assert_eq!(event.provider_metadata[A2A_TASK_ID_KEY], "task-1");
            assert_eq!(event.provider_metadata[A2A_CONTEXT_ID_KEY], "ctx-1");
        }

        #[test]
        fn a_direct_message_reply_ends_the_turn_with_its_text() {
            let reply = a2a_protocol_types::Message {
                id: a2a_protocol_types::MessageId::new("m-1"),
                role: a2a_protocol_types::MessageRole::Agent,
                parts: vec![a2a_protocol_types::Part::text("hello there")],
                task_id: None,
                context_id: None,
                reference_task_ids: None,
                extensions: None,
                metadata: None,
            };
            let resp = a2a_protocol_types::events::StreamResponse::Message(reply);

            let event = RemoteEvents::new("inv-1", "agent-1").to_event(&resp).unwrap();
            assert_eq!(event.author, "agent-1");
            assert!(event.llm_response.turn_complete);
            let text: String = event
                .llm_response
                .content
                .expect("content")
                .parts
                .iter()
                .filter_map(Part::text)
                .collect();
            assert_eq!(text, "hello there");
        }

        #[test]
        fn convert_status_update_non_terminal_without_message() {
            use a2a_protocol_types::events::TaskStatusUpdateEvent;
            use a2a_protocol_types::task::{ContextId, TaskId, TaskState, TaskStatus};

            let status_event = TaskStatusUpdateEvent {
                task_id: TaskId::new("task-1"),
                context_id: ContextId::new("ctx-1"),
                status: TaskStatus::new(TaskState::Working),
                metadata: None,
            };

            let resp = a2a_protocol_types::events::StreamResponse::StatusUpdate(status_event);
            let result = RemoteEvents::new("inv-1", "agent-1").to_event(&resp);

            // Non-terminal without message produces no event
            assert!(result.is_none());
        }

        #[test]
        fn convert_artifact_update_with_text() {
            use a2a_protocol_types::artifact::{Artifact, ArtifactId};
            use a2a_protocol_types::events::TaskArtifactUpdateEvent;
            use a2a_protocol_types::task::{ContextId, TaskId};

            let artifact_event = TaskArtifactUpdateEvent {
                task_id: TaskId::new("task-1"),
                context_id: ContextId::new("ctx-1"),
                artifact: Artifact {
                    id: ArtifactId::new("art-1"),
                    name: Some("result".to_string()),
                    description: None,
                    parts: vec![a2a_protocol_types::Part::text("artifact content")],
                    extensions: None,
                    metadata: None,
                },
                append: None,
                last_chunk: Some(true),
                metadata: None,
            };

            let resp = a2a_protocol_types::events::StreamResponse::ArtifactUpdate(artifact_event);
            let event = RemoteEvents::new("inv-1", "agent-1").to_event(&resp).unwrap();

            assert_eq!(event.author, "agent-1");
            let content = event.llm_response.content.unwrap();
            assert_eq!(content.parts.len(), 1);
            match &content.parts[0] {
                Part::Text { text } => assert_eq!(text, "artifact content"),
                _ => panic!("expected text part"),
            }
            // last_chunk=true means partial=false
            assert!(!event.llm_response.partial);
        }

        #[test]
        fn convert_artifact_update_partial() {
            use a2a_protocol_types::artifact::{Artifact, ArtifactId};
            use a2a_protocol_types::events::TaskArtifactUpdateEvent;
            use a2a_protocol_types::task::{ContextId, TaskId};

            let artifact_event = TaskArtifactUpdateEvent {
                task_id: TaskId::new("task-1"),
                context_id: ContextId::new("ctx-1"),
                artifact: Artifact {
                    id: ArtifactId::new("art-1"),
                    name: None,
                    description: None,
                    parts: vec![a2a_protocol_types::Part::text("partial...")],
                    extensions: None,
                    metadata: None,
                },
                append: None,
                last_chunk: Some(false),
                metadata: None,
            };

            let resp = a2a_protocol_types::events::StreamResponse::ArtifactUpdate(artifact_event);
            let event = RemoteEvents::new("inv-1", "agent-1").to_event(&resp).unwrap();

            assert!(event.llm_response.partial);
        }

        #[test]
        fn create_v1_error_event_sets_fields() {
            let event = create_v1_error_event("inv-1", "agent-1", "something broke");
            assert_eq!(event.author, "agent-1");
            assert_eq!(event.llm_response.error_message.as_deref(), Some("something broke"));
            assert!(event.llm_response.turn_complete);
        }
    }
}