lc-a2a 0.14.0

A2A (Agent-to-Agent) protocol support for langchainrust — client, server, and protocol types.
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
//! A2A Server - handler functions for the Agent-to-Agent protocol.
//!
//! Provides `A2AServer` which holds an underlying agent (a `BaseChain`) and
//! exposes handler functions that can be plugged into any HTTP framework
//! (axum, actix, warp, etc.) rather than running its own server.
//!
//! # Endpoints
//!
//! - `GET /.well-known/agent-card.json` -> returns `AgentCard` (via `get_agent_card`)
//! - `POST /` -> accepts `A2ARequest`, dispatches, returns `A2AResponse`
//!   (via `handle_a2a_request` / `handle_a2a_request_authenticated`)
//!
//! # Task Model
//!
//! `tasks/send` follows the A2A asynchronous task lifecycle. The request is
//! acknowledged immediately with a `submitted` task and the chain runs in the
//! background, transitioning the task `submitted -> working -> completed`
//! (or `failed`). Poll `tasks/get` to observe progress. Every transition is
//! guarded by the [`TaskStatus`] state machine, so a task cancelled while the
//! chain is still running is never clobbered back to a live state.
//!
//! # Multi-turn & Input-Required (P2-2/P2-3)
//!
//! Re-sending `tasks/send` with a `taskId` appends a message to the existing
//! task's history and re-runs the chain over the whole conversation. A chain
//! that needs more information returns a `ChainError::MissingInput` /
//! `ChainError::InputError`, which the server maps to the `input-required`
//! state; the client then resumes with `tasks/send {taskId, message}`.
//!
//! # Ownership & Idempotency (P1-4/P1-6)
//!
//! Tasks carry an optional `owner` taken from request metadata. `tasks/get`
//! and `tasks/cancel` from a caller whose metadata `owner` does not match the
//! task's are rejected (`-32003`). A `message_id` in request metadata makes
//! `tasks/send` idempotent: re-sending the same id returns the already
//! created task instead of running the chain twice.
//!
//! # Task Persistence (P1-1)
//!
//! Tasks are stored through the [`TaskStore`] trait, defaulting to an
//! in-memory [`InMemoryTaskStore`] shared with background workers. Swap in
//! your own backend with [`A2AServer::with_store`]. Terminal tasks older than
//! the configured TTL are cleaned up lazily on read access.
//!
//! # Streaming (P2-1)
//!
//! Enable [`A2AServer::with_streaming`] to get a `broadcast` channel of
//! [`TaskPushNotification`]s (`subscribe()`), which an HTTP layer can expose
//! as an SSE endpoint. The agent card then advertises `{"sse": true}`.
//!
//! # Skill routing (P2-4)
//!
//! [`A2AServer::with_skill_router`] dispatches `tasks/send` requests that
//! carry a `skillId` param to a different chain based on the card's skills.
//!
//! # Example
//!
//! ```ignore
//! use lc_a2a::{A2AServer, AgentCard};
//! use lc_chains::LLMChain;
//! use std::sync::Arc;
//!
//! let chain = Arc::new(LLMChain::new(llm, "You are a helpful assistant"));
//! let server = A2AServer::new(chain)
//!     .with_card(AgentCard::new("my-agent", "A helpful agent", "http://localhost:8080"));
//!
//! // In your HTTP handler:
//! let response = server.handle_a2a_request(request).await;
//! ```

use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;

use serde_json::{json, Value};
use tokio::sync::{broadcast, RwLock};

use lc_agents::AgentExecutor;
use lc_chains::base::{BaseChain, ChainError, ChainResult};

use super::agent_adapter::AgentExecutorChain;

use super::protocol::{
    A2AErrorData, A2AMessage, A2ARequest, A2AResponse, A2ATask, A2ATaskResult, A2AWorkflow,
    AgentCard, AgentSkill, TaskFilter, TaskPushNotification, TaskStatus,
};
use super::rate_limiter::RateLimiter;
use super::router::{SkillMapRouter, SkillRouter};
use super::store::{InMemoryTaskStore, StoredTask, TaskStore, DEFAULT_MAX_TASKS};

/// Default task time-to-live before expiry cleanup (24 hours).
const DEFAULT_TASK_TTL: Duration = Duration::from_secs(24 * 60 * 60);

/// A2A Server - wraps an agent and provides handler functions.
///
/// The server does NOT start its own HTTP listener. Instead, it provides
/// `handle_a2a_request()` and `get_agent_card()` that you can call from
/// any HTTP framework's route handler.
///
/// Tasks are stored through the [`TaskStore`] trait so that `tasks/get` can
/// retrieve them and `tasks/cancel` can transition their status. When the
/// default in-memory store exceeds its capacity, the least recently updated
/// task is evicted (LRU).
pub struct A2AServer {
    /// The underlying chain/agent.
    chain: Arc<dyn BaseChain>,
    /// The agent card metadata.
    card: AgentCard,
    /// Task persistence backend (P1-1).
    store: Arc<dyn TaskStore>,
    /// `message_id -> task_id` map for idempotent `tasks/send` (P1-6).
    message_ids: Arc<RwLock<HashMap<String, String>>>,
    /// Optional skill -> chain router (P2-4).
    skill_router: Option<Arc<dyn SkillRouter>>,
    /// Optional SSE event bus (P2-1).
    event_bus: Option<Arc<broadcast::Sender<TaskPushNotification>>>,
    /// Expected bearer token for authenticated requests (None = auth disabled).
    expected_token: Option<String>,
    /// Optional rate limiter applied to every request.
    rate_limiter: Option<Arc<RateLimiter>>,
    /// Time-to-live for tasks before they expire.
    task_ttl: Option<Duration>,
}

impl A2AServer {
    /// Create a new A2A server backed by a `BaseChain`.
    pub fn new(chain: Arc<dyn BaseChain>) -> Self {
        let card = AgentCard::new(
            chain.name(),
            format!("Agent backed by {}", chain.name()),
            "http://localhost:8080",
        )
        .with_skill(AgentSkill::new(
            "default",
            chain.name(),
            format!("Agent backed by {}", chain.name()),
        ));
        Self {
            chain,
            card,
            store: Arc::new(InMemoryTaskStore::with_max_tasks(DEFAULT_MAX_TASKS)),
            message_ids: Arc::new(RwLock::new(HashMap::new())),
            skill_router: None,
            event_bus: None,
            expected_token: None,
            rate_limiter: None,
            task_ttl: Some(DEFAULT_TASK_TTL),
        }
    }

    /// Create a server backed directly by a stateful agent (P1-8).
    ///
    /// The [`AgentExecutor`] is adapted to the chain interface, so A2A tasks
    /// get genuine conversational continuity. Attach memory to the executor
    /// (`.with_memory(...)`) before wrapping for multi-turn state.
    pub fn from_agent(executor: Arc<AgentExecutor>) -> Self {
        Self::new(Arc::new(AgentExecutorChain::new(executor)))
    }

    /// Replace the default in-memory task store with a custom backend (P1-1).
    pub fn with_store(mut self, store: Arc<dyn TaskStore>) -> Self {
        self.store = store;
        self
    }

    /// Set the maximum number of tasks before LRU eviction.
    ///
    /// Replaces the store with a fresh in-memory store of the given capacity,
    /// discarding any tasks stored so far. Call this before sending tasks.
    pub fn with_max_tasks(mut self, max: usize) -> Self {
        self.store = Arc::new(InMemoryTaskStore::with_max_tasks(max.max(1)));
        self
    }

    /// Attach a skill router so `tasks/send` requests with a `skillId` are
    /// dispatched to a different chain (P2-4).
    pub fn with_skill_router(mut self, router: Arc<dyn SkillRouter>) -> Self {
        self.skill_router = Some(router);
        self
    }

    /// Attach a default skill router built from a static `skill_id -> chain`
    /// map (P2-4).
    pub fn with_skill_map(mut self, map: SkillMapRouter) -> Self {
        self.skill_router = Some(Arc::new(map));
        self
    }

    /// Enable streaming push notifications over an SSE-compatible channel
    /// (P2-1).
    ///
    /// Creates a `broadcast` channel with the given capacity and advertises
    /// `{"sse": true}` on the agent card. Subscribe with
    /// [`A2AServer::subscribe`].
    pub fn with_streaming(mut self, capacity: usize) -> Self {
        let (tx, _rx) = broadcast::channel(capacity.max(1));
        self.event_bus = Some(Arc::new(tx));
        self.card = self.card.clone().with_interfaces(json!({ "sse": true }));
        self
    }

    /// Subscribe to task push notifications, if streaming is enabled (P2-1).
    ///
    /// Returns `None` when the server was not built with
    /// [`A2AServer::with_streaming`].
    pub fn subscribe(&self) -> Option<broadcast::Receiver<TaskPushNotification>> {
        self.event_bus.as_ref().map(|tx| tx.subscribe())
    }

    /// Require a bearer token on every request.
    ///
    /// Enables authentication on the server and advertises `bearer` as a
    /// supported scheme on the agent card. Requests without a matching
    /// `Authorization: Bearer <token>` header are rejected with a 401.
    pub fn with_auth_token(mut self, token: impl Into<String>) -> Self {
        self.expected_token = Some(token.into());
        self.card = self
            .card
            .clone()
            .with_authentication(vec!["bearer".to_string()]);
        self
    }

    /// Attach a rate limiter applied to every incoming request.
    pub fn with_rate_limiter(mut self, limiter: Arc<RateLimiter>) -> Self {
        self.rate_limiter = Some(limiter);
        self
    }

    /// Set the task time-to-live before expiry cleanup (`None` disables expiry).
    pub fn with_task_ttl(mut self, ttl: Option<Duration>) -> Self {
        self.task_ttl = ttl;
        self
    }

    /// Spawn a background sweeper that periodically scans for expired tasks
    /// (P1-2), in addition to the lazy cleanup on the read paths.
    ///
    /// The loop calls [`sweep_expired_tasks`] every `interval` (clamped to at
    /// least 1s). It runs until the current Tokio runtime shuts down. If the
    /// server has no TTL configured (`with_task_ttl(None)`), no task is
    /// spawned — there is nothing to expire.
    pub fn with_background_cleanup(self, interval: Duration) -> Self {
        let Some(ttl) = self.task_ttl else {
            return self;
        };
        let store = self.store.clone();
        // Clamp away a zero interval (which `tokio::time::interval` rejects);
        // sub-second intervals are allowed so tests can drive the sweeper fast.
        let interval = interval.max(Duration::from_millis(1));
        tokio::spawn(async move {
            let mut ticker = tokio::time::interval(interval);
            // The first tick completes immediately; consume it so the first
            // sweep happens after one full interval.
            ticker.tick().await;
            loop {
                ticker.tick().await;
                sweep_expired_tasks(&store, ttl).await;
            }
        });
        self
    }

    /// Set a custom agent card.
    pub fn with_card(mut self, card: AgentCard) -> Self {
        self.card = card;
        self
    }

    /// Get the agent card (for `GET /.well-known/agent-card.json`).
    pub fn get_agent_card(&self) -> &AgentCard {
        &self.card
    }

    /// Handle an incoming A2A request (for `POST /`).
    ///
    /// Applies the optional rate limiter, then dispatches based on the
    /// request method:
    /// - `tasks/send` -> acknowledge a new async task (or continue one)
    /// - `tasks/get` -> return a stored task
    /// - `tasks/cancel` -> cancel a stored task
    /// - `tasks/list` -> list stored tasks
    /// - unknown method -> method_not_found error
    pub async fn handle_a2a_request(&self, req: A2ARequest) -> A2AResponse {
        if let Some(limiter) = &self.rate_limiter {
            if let Err(e) = limiter.try_acquire().await {
                return A2AResponse::error(req.id, 429, e.to_string());
            }
        }
        self.dispatch(req).await
    }

    /// Handle an incoming request with an optional bearer token.
    ///
    /// If the server was configured with [`A2AServer::with_auth_token`],
    /// requests without a matching bearer token are rejected with a 401.
    pub async fn handle_a2a_request_authenticated(
        &self,
        req: A2ARequest,
        bearer: Option<&str>,
    ) -> A2AResponse {
        if let Some(expected) = &self.expected_token {
            match bearer {
                None => return A2AResponse::error(req.id, 401, "Authentication required"),
                Some(token) if token != expected => {
                    return A2AResponse::error(req.id, 401, "Invalid authentication token");
                }
                Some(_) => {}
            }
        }
        self.handle_a2a_request(req).await
    }

    /// Dispatch a request to the matching handler.
    ///
    /// Requests carrying a W3C-style `trace_id` in metadata are logged so a
    /// distributed trace can be followed across agents (P1-5).
    async fn dispatch(&self, req: A2ARequest) -> A2AResponse {
        if let Some(trace_id) = req.trace_id() {
            log::debug!(
                "a2a request method={} id={} trace_id={}",
                req.method,
                req.id,
                trace_id
            );
        }
        match req.method.as_str() {
            "tasks/send" => self.handle_tasks_send(req).await,
            "tasks/get" => self.handle_tasks_get(req).await,
            "tasks/cancel" => self.handle_tasks_cancel(req).await,
            "tasks/list" => self.handle_tasks_list(req).await,
            "tasks/runWorkflow" => self.handle_workflow_run(req).await,
            _ => A2AResponse::from_error_data(req.id, A2AErrorData::method_not_found()),
        }
    }

    /// Handle `tasks/send`: create a new async task (or continue an existing
    /// one) and run the chain in the background.
    ///
    /// New tasks are acknowledged immediately with a `submitted` task and the
    /// chain runs in a spawned task. When the request carries a `taskId`
    /// (continuation, P2-2/P2-3), the message is appended to that task's
    /// history and it is re-run. A `message_id` makes the call idempotent
    /// (P1-6). A `skillId` param routes to a different chain (P2-4).
    async fn handle_tasks_send(&self, req: A2ARequest) -> A2AResponse {
        let params = match req.params.clone() {
            Some(p) => p,
            None => {
                return A2AResponse::from_error_data(
                    req.id,
                    A2AErrorData::invalid_params("Missing params for tasks/send"),
                )
            }
        };

        let message = extract_message(&params);

        // P1-6: idempotent re-send — a repeated message_id returns the
        // already-created task instead of running the chain a second time.
        let message_id = req.message_id().map(|s| s.to_string());
        if let Some(mid) = &message_id {
            if let Some(existing_id) = self.message_ids.read().await.get(mid).cloned() {
                if let Ok(Some(stored)) = self.store.get(&existing_id).await {
                    if !self.caller_owns(&req, &stored.task) {
                        return forbidden(req.id, "caller does not own the existing task");
                    }
                    return A2AResponse::ok(req.id, json!({ "task": stored.task }));
                }
                // The referenced task was evicted/expired: forget the mapping
                // and treat this as a fresh send.
                self.message_ids.write().await.remove(mid);
            }
        }

        // P2-2/P2-3: continuation — append to an existing task and re-run.
        if let Some(task_id) = req.task_id().map(|s| s.to_string()) {
            return self
                .handle_tasks_send_continue(req, task_id, message, message_id)
                .await;
        }

        // Fresh task.
        let task_id = uuid::Uuid::new_v4().to_string();
        let mut task = A2ATask::new(task_id.clone(), message);
        if let Some(owner) = req.owner() {
            task = task.with_owner(owner);
        }
        let mut stored = StoredTask::new(task.clone());
        // P1-5: carry the request's trace id onto the task so the trace can be
        // correlated after creation.
        if let Some(trace_id) = req.trace_id() {
            stored = stored.with_trace_id(trace_id);
        }
        if self.store.upsert(stored).await.is_err() {
            return A2AResponse::from_error_data(
                req.id,
                A2AErrorData::internal_error("task store write failed"),
            );
        }

        if let Some(mid) = &message_id {
            self.message_ids
                .write()
                .await
                .insert(mid.clone(), task_id.clone());
        }

        // P2-4: route by skill if a router is configured.
        let skill_id = params.get("skillId").and_then(Value::as_str);
        let chain = self.resolve_chain(skill_id);

        let store = self.store.clone();
        let bus = self.event_bus.clone();
        let history = task.message_history().into_owned();
        let spawned_id = task_id.clone();
        tokio::spawn(async move {
            run_task(&store, chain, &spawned_id, history, bus).await;
        });

        A2AResponse::ok(req.id, json!({ "task": task }))
    }

    /// Append a message to an existing task and re-run it (P2-2/P2-3).
    ///
    /// Only tasks in the `input-required` state can be resumed — this is the
    /// one A2A flow where the client sends another message to the same task
    /// (to supply the information the agent asked for). Continuing a
    /// `working` task would spawn a second background worker that races the
    /// first, and terminal tasks cannot change, so both are rejected with
    /// `-32004`.
    async fn handle_tasks_send_continue(
        &self,
        req: A2ARequest,
        task_id: String,
        message: A2AMessage,
        message_id: Option<String>,
    ) -> A2AResponse {
        let mut stored = match self.store.get(&task_id).await {
            Ok(Some(s)) => s,
            Ok(None) | Err(_) => return task_not_found(req.id, &task_id),
        };

        // P1-4: ownership.
        if !self.caller_owns(&req, &stored.task) {
            return forbidden(req.id, "caller does not own this task");
        }

        // P2-3: only an input-required task can be resumed with new input.
        if stored.task.status != TaskStatus::InputRequired {
            return A2AResponse::from_error_data(
                req.id,
                A2AErrorData::new(
                    -32004,
                    format!("Cannot continue task in state {}", stored.task.status),
                ),
            );
        }

        stored.task.push_message(message);
        if stored.task.status.can_transition_to(&TaskStatus::Working) {
            stored.task.status = TaskStatus::Working;
        }
        stored.touch();
        let task = stored.task.clone();
        if self.store.upsert(stored).await.is_err() {
            return A2AResponse::from_error_data(
                req.id,
                A2AErrorData::internal_error("task store write failed"),
            );
        }

        // P1-6: idempotency — a retried resume with the same message_id must
        // not append the message a second time.
        if let Some(mid) = message_id {
            self.message_ids.write().await.insert(mid, task_id.clone());
        }

        let store = self.store.clone();
        let chain = self.resolve_chain(None);
        let bus = self.event_bus.clone();
        let history = task.message_history().into_owned();
        let spawned_id = task_id.clone();
        tokio::spawn(async move {
            run_task(&store, chain, &spawned_id, history, bus).await;
        });

        A2AResponse::ok(req.id, json!({ "task": task }))
    }

    /// Handle `tasks/get`: return a task by ID.
    ///
    /// Ownership (P1-4): tasks carrying an `owner` are only readable by the
    /// matching caller.
    async fn handle_tasks_get(&self, req: A2ARequest) -> A2AResponse {
        let task_id = req
            .params
            .as_ref()
            .and_then(|p| p.get("taskId"))
            .and_then(|v| v.as_str())
            .unwrap_or("");

        if task_id.is_empty() {
            return A2AResponse::from_error_data(
                req.id,
                A2AErrorData::invalid_params("Missing taskId parameter"),
            );
        }

        self.cleanup_expired_tasks().await;

        match self.store.get(task_id).await {
            Ok(Some(stored)) => {
                if !self.caller_owns(&req, &stored.task) {
                    return forbidden(req.id, "caller does not own this task");
                }
                task_details_response(req.id, &stored)
            }
            Ok(None) => task_not_found(req.id, task_id),
            Err(_) => A2AResponse::from_error_data(
                req.id,
                A2AErrorData::internal_error("task store read failed"),
            ),
        }
    }

    /// Handle `tasks/cancel`: cancel a task by ID.
    ///
    /// Cancellation is only legal from a non-terminal state; cancelling an
    /// already-terminal task is an idempotent no-op that returns it unchanged.
    /// Ownership (P1-4) is enforced like `tasks/get`.
    async fn handle_tasks_cancel(&self, req: A2ARequest) -> A2AResponse {
        let task_id = req
            .params
            .as_ref()
            .and_then(|p| p.get("taskId"))
            .and_then(|v| v.as_str())
            .unwrap_or("");

        if task_id.is_empty() {
            return A2AResponse::from_error_data(
                req.id,
                A2AErrorData::invalid_params("Missing taskId parameter"),
            );
        }

        let mut stored = match self.store.get(task_id).await {
            Ok(Some(s)) => s,
            Ok(None) | Err(_) => return task_not_found(req.id, task_id),
        };

        if !self.caller_owns(&req, &stored.task) {
            return forbidden(req.id, "caller does not own this task");
        }

        if stored.task.status.is_terminal() {
            // Idempotent: already finished, return it unchanged.
            return A2AResponse::ok(req.id, json!({ "task": stored.task }));
        }
        if stored.task.status.can_transition_to(&TaskStatus::Cancelled) {
            stored.task.status = TaskStatus::Cancelled;
            stored.touch();
            if self.store.upsert(stored.clone()).await.is_err() {
                return A2AResponse::from_error_data(
                    req.id,
                    A2AErrorData::internal_error("task store write failed"),
                );
            }
            publish_status(&self.event_bus, task_id, TaskStatus::Cancelled, None);
            A2AResponse::ok(req.id, json!({ "task": stored.task }))
        } else {
            A2AResponse::from_error_data(
                req.id,
                A2AErrorData::new(
                    -32002,
                    format!("Cannot cancel task in state {}", stored.task.status),
                ),
            )
        }
    }

    /// Handle `tasks/list`: list stored tasks, optionally filtered by
    /// `owner` / `status` params (P1-1).
    ///
    /// A caller that carries an `owner` identity and does not pass an explicit
    /// `owner` param only sees its own tasks.
    async fn handle_tasks_list(&self, req: A2ARequest) -> A2AResponse {
        self.cleanup_expired_tasks().await;

        let mut filter = TaskFilter::new();
        if let Some(params) = &req.params {
            if let Some(owner) = params.get("owner").and_then(Value::as_str) {
                filter = filter.with_owner(owner);
            }
            if let Some(status) = params.get("status").and_then(Value::as_str) {
                if let Ok(ts) =
                    serde_json::from_value::<TaskStatus>(Value::String(status.to_string()))
                {
                    filter = filter.with_statuses(vec![ts]);
                }
            }
        }
        if filter.owner.is_none() {
            if let Some(owner) = req.owner() {
                filter = filter.with_owner(owner);
            }
        }

        match self.store.list(&filter).await {
            Ok(stored) => {
                let tasks: Vec<&A2ATask> = stored.iter().map(|s| &s.task).collect();
                A2AResponse::ok(req.id, json!({ "tasks": tasks }))
            }
            Err(_) => A2AResponse::from_error_data(
                req.id,
                A2AErrorData::internal_error("task store read failed"),
            ),
        }
    }

    /// Handle `tasks/runWorkflow`: execute an ordered multi-step workflow and
    /// aggregate per-step results (P2-8).
    ///
    /// A workflow is backed by a single task (id = `workflow.workflow_id` or a
    /// fresh UUID). Steps run in order, each routed to the chain selected by
    /// its `skill_id` (falling back to the default chain). A step failure
    /// marks the workflow task `failed` and stops execution — the results
    /// aggregated up to that point are still returned. Ownership (P1-4) and
    /// trace propagation (P1-5) apply to the backing task like `tasks/send`.
    async fn handle_workflow_run(&self, req: A2ARequest) -> A2AResponse {
        let params = match req.params.clone() {
            Some(p) => p,
            None => {
                return A2AResponse::from_error_data(
                    req.id,
                    A2AErrorData::invalid_params("Missing params for tasks/runWorkflow"),
                );
            }
        };
        let workflow: A2AWorkflow = match params.get("workflow") {
            Some(w) => match serde_json::from_value(w.clone()) {
                Ok(wf) => wf,
                Err(_) => {
                    return A2AResponse::from_error_data(
                        req.id,
                        A2AErrorData::invalid_params("Malformed workflow"),
                    );
                }
            },
            None => {
                return A2AResponse::from_error_data(
                    req.id,
                    A2AErrorData::invalid_params("Missing workflow for tasks/runWorkflow"),
                );
            }
        };
        if workflow.steps.is_empty() {
            return A2AResponse::from_error_data(
                req.id,
                A2AErrorData::invalid_params("Workflow has no steps"),
            );
        }

        // Create the backing task, propagating owner and trace id.
        let task_id = workflow
            .workflow_id
            .clone()
            .unwrap_or_else(|| uuid::Uuid::new_v4().to_string());
        let mut task = A2ATask::new(
            task_id.clone(),
            A2AMessage::user(format!(
                "workflow: {}",
                workflow.name.as_deref().unwrap_or("unnamed")
            )),
        )
        .with_status(TaskStatus::Working);
        if let Some(owner) = req.owner() {
            task = task.with_owner(owner);
        }
        let mut stored = StoredTask::new(task.clone());
        if let Some(trace_id) = req.trace_id() {
            stored = stored.with_trace_id(trace_id);
        }
        if self.store.upsert(stored).await.is_err() {
            return A2AResponse::from_error_data(
                req.id,
                A2AErrorData::internal_error("task store write failed"),
            );
        }
        publish_status(&self.event_bus, &task_id, TaskStatus::Working, None);

        // Execute steps in order, aggregating per-step outputs.
        let mut results = serde_json::Map::new();
        let mut failure: Option<(String, String)> = None; // (step_id, message)
        for step in &workflow.steps {
            let chain = self.resolve_chain(step.skill_id.as_deref());
            let input = build_chain_input(&step.message.content, chain.as_ref());
            match chain.invoke(input).await {
                Ok(result) => {
                    let output = extract_output(&result);
                    results.insert(step.id.clone(), Value::String(output));
                }
                Err(e) => {
                    failure = Some((step.id.clone(), e.to_string()));
                    break;
                }
            }
        }

        // Finalize the backing task with the aggregated outcome.
        let mut finalize = match self.store.get(&task_id).await {
            Ok(Some(s)) => s,
            _ => {
                return A2AResponse::from_error_data(
                    req.id,
                    A2AErrorData::internal_error("workflow task vanished"),
                );
            }
        };
        let aggregated = results
            .values()
            .filter_map(|v| v.as_str())
            .collect::<Vec<_>>()
            .join("\n");
        match failure {
            Some((step_id, message)) => {
                finalize.task.status = TaskStatus::Failed;
                finalize.error = Some(format!("step `{step_id}` failed: {message}"));
                let error = finalize.error.clone();
                let _ = self.store.upsert(finalize.clone()).await;
                publish_status(
                    &self.event_bus,
                    &task_id,
                    TaskStatus::Failed,
                    error.as_deref(),
                );
                A2AResponse::ok(
                    req.id,
                    json!({
                        "task": finalize.task,
                        "error": error,
                        "results": Value::Object(results),
                    }),
                )
            }
            None => {
                finalize.task.status = TaskStatus::Completed;
                finalize.result = Some(A2ATaskResult::new(aggregated));
                finalize.error = None;
                let _ = self.store.upsert(finalize.clone()).await;
                publish_status(&self.event_bus, &task_id, TaskStatus::Completed, None);
                publish_artifact(&self.event_bus, &task_id, finalize.result.clone().unwrap());
                A2AResponse::ok(
                    req.id,
                    json!({
                        "task": finalize.task,
                        "result": finalize.result,
                        "results": Value::Object(results),
                    }),
                )
            }
        }
    }

    /// Whether `req` may access a task with `owner`-based protection (P1-4).
    ///
    /// Tasks without an `owner` are open to any caller; tasks with an `owner`
    /// are only accessible to a caller whose metadata `owner` matches exactly.
    fn caller_owns(&self, req: &A2ARequest, task: &A2ATask) -> bool {
        match &task.owner {
            Some(task_owner) => req.owner() == Some(task_owner.as_str()),
            None => true,
        }
    }

    /// Resolve the chain for a skill id, falling back to the default chain
    /// (P2-4).
    fn resolve_chain(&self, skill_id: Option<&str>) -> Arc<dyn BaseChain> {
        if let Some(sid) = skill_id {
            if let Some(router) = &self.skill_router {
                if let Some(chain) = router.chain_for(sid) {
                    return chain;
                }
            }
        }
        self.chain.clone()
    }

    /// Lazily expire tasks older than the configured TTL.
    ///
    /// Terminal tasks older than the TTL are removed to bound memory; live
    /// tasks older than the TTL are transitioned to `expired`.
    async fn cleanup_expired_tasks(&self) {
        let Some(ttl) = self.task_ttl else {
            return;
        };
        sweep_expired_tasks(&self.store, ttl).await;
    }
}

/// Sweep tasks older than `ttl` (P1-2).
///
/// Terminal tasks are deleted to bound memory; live tasks that may transition
/// are marked `expired`. Shared by the lazy read-path cleanup and the
/// background [`A2AServer::with_background_cleanup`] sweeper.
async fn sweep_expired_tasks(store: &Arc<dyn TaskStore>, ttl: Duration) {
    let Ok(list) = store.list(&TaskFilter::new()).await else {
        return;
    };
    for stored in list {
        if stored.age() < ttl {
            continue;
        }
        if stored.task.status.is_terminal() {
            // Free memory for tasks that have been terminal for > ttl.
            let _ = store.delete(&stored.task.id).await;
        } else if stored.task.status.can_transition_to(&TaskStatus::Expired) {
            let mut expired = stored;
            expired.task.status = TaskStatus::Expired;
            expired.touch();
            let _ = store.upsert(expired).await;
        }
    }
}

/// Execute a task in the background: `submitted -> working ->
/// completed/failed/input-required`, guarded by the task state machine so it
/// never clobbers a terminal status (e.g. a task cancelled while the chain
/// was still running).
async fn run_task(
    store: &Arc<dyn TaskStore>,
    chain: Arc<dyn BaseChain>,
    task_id: &str,
    history: Vec<A2AMessage>,
    event_bus: Option<Arc<broadcast::Sender<TaskPushNotification>>>,
) {
    // submitted / input-required -> working
    if let Ok(Some(mut stored)) = store.get(task_id).await {
        if stored.task.status.can_transition_to(&TaskStatus::Working) {
            stored.task.status = TaskStatus::Working;
            stored.touch();
            let _ = store.upsert(stored).await;
            publish_status(&event_bus, task_id, TaskStatus::Working, None);
        }
    }

    let input = build_chain_input_from_history(&history, chain.as_ref());
    match chain.invoke(input).await {
        Ok(result) => {
            let output = extract_output(&result);
            if let Ok(Some(mut stored)) = store.get(task_id).await {
                if stored.task.status.can_transition_to(&TaskStatus::Completed) {
                    stored.task.status = TaskStatus::Completed;
                    stored.result = Some(A2ATaskResult::new(output.clone()));
                    stored.error = None;
                    stored.touch();
                    let _ = store.upsert(stored).await;
                    publish_status(&event_bus, task_id, TaskStatus::Completed, None);
                    publish_artifact(&event_bus, task_id, A2ATaskResult::new(output));
                }
            }
        }
        Err(e) => {
            if is_input_required(&e) {
                // P2-3: the chain is asking the client for more information.
                let prompt = e.to_string();
                if let Ok(Some(mut stored)) = store.get(task_id).await {
                    if stored
                        .task
                        .status
                        .can_transition_to(&TaskStatus::InputRequired)
                    {
                        stored.task.status = TaskStatus::InputRequired;
                        stored.error = Some(prompt.clone());
                        stored.touch();
                        let _ = store.upsert(stored).await;
                        publish_status(
                            &event_bus,
                            task_id,
                            TaskStatus::InputRequired,
                            Some(&prompt),
                        );
                    }
                }
            } else if let Ok(Some(mut stored)) = store.get(task_id).await {
                if stored.task.status.can_transition_to(&TaskStatus::Failed) {
                    stored.task.status = TaskStatus::Failed;
                    stored.error = Some(e.to_string());
                    stored.touch();
                    let _ = store.upsert(stored).await;
                    publish_status(
                        &event_bus,
                        task_id,
                        TaskStatus::Failed,
                        Some(&e.to_string()),
                    );
                }
            }
        }
    }
}

/// Whether a chain error signals that more input is needed (P2-3).
///
/// `MissingInput` (a required key is absent) and `InputError` (the input is
/// present but incomplete/malformed) are mapped to the `input-required` task
/// state so the client can resume the conversation.
fn is_input_required(e: &ChainError) -> bool {
    matches!(e, ChainError::MissingInput(_) | ChainError::InputError(_))
}

/// Extract the `A2AMessage` from `tasks/send` params.
///
/// Reads `params.message` (a message object); when absent, the whole params
/// become the input content.
fn extract_message(params: &Value) -> A2AMessage {
    match params.get("message") {
        Some(msg_val) => serde_json::from_value(msg_val.clone()).unwrap_or_else(|_| {
            A2AMessage::new(
                "user",
                msg_val
                    .get("content")
                    .and_then(|v| v.as_str())
                    .unwrap_or(""),
            )
        }),
        None => A2AMessage::user(params.to_string()),
    }
}

/// Build the chain input map from a full message history (P2-2).
///
/// A single-message history keeps its original content (backward compatible);
/// multi-turn histories are joined as `role: content` lines so the chain sees
/// the whole conversation.
fn build_chain_input_from_history(
    history: &[A2AMessage],
    chain: &dyn BaseChain,
) -> HashMap<String, Value> {
    let content = if history.len() == 1 {
        history[0].content.clone()
    } else {
        history
            .iter()
            .map(|m| format!("{}: {}", m.role, m.content))
            .collect::<Vec<_>>()
            .join("\n")
    };
    build_chain_input(&content, chain)
}

/// Build the chain input map from message content, using the chain's first
/// declared input key (or a fallback `"input"` key).
fn build_chain_input(content: &str, chain: &dyn BaseChain) -> HashMap<String, Value> {
    let mut map = HashMap::new();
    let input_keys = chain.input_keys();
    if let Some(first_key) = input_keys.first() {
        map.insert(first_key.to_string(), Value::String(content.to_string()));
    } else {
        map.insert("input".to_string(), Value::String(content.to_string()));
    }
    map
}

/// Extract the output text from a chain result (first value).
fn extract_output(result: &ChainResult) -> String {
    result
        .values()
        .next()
        .and_then(|v| v.as_str())
        .unwrap_or("")
        .to_string()
}

/// Build a `{task, result?, error?}` response for `tasks/get`.
fn task_details_response(id: u64, stored: &StoredTask) -> A2AResponse {
    let mut result = json!({ "task": stored.task });
    if let Some(ref task_result) = stored.result {
        result["result"] = json!(task_result);
    }
    if let Some(ref error) = stored.error {
        result["error"] = json!(error);
    }
    A2AResponse::ok(id, result)
}

/// `-32001` task-not-found error.
fn task_not_found(id: u64, task_id: &str) -> A2AResponse {
    A2AResponse::from_error_data(
        id,
        A2AErrorData::new(-32001, format!("Task not found: {}", task_id)),
    )
}

/// `-32003` ownership violation error.
fn forbidden(id: u64, message: impl Into<String>) -> A2AResponse {
    A2AResponse::from_error_data(id, A2AErrorData::new(-32003, message))
}

/// Publish a status-update event on the optional event bus (P2-1).
fn publish_status(
    bus: &Option<Arc<broadcast::Sender<TaskPushNotification>>>,
    task_id: &str,
    status: TaskStatus,
    error: Option<&str>,
) {
    if let Some(sender) = bus {
        let event = match error {
            Some(e) => TaskPushNotification::status_with_error(task_id, status, e),
            None => TaskPushNotification::status(task_id, status),
        };
        let _ = sender.send(event);
    }
}

/// Publish an artifact-update event on the optional event bus (P2-1).
fn publish_artifact(
    bus: &Option<Arc<broadcast::Sender<TaskPushNotification>>>,
    task_id: &str,
    artifact: A2ATaskResult,
) {
    if let Some(sender) = bus {
        let _ = sender.send(TaskPushNotification::artifact(task_id, artifact));
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use lc_agents::{AgentError, AgentFinish, AgentOutput, AgentStep, BaseAgent};
    use lc_chains::base::{BaseChain, ChainError, ChainResult};
    use tokio::sync::Notify;

    use crate::protocol::WorkflowStep;

    /// A simple mock chain that echoes the input.
    struct EchoChain;

    #[async_trait::async_trait]
    impl BaseChain for EchoChain {
        fn input_keys(&self) -> Vec<&str> {
            vec!["input"]
        }

        fn output_keys(&self) -> Vec<&str> {
            vec!["output"]
        }

        async fn invoke(&self, inputs: HashMap<String, Value>) -> Result<ChainResult, ChainError> {
            let input = inputs.get("input").and_then(|v| v.as_str()).unwrap_or("");
            let mut result = HashMap::new();
            result.insert("output".to_string(), Value::String(input.to_string()));
            Ok(result)
        }

        fn name(&self) -> &str {
            "echo-chain"
        }
    }

    /// A chain that always fails.
    struct FailChain;

    #[async_trait::async_trait]
    impl BaseChain for FailChain {
        fn input_keys(&self) -> Vec<&str> {
            vec!["input"]
        }

        fn output_keys(&self) -> Vec<&str> {
            vec!["output"]
        }

        async fn invoke(&self, _inputs: HashMap<String, Value>) -> Result<ChainResult, ChainError> {
            Err(ChainError::ExecutionError(
                "intentional failure".to_string(),
            ))
        }

        fn name(&self) -> &str {
            "fail-chain"
        }
    }

    /// A chain that signals when it starts and blocks until released.
    /// Lets tests observe the `working` state and cancel mid-flight.
    struct BlockingChain {
        started: Arc<Notify>,
        release: Arc<Notify>,
    }

    #[async_trait::async_trait]
    impl BaseChain for BlockingChain {
        fn input_keys(&self) -> Vec<&str> {
            vec!["input"]
        }

        fn output_keys(&self) -> Vec<&str> {
            vec!["output"]
        }

        async fn invoke(&self, _inputs: HashMap<String, Value>) -> Result<ChainResult, ChainError> {
            self.started.notify_one();
            self.release.notified().await;
            let mut result = HashMap::new();
            result.insert("output".to_string(), Value::String("done".to_string()));
            Ok(result)
        }

        fn name(&self) -> &str {
            "blocking-chain"
        }
    }

    /// A chain that asks for more input until it sees "alice" (P2-3).
    struct InputRequiredChain;

    #[async_trait::async_trait]
    impl BaseChain for InputRequiredChain {
        fn input_keys(&self) -> Vec<&str> {
            vec!["input"]
        }

        fn output_keys(&self) -> Vec<&str> {
            vec!["output"]
        }

        async fn invoke(&self, inputs: HashMap<String, Value>) -> Result<ChainResult, ChainError> {
            let input = inputs.get("input").and_then(|v| v.as_str()).unwrap_or("");
            if !input.contains("alice") {
                return Err(ChainError::MissingInput(
                    "please provide your name".to_string(),
                ));
            }
            let mut result = HashMap::new();
            result.insert("output".to_string(), Value::String(input.to_string()));
            Ok(result)
        }

        fn name(&self) -> &str {
            "input-required-chain"
        }
    }

    /// A chain whose output is a fixed label (for skill-routing observability).
    struct NamedChain(String);

    #[async_trait::async_trait]
    impl BaseChain for NamedChain {
        fn input_keys(&self) -> Vec<&str> {
            vec!["input"]
        }

        fn output_keys(&self) -> Vec<&str> {
            vec!["output"]
        }

        async fn invoke(&self, _inputs: HashMap<String, Value>) -> Result<ChainResult, ChainError> {
            let mut out = HashMap::new();
            out.insert("output".to_string(), Value::String(self.0.clone()));
            Ok(out)
        }

        fn name(&self) -> &str {
            &self.0
        }
    }

    fn echo_server() -> A2AServer {
        A2AServer::new(Arc::new(EchoChain))
    }

    fn fail_server() -> A2AServer {
        A2AServer::new(Arc::new(FailChain))
    }

    /// A planner that echoes the input back — drives an `AgentExecutor` for the
    /// `from_agent` end-to-end path.
    struct EchoAgent;

    #[async_trait::async_trait]
    impl BaseAgent for EchoAgent {
        async fn plan(
            &self,
            _intermediate_steps: &[AgentStep],
            inputs: &HashMap<String, String>,
        ) -> Result<AgentOutput, AgentError> {
            let input = inputs.get("input").cloned().unwrap_or_default();
            Ok(AgentOutput::Finish(AgentFinish::new(
                format!("agent-said: {}", input),
                String::new(),
            )))
        }
    }

    /// Poll `tasks/get` until the task reaches `want`, then return the response.
    async fn wait_for_status(server: &A2AServer, task_id: &str, want: &str) -> A2AResponse {
        for _ in 0..200 {
            let resp = server
                .handle_a2a_request(A2ARequest::get_task(99, task_id))
                .await;
            if let Some(r) = &resp.result {
                if r.get("task")
                    .and_then(|t| t.get("status"))
                    .and_then(|s| s.as_str())
                    == Some(want)
                {
                    return resp;
                }
            }
            tokio::time::sleep(std::time::Duration::from_millis(10)).await;
        }
        panic!("task {task_id} did not reach status {want} in time");
    }

    /// Send a task and return the created task id.
    async fn send_task_id(server: &A2AServer, content: &str) -> String {
        let resp = server
            .handle_a2a_request(A2ARequest::send_task(1, &A2AMessage::user(content)))
            .await;
        assert!(!resp.is_error());
        resp.result.unwrap()["task"]["id"]
            .as_str()
            .unwrap()
            .to_string()
    }

    #[test]
    fn get_agent_card_default() {
        let server = echo_server();
        let card = server.get_agent_card();
        assert_eq!(card.name, "echo-chain");
        assert!(card.description.contains("echo-chain"));
        assert_eq!(card.protocol_version, "0.3.0");
        assert_eq!(card.skills.len(), 1);
        assert_eq!(card.skills[0].id, "default");
        assert_eq!(card.skills[0].name, "echo-chain");
    }

    #[test]
    fn get_agent_card_custom() {
        let card = AgentCard::new("custom", "Custom agent", "http://example.com")
            .with_skill(AgentSkill::new("s1", "text-generation", "Generates text"));
        let server = echo_server().with_card(card);
        let card = server.get_agent_card();
        assert_eq!(card.name, "custom");
        assert_eq!(card.url, "http://example.com");
        assert_eq!(card.skills.len(), 1);
        assert_eq!(card.skills[0].id, "s1");
    }

    #[tokio::test]
    async fn handle_tasks_send_returns_submitted_immediately() {
        let server = echo_server();
        let msg = A2AMessage::user("hello world");
        let req = A2ARequest::send_task(1, &msg);
        let resp = server.handle_a2a_request(req).await;
        assert!(!resp.is_error());

        // The request acknowledges immediately with a `submitted` task.
        let result = resp.result.unwrap();
        let task = result.get("task").unwrap();
        assert_eq!(task["status"], "submitted");
        // No result yet.
        assert!(result.get("result").is_none());
    }

    #[tokio::test]
    async fn from_agent_serves_tasks_end_to_end() {
        // P1-8: an A2AServer backed by an AgentExecutor (adapted to BaseChain).
        let executor = Arc::new(AgentExecutor::new(Arc::new(EchoAgent), Vec::new()));
        let server = A2AServer::from_agent(executor);

        let task_id = send_task_id(&server, "hi").await;
        let done = wait_for_status(&server, &task_id, "completed").await;
        let output = done.result.unwrap()["result"]["output"]
            .as_str()
            .unwrap()
            .to_string();
        // The agent (not a plain chain) actually ran and produced its answer.
        assert_eq!(output, "agent-said: hi");
    }

    #[tokio::test]
    async fn handle_tasks_get_shows_working_then_completed() {
        let server = echo_server();
        let msg = A2AMessage::user("hello");
        let send_resp = server
            .handle_a2a_request(A2ARequest::send_task(1, &msg))
            .await;
        let task_id = send_resp.result.unwrap()["task"]["id"]
            .as_str()
            .unwrap()
            .to_string();

        let done = wait_for_status(&server, &task_id, "completed").await;
        let result = done.result.unwrap();
        let task = result.get("task").unwrap();
        assert_eq!(task["id"], task_id);
        assert_eq!(task["status"], "completed");
        let task_result = result.get("result").unwrap();
        assert_eq!(task_result["output"], "hello");
    }

    #[tokio::test]
    async fn handle_tasks_send_failure() {
        let server = fail_server();
        let send_resp = server
            .handle_a2a_request(A2ARequest::send_task(2, &A2AMessage::user("hello")))
            .await;
        // Submission itself succeeds; the failure is recorded on the task.
        assert!(!send_resp.is_error());

        let task_id = send_resp.result.unwrap()["task"]["id"]
            .as_str()
            .unwrap()
            .to_string();
        let done = wait_for_status(&server, &task_id, "failed").await;
        let result = done.result.unwrap();
        assert_eq!(result["task"]["status"], "failed");
        let error = result.get("error").unwrap();
        assert!(error.as_str().unwrap().contains("intentional failure"));
    }

    #[tokio::test]
    async fn handle_tasks_send_missing_params() {
        let server = echo_server();
        let req = A2ARequest::new(3, "tasks/send", None);
        let resp = server.handle_a2a_request(req).await;
        assert!(resp.is_error());
        let err = resp.error.unwrap();
        assert_eq!(err.code, -32602);
    }

    #[tokio::test]
    async fn handle_tasks_get_not_found() {
        let server = echo_server();
        let req = A2ARequest::get_task(5, "nonexistent-task");
        let resp = server.handle_a2a_request(req).await;
        assert!(resp.is_error());
        let err = resp.error.unwrap();
        assert!(err.message.contains("Task not found"));
    }

    #[tokio::test]
    async fn handle_tasks_cancel_nonexistent() {
        let server = echo_server();
        let req = A2ARequest::cancel_task(6, "task-123");
        let resp = server.handle_a2a_request(req).await;
        assert!(resp.is_error());
        let err = resp.error.unwrap();
        assert!(err.message.contains("Task not found"));
    }

    #[tokio::test]
    async fn handle_tasks_cancel_working_task() {
        let started = Arc::new(Notify::new());
        let release = Arc::new(Notify::new());
        let chain = Arc::new(BlockingChain {
            started: started.clone(),
            release: release.clone(),
        });
        let server = A2AServer::new(chain);

        let send_resp = server
            .handle_a2a_request(A2ARequest::send_task(1, &A2AMessage::user("hi")))
            .await;
        let task_id = send_resp.result.unwrap()["task"]["id"]
            .as_str()
            .unwrap()
            .to_string();

        // Wait for the background chain to start -> task is `working`.
        started.notified().await;
        let get_resp = server
            .handle_a2a_request(A2ARequest::get_task(2, &task_id))
            .await;
        assert_eq!(get_resp.result.unwrap()["task"]["status"], "working");

        // Cancel it mid-flight.
        let cancel_resp = server
            .handle_a2a_request(A2ARequest::cancel_task(3, &task_id))
            .await;
        assert!(!cancel_resp.is_error());
        assert_eq!(cancel_resp.result.unwrap()["task"]["status"], "cancelled");

        // Release the chain; the background worker must NOT clobber the
        // cancelled status back to completed.
        release.notify_one();
        tokio::time::sleep(std::time::Duration::from_millis(20)).await;
        let get_resp = server
            .handle_a2a_request(A2ARequest::get_task(4, &task_id))
            .await;
        assert_eq!(get_resp.result.unwrap()["task"]["status"], "cancelled");
    }

    #[tokio::test]
    async fn handle_tasks_cancel_completed_is_idempotent() {
        let server = echo_server();
        let send_resp = server
            .handle_a2a_request(A2ARequest::send_task(1, &A2AMessage::user("hi")))
            .await;
        let task_id = send_resp.result.unwrap()["task"]["id"]
            .as_str()
            .unwrap()
            .to_string();

        wait_for_status(&server, &task_id, "completed").await;

        let cancel_resp = server
            .handle_a2a_request(A2ARequest::cancel_task(2, &task_id))
            .await;
        assert!(!cancel_resp.is_error());
        // Already terminal: returned unchanged.
        assert_eq!(cancel_resp.result.unwrap()["task"]["status"], "completed");
    }

    #[tokio::test]
    async fn handle_tasks_cancel_missing_task_id() {
        let server = echo_server();
        let req = A2ARequest::new(7, "tasks/cancel", Some(json!({})));
        let resp = server.handle_a2a_request(req).await;
        assert!(resp.is_error());
    }

    #[tokio::test]
    async fn handle_tasks_list_returns_tasks() {
        let server = echo_server();
        let send_resp = server
            .handle_a2a_request(A2ARequest::send_task(1, &A2AMessage::user("hi")))
            .await;
        let task_id = send_resp.result.unwrap()["task"]["id"]
            .as_str()
            .unwrap()
            .to_string();

        let resp = server
            .handle_a2a_request(A2ARequest::new(2, "tasks/list", None))
            .await;
        assert!(!resp.is_error());
        let result = resp.result.unwrap();
        let tasks = result["tasks"].as_array().unwrap();
        assert!(
            tasks
                .iter()
                .any(|t| t["id"].as_str() == Some(task_id.as_str())),
            "expected task {task_id} in list"
        );
    }

    #[tokio::test]
    async fn handle_unknown_method() {
        let server = echo_server();
        let req = A2ARequest::new(8, "foo/bar", None);
        let resp = server.handle_a2a_request(req).await;
        assert!(resp.is_error());
        let err = resp.error.unwrap();
        assert_eq!(err.code, -32601);
    }

    #[tokio::test]
    async fn handle_tasks_send_with_raw_params() {
        // When params has no "message" key, the entire params become the content.
        let server = echo_server();
        let req = A2ARequest::new(9, "tasks/send", Some(json!({"query": "test query"})));
        let resp = server.handle_a2a_request(req).await;
        assert!(!resp.is_error());
    }

    #[tokio::test]
    async fn handle_tasks_send_chain_with_no_input_keys() {
        /// A chain with no input keys.
        struct NoKeyChain;

        #[async_trait::async_trait]
        impl BaseChain for NoKeyChain {
            fn input_keys(&self) -> Vec<&str> {
                vec![]
            }

            fn output_keys(&self) -> Vec<&str> {
                vec!["output"]
            }

            async fn invoke(
                &self,
                inputs: HashMap<String, Value>,
            ) -> Result<ChainResult, ChainError> {
                let input = inputs
                    .get("input")
                    .and_then(|v| v.as_str())
                    .unwrap_or("default");
                let mut result = HashMap::new();
                result.insert("output".to_string(), Value::String(input.to_string()));
                Ok(result)
            }

            fn name(&self) -> &str {
                "no-key-chain"
            }
        }

        let server = A2AServer::new(Arc::new(NoKeyChain));
        let msg = A2AMessage::user("hello");
        let req = A2ARequest::send_task(10, &msg);
        let resp = server.handle_a2a_request(req).await;
        assert!(!resp.is_error());
    }

    #[tokio::test]
    async fn handle_a2a_request_authenticated_requires_token() {
        let server = echo_server().with_auth_token("secret");
        assert_eq!(
            server.get_agent_card().authentication,
            Some(vec!["bearer".to_string()])
        );

        let msg = A2AMessage::user("hi");
        let resp = server
            .handle_a2a_request_authenticated(A2ARequest::send_task(1, &msg), None)
            .await;
        assert!(resp.is_error());
        assert_eq!(resp.error.unwrap().code, 401);
    }

    #[tokio::test]
    async fn handle_a2a_request_authenticated_invalid_token() {
        let server = echo_server().with_auth_token("secret");
        let msg = A2AMessage::user("hi");
        let resp = server
            .handle_a2a_request_authenticated(A2ARequest::send_task(1, &msg), Some("wrong"))
            .await;
        assert!(resp.is_error());
        assert_eq!(resp.error.unwrap().code, 401);
    }

    #[tokio::test]
    async fn handle_a2a_request_authenticated_valid_token() {
        let server = echo_server().with_auth_token("secret");
        let msg = A2AMessage::user("hi");
        let resp = server
            .handle_a2a_request_authenticated(A2ARequest::send_task(1, &msg), Some("secret"))
            .await;
        assert!(!resp.is_error());
    }

    #[tokio::test]
    async fn handle_a2a_request_unauthenticated_passes() {
        // Without an auth token configured, requests pass straight through.
        let server = echo_server();
        let msg = A2AMessage::user("hi");
        let resp = server
            .handle_a2a_request_authenticated(A2ARequest::send_task(1, &msg), None)
            .await;
        assert!(!resp.is_error());
    }

    #[tokio::test]
    async fn handle_a2a_request_rate_limited() {
        let server = echo_server().with_rate_limiter(Arc::new(RateLimiter::new(0, 1)));
        let msg = A2AMessage::user("hi");
        let r1 = server
            .handle_a2a_request(A2ARequest::send_task(1, &msg))
            .await;
        assert!(!r1.is_error());

        let r2 = server
            .handle_a2a_request(A2ARequest::send_task(2, &msg))
            .await;
        assert!(r2.is_error());
        assert_eq!(r2.error.unwrap().code, 429);
    }

    // ---- P1-6: idempotent tasks/send ----

    #[tokio::test]
    async fn handle_tasks_send_idempotent_message_id() {
        let server = echo_server();
        let msg = A2AMessage::user("hello");
        let req = A2ARequest::send_task_with_message_id(1, &msg, "idem-1");
        let r1 = server.handle_a2a_request(req.clone()).await;
        assert!(!r1.is_error());
        let task1 = r1.result.unwrap()["task"]["id"]
            .as_str()
            .unwrap()
            .to_string();

        let r2 = server.handle_a2a_request(req).await;
        assert!(!r2.is_error());
        let task2 = r2.result.unwrap()["task"]["id"]
            .as_str()
            .unwrap()
            .to_string();

        // Same message_id -> same task returned, not a second run.
        assert_eq!(task1, task2);
    }

    // ---- P1-4: ownership ----

    #[tokio::test]
    async fn handle_tasks_get_owner_enforced() {
        let server = echo_server();
        let send_resp = server
            .handle_a2a_request(
                A2ARequest::send_task(1, &A2AMessage::user("hi")).with_owner("alice"),
            )
            .await;
        let task_id = send_resp.result.unwrap()["task"]["id"]
            .as_str()
            .unwrap()
            .to_string();

        // Same owner -> allowed.
        let ok = server
            .handle_a2a_request(A2ARequest::get_task(2, &task_id).with_owner("alice"))
            .await;
        assert!(!ok.is_error());

        // Different owner -> 403.
        let denied = server
            .handle_a2a_request(A2ARequest::get_task(3, &task_id).with_owner("bob"))
            .await;
        assert!(denied.is_error());
        assert_eq!(denied.error.unwrap().code, -32003);

        // No owner identity -> 403 (task is protected).
        let anon = server
            .handle_a2a_request(A2ARequest::get_task(4, &task_id))
            .await;
        assert!(anon.is_error());
        assert_eq!(anon.error.unwrap().code, -32003);
    }

    #[tokio::test]
    async fn handle_tasks_cancel_owner_enforced() {
        let server = echo_server();
        let send_resp = server
            .handle_a2a_request(
                A2ARequest::send_task(1, &A2AMessage::user("hi")).with_owner("alice"),
            )
            .await;
        let task_id = send_resp.result.unwrap()["task"]["id"]
            .as_str()
            .unwrap()
            .to_string();

        let denied = server
            .handle_a2a_request(A2ARequest::cancel_task(2, &task_id).with_owner("bob"))
            .await;
        assert!(denied.is_error());
        assert_eq!(denied.error.unwrap().code, -32003);

        let ok = server
            .handle_a2a_request(A2ARequest::cancel_task(3, &task_id).with_owner("alice"))
            .await;
        assert!(!ok.is_error());
        assert_eq!(ok.result.unwrap()["task"]["status"], "cancelled");
    }

    #[tokio::test]
    async fn handle_tasks_list_filters_by_owner() {
        let server = echo_server();
        let _a = server
            .handle_a2a_request(
                A2ARequest::send_task(1, &A2AMessage::user("hi")).with_owner("alice"),
            )
            .await;
        let _b = server
            .handle_a2a_request(A2ARequest::send_task(2, &A2AMessage::user("hi")).with_owner("bob"))
            .await;

        // Alice's identity lists only her tasks by default.
        let resp = server
            .handle_a2a_request(A2ARequest::new(3, "tasks/list", None).with_owner("alice"))
            .await;
        let tasks = resp.result.unwrap()["tasks"].as_array().unwrap().clone();
        assert_eq!(tasks.len(), 1);
        assert_eq!(tasks[0]["owner"], "alice");

        // Anonymous listing sees everything (no owner filter requested).
        let resp = server
            .handle_a2a_request(A2ARequest::new(4, "tasks/list", None))
            .await;
        let tasks = resp.result.unwrap()["tasks"].as_array().unwrap().clone();
        assert_eq!(tasks.len(), 2);
    }

    // ---- P2-2/P2-3: multi-turn continuation ----

    #[tokio::test]
    async fn handle_tasks_send_continue_terminal_rejected() {
        let server = echo_server();
        let task_id = send_task_id(&server, "hello").await;
        wait_for_status(&server, &task_id, "completed").await;

        // Second continue after completion is rejected.
        let continue_resp = server
            .handle_a2a_request(A2ARequest::continue_task(
                2,
                &task_id,
                &A2AMessage::user("x"),
            ))
            .await;
        assert!(continue_resp.is_error());
        assert_eq!(continue_resp.error.unwrap().code, -32004);
    }

    // ---- P2-3: input-required flow ----

    #[tokio::test]
    async fn handle_tasks_send_input_required_then_resume() {
        let server = A2AServer::new(Arc::new(InputRequiredChain));
        let task_id = send_task_id(&server, "hello").await;

        // The chain asks for more input -> task goes input-required.
        let pending = wait_for_status(&server, &task_id, "input-required").await;
        let error = pending.result.unwrap()["error"]
            .as_str()
            .unwrap()
            .to_string();
        assert!(error.contains("please provide your name"));

        // Resume with the missing information via taskId.
        let resume_resp = server
            .handle_a2a_request(A2ARequest::continue_task(
                2,
                &task_id,
                &A2AMessage::user("my name is alice"),
            ))
            .await;
        assert!(!resume_resp.is_error());

        let done = wait_for_status(&server, &task_id, "completed").await;
        let output = done.result.unwrap()["result"]["output"]
            .as_str()
            .unwrap()
            .to_string();
        // The resumed run sees the full conversation: original turn + answer.
        assert!(
            output.contains("hello"),
            "resumed output missing first turn: {output}"
        );
        assert!(
            output.contains("alice"),
            "resumed output missing answer: {output}"
        );
    }

    #[tokio::test]
    async fn handle_tasks_send_continue_working_rejected() {
        // Only input-required tasks can be resumed. Continuing a task that is
        // still `working` would spawn a second worker racing the first.
        let started = Arc::new(Notify::new());
        let release = Arc::new(Notify::new());
        let chain = Arc::new(BlockingChain {
            started: started.clone(),
            release: release.clone(),
        });
        let server = A2AServer::new(chain);

        let send_resp = server
            .handle_a2a_request(A2ARequest::send_task(1, &A2AMessage::user("hi")))
            .await;
        let task_id = send_resp.result.unwrap()["task"]["id"]
            .as_str()
            .unwrap()
            .to_string();

        // Wait until the chain is running -> the task is `working`.
        started.notified().await;

        let continue_resp = server
            .handle_a2a_request(A2ARequest::continue_task(
                2,
                &task_id,
                &A2AMessage::user("more"),
            ))
            .await;
        assert!(continue_resp.is_error());
        assert_eq!(continue_resp.error.unwrap().code, -32004);

        // Let the first worker finish so it does not outlive the test.
        release.notify_one();
    }

    // ---- P1-1: custom store ----

    #[tokio::test]
    async fn with_store_custom_backend() {
        let store = InMemoryTaskStore::with_max_tasks(1);
        let server = echo_server().with_store(Arc::new(store));

        let first = send_task_id(&server, "one").await;
        let second = send_task_id(&server, "two").await;

        // Capacity 1: the first task was evicted, the second survives.
        let gone = server
            .handle_a2a_request(A2ARequest::get_task(2, &first))
            .await;
        assert!(gone.is_error());
        assert!(gone.error.unwrap().message.contains("Task not found"));

        let present = server
            .handle_a2a_request(A2ARequest::get_task(3, &second))
            .await;
        assert!(!present.is_error());
    }

    // ---- P2-4: skill routing ----

    #[tokio::test]
    async fn handle_tasks_send_routes_by_skill() {
        let router = SkillMapRouter::new()
            .with_skill("math", Arc::new(NamedChain("math-chain".to_string())));
        let server = echo_server().with_skill_map(router);

        // A request with skillId=math is handled by the routed chain.
        let params = json!({
            "message": { "role": "user", "content": "hi" },
            "skillId": "math"
        });
        let resp = server
            .handle_a2a_request(A2ARequest::new(1, "tasks/send", Some(params)))
            .await;
        let task_id = resp.result.unwrap()["task"]["id"]
            .as_str()
            .unwrap()
            .to_string();

        let done = wait_for_status(&server, &task_id, "completed").await;
        let output = done.result.unwrap()["result"]["output"]
            .as_str()
            .unwrap()
            .to_string();
        assert_eq!(output, "math-chain");

        // Without a skillId the default echo chain handles it.
        let task_id = send_task_id(&server, "hello").await;
        let done = wait_for_status(&server, &task_id, "completed").await;
        let output = done.result.unwrap()["result"]["output"]
            .as_str()
            .unwrap()
            .to_string();
        assert_eq!(output, "hello");
    }

    #[tokio::test]
    async fn handle_tasks_send_unknown_skill_falls_back() {
        let router = SkillMapRouter::new()
            .with_skill("math", Arc::new(NamedChain("math-chain".to_string())));
        let server = echo_server().with_skill_map(router);

        let params = json!({
            "message": { "role": "user", "content": "hi" },
            "skillId": "unknown"
        });
        let resp = server
            .handle_a2a_request(A2ARequest::new(1, "tasks/send", Some(params)))
            .await;
        let task_id = resp.result.unwrap()["task"]["id"]
            .as_str()
            .unwrap()
            .to_string();

        let done = wait_for_status(&server, &task_id, "completed").await;
        let output = done.result.unwrap()["result"]["output"]
            .as_str()
            .unwrap()
            .to_string();
        assert_eq!(output, "hi");
    }

    // ---- P2-1: streaming events ----

    #[tokio::test]
    async fn with_streaming_publishes_events_and_advertises_sse() {
        let server = echo_server().with_streaming(16);
        let card = server.get_agent_card();
        assert_eq!(
            card.interfaces,
            Some(json!({ "sse": true })),
            "streaming advertises sse interface"
        );

        let mut rx = server.subscribe().expect("subscribed");
        let task_id = send_task_id(&server, "hello").await;

        // Collect events until the terminal Completed status arrives.
        let mut saw_working = false;
        let mut saw_completed = false;
        let mut saw_artifact = false;
        for _ in 0..8 {
            match rx.recv().await {
                Ok(event) => {
                    assert_eq!(event.id(), task_id);
                    match event.status_value() {
                        Some(TaskStatus::Working) => saw_working = true,
                        Some(TaskStatus::Completed) => saw_completed = true,
                        // ArtifactUpdate carries no status.
                        None => saw_artifact = true,
                        _ => {}
                    }
                    if saw_completed && saw_artifact {
                        break;
                    }
                }
                Err(_) => break,
            }
        }
        assert!(saw_working, "expected a working event");
        assert!(saw_completed, "expected a completed event");
        assert!(saw_artifact, "expected an artifact event");
    }

    #[tokio::test]
    async fn without_streaming_no_subscriber() {
        let server = echo_server();
        assert!(server.subscribe().is_none());
    }

    #[tokio::test]
    async fn sweep_expired_tasks_cleans_terminal_and_expires_live() {
        let store: Arc<dyn TaskStore> = Arc::new(InMemoryTaskStore::with_max_tasks(10));

        // Terminal task past TTL -> deleted.
        let mut terminal = StoredTask::new(
            A2ATask::new("t-term", A2AMessage::user("done")).with_status(TaskStatus::Completed),
        );
        terminal.updated_at = std::time::Instant::now() - Duration::from_secs(100);

        // Live task past TTL -> marked expired.
        let mut live = StoredTask::new(
            A2ATask::new("t-live", A2AMessage::user("run")).with_status(TaskStatus::Working),
        );
        live.updated_at = std::time::Instant::now() - Duration::from_secs(100);

        // Fresh task -> untouched.
        let fresh = StoredTask::new(A2ATask::new("t-fresh", A2AMessage::user("new")));

        store.upsert(terminal).await.unwrap();
        store.upsert(live).await.unwrap();
        store.upsert(fresh).await.unwrap();

        sweep_expired_tasks(&store, Duration::from_secs(10)).await;

        assert!(
            store.get("t-term").await.unwrap().is_none(),
            "terminal task past TTL is deleted"
        );
        let live = store.get("t-live").await.unwrap().expect("live task kept");
        assert_eq!(live.task.status, TaskStatus::Expired);
        let fresh = store
            .get("t-fresh")
            .await
            .unwrap()
            .expect("fresh task kept");
        assert_eq!(fresh.task.status, TaskStatus::Submitted);
    }

    #[tokio::test]
    async fn background_cleanup_sweeps_periodically() {
        let store: Arc<dyn TaskStore> = Arc::new(InMemoryTaskStore::with_max_tasks(10));
        let mut expired = StoredTask::new(
            A2ATask::new("t-old", A2AMessage::user("hi")).with_status(TaskStatus::Working),
        );
        expired.updated_at = std::time::Instant::now() - Duration::from_secs(100);
        store.upsert(expired).await.unwrap();

        // The background sweeper ticks every 5ms and expires t-old without any
        // read-path trigger.
        let _server = A2AServer::new(Arc::new(EchoChain))
            .with_store(store.clone())
            .with_task_ttl(Some(Duration::from_secs(10)))
            .with_background_cleanup(Duration::from_millis(5));

        tokio::time::sleep(Duration::from_millis(50)).await;

        let t = store
            .get("t-old")
            .await
            .unwrap()
            .expect("live task still present");
        assert_eq!(t.task.status, TaskStatus::Expired);
    }

    #[tokio::test]
    async fn task_stores_request_trace_id() {
        let store: Arc<dyn TaskStore> = Arc::new(InMemoryTaskStore::with_max_tasks(10));
        let server = A2AServer::new(Arc::new(EchoChain)).with_store(store.clone());

        let req = A2ARequest::send_task(1, &A2AMessage::user("hello")).with_trace_id("trace-abc");
        let resp = server.handle_a2a_request(req).await;
        assert!(!resp.is_error());
        let task_id = resp.result.unwrap()["task"]["id"]
            .as_str()
            .unwrap()
            .to_string();

        let stored = store.get(&task_id).await.unwrap().expect("task stored");
        assert_eq!(stored.trace_id.as_deref(), Some("trace-abc"));
    }

    #[tokio::test]
    async fn task_without_trace_id_has_none() {
        let store: Arc<dyn TaskStore> = Arc::new(InMemoryTaskStore::with_max_tasks(10));
        let server = A2AServer::new(Arc::new(EchoChain)).with_store(store.clone());

        let resp = server
            .handle_a2a_request(A2ARequest::send_task(1, &A2AMessage::user("hi")))
            .await;
        assert!(!resp.is_error());
        let task_id = resp.result.unwrap()["task"]["id"]
            .as_str()
            .unwrap()
            .to_string();

        let stored = store.get(&task_id).await.unwrap().expect("task stored");
        assert!(stored.trace_id.is_none());
    }

    #[tokio::test]
    async fn run_workflow_executes_steps_in_order_and_aggregates() {
        let store: Arc<dyn TaskStore> = Arc::new(InMemoryTaskStore::with_max_tasks(10));
        let server = A2AServer::new(Arc::new(EchoChain)).with_store(store.clone());

        let workflow = A2AWorkflow::new(vec![
            WorkflowStep::new("s1", "first"),
            WorkflowStep::new("s2", "second"),
        ]);
        let resp = server
            .handle_a2a_request(A2ARequest::run_workflow(1, &workflow))
            .await;
        assert!(!resp.is_error());
        let result = resp.result.unwrap();
        assert_eq!(result["task"]["status"], "completed");
        assert_eq!(result["results"]["s1"], "first");
        assert_eq!(result["results"]["s2"], "second");

        // The backing task was persisted with the aggregated output.
        let task_id = result["task"]["id"].as_str().unwrap();
        let stored = store.get(task_id).await.unwrap().expect("task stored");
        assert_eq!(stored.task.status, TaskStatus::Completed);
        assert_eq!(stored.result.as_ref().unwrap().output, "first\nsecond");
    }

    #[tokio::test]
    async fn run_workflow_respects_supplied_workflow_id_and_owner() {
        let store: Arc<dyn TaskStore> = Arc::new(InMemoryTaskStore::with_max_tasks(10));
        let server = A2AServer::new(Arc::new(EchoChain)).with_store(store.clone());

        let workflow = A2AWorkflow::new(vec![WorkflowStep::new("s1", "hi")])
            .with_workflow_id("wf-42")
            .with_name("my workflow");
        let resp = server
            .handle_a2a_request(A2ARequest::run_workflow(1, &workflow).with_owner("alice"))
            .await;
        assert!(!resp.is_error());
        let result = resp.result.unwrap();
        assert_eq!(result["task"]["id"], "wf-42");

        let stored = store.get("wf-42").await.unwrap().expect("task stored");
        assert_eq!(stored.task.owner.as_deref(), Some("alice"));
    }

    #[tokio::test]
    async fn run_workflow_routes_steps_by_skill() {
        let store: Arc<dyn TaskStore> = Arc::new(InMemoryTaskStore::with_max_tasks(10));
        let server = A2AServer::new(Arc::new(EchoChain))
            .with_store(store.clone())
            .with_skill_map(
                SkillMapRouter::new()
                    .with_skill("translate", Arc::new(NamedChain("translated".to_string()))),
            );

        let workflow = A2AWorkflow::new(vec![
            WorkflowStep::new("s1", "hello"),
            WorkflowStep::with_skill("s2", "bonjour", "translate"),
        ]);
        let resp = server
            .handle_a2a_request(A2ARequest::run_workflow(1, &workflow))
            .await;
        assert!(!resp.is_error());
        let result = resp.result.unwrap();
        assert_eq!(result["results"]["s1"], "hello");
        assert_eq!(result["results"]["s2"], "translated");
    }

    #[tokio::test]
    async fn run_workflow_step_failure_marks_task_failed_and_stops() {
        let store: Arc<dyn TaskStore> = Arc::new(InMemoryTaskStore::with_max_tasks(10));
        let failing = A2AServer::new(Arc::new(EchoChain))
            .with_store(store.clone())
            .with_skill_map(SkillMapRouter::new().with_skill("failing", Arc::new(FailChain)));

        let workflow = A2AWorkflow::new(vec![
            WorkflowStep::new("s1", "ok"),
            WorkflowStep::with_skill("s2", "boom", "failing"),
        ]);
        let resp = failing
            .handle_a2a_request(A2ARequest::run_workflow(1, &workflow))
            .await;
        assert!(!resp.is_error()); // the task itself records the failure
        let result = resp.result.unwrap();
        assert_eq!(result["task"]["status"], "failed");
        assert!(result["results"].get("s1").is_some());
        assert!(result["results"].get("s2").is_none());
        assert!(result["error"]
            .as_str()
            .unwrap()
            .contains("step `s2` failed"));

        let stored = store
            .get(result["task"]["id"].as_str().unwrap())
            .await
            .unwrap()
            .unwrap();
        assert_eq!(stored.task.status, TaskStatus::Failed);
        assert!(stored.error.as_deref().unwrap().contains("s2"));
    }

    #[tokio::test]
    async fn run_workflow_missing_params_invalid() {
        let server = A2AServer::new(Arc::new(EchoChain));
        let resp = server
            .handle_a2a_request(A2ARequest::new(1, "tasks/runWorkflow", None))
            .await;
        assert!(resp.is_error());
    }

    #[tokio::test]
    async fn run_workflow_empty_steps_invalid() {
        let server = A2AServer::new(Arc::new(EchoChain));
        let resp = server
            .handle_a2a_request(A2ARequest::run_workflow(1, &A2AWorkflow::new(vec![])))
            .await;
        assert!(resp.is_error());
    }

    #[tokio::test]
    async fn run_workflow_carries_trace_id_onto_backing_task() {
        let store: Arc<dyn TaskStore> = Arc::new(InMemoryTaskStore::with_max_tasks(10));
        let server = A2AServer::new(Arc::new(EchoChain)).with_store(store.clone());

        let workflow = A2AWorkflow::new(vec![WorkflowStep::new("s1", "hi")]);
        let resp = server
            .handle_a2a_request(A2ARequest::run_workflow(1, &workflow).with_trace_id("trace-wf"))
            .await;
        assert!(!resp.is_error());
        let task_id = resp.result.unwrap()["task"]["id"]
            .as_str()
            .unwrap()
            .to_string();
        let stored = store.get(&task_id).await.unwrap().unwrap();
        assert_eq!(stored.trace_id.as_deref(), Some("trace-wf"));
    }
}