agentplane 0.34.0

Durable, replayable agent runtime — the journal is the plan of record
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
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
//! Serving A2A: this plane, as an agent other agents can call.
//!
//! The client side ([`crate::peers::a2a`]) lets this plane *call* peers. This is
//! the other half — a peer calling us — and it is a different problem, because
//! everything arriving here came from somebody else.
//!
//! # Why this is not a route on the operator API
//!
//! Every route on [`crate::api::Api`] authenticates and then authorizes. An
//! Agent Card is public by design: it is what a caller reads *before* it has
//! credentials, and a card behind authentication cannot be discovered. Bolting
//! an unauthenticated path onto a surface whose invariant is "every route
//! authenticates" would delete that invariant for the one route nobody would
//! think to check.
//!
//! So this is its own router with its own rule: **the card is public, every
//! method call is authenticated and authorized**.
//!
//! # What arrives here is untrusted
//!
//! A message from a peer is data written by a party this plane does not control,
//! so it is admitted as `Tainted` with the sending
//! peer's identity as its provenance source — never as trusted input. A skill
//! that wants to act on it has to say so at a gate, and a protected sink field
//! can name the one counterparty it will accept an amount from.
//!
//! This is the same reason the operator API takes an event's `source` from the
//! authenticated caller rather than the body: a party describing itself is not
//! evidence about itself.
//!
//! # The capability is named, never inferred
//!
//! A2A messages do not carry a "call this skill" field — the protocol assumes an
//! agent works out what is being asked. This plane will not: choosing which
//! capability to run on the strength of an untrusted message is a dispatch
//! decision made by inference, and the thing doing the inferring would be a
//! model reading attacker-controlled text.
//!
//! The skill is taken from `message.metadata.skill`, matched against the card's
//! advertised skill ids. When the agent advertises exactly one there is nothing
//! to infer and it is used; when it advertises several and none was named, the
//! call is refused rather than guessed.
//!
//! # Optional capabilities say what is wired
//!
//! Streaming and non-terminal task subscription are durable journal views.
//! Push is advertised only after `with_push` supplies durable registration
//! storage and a retrying transport worker; without that wiring every push
//! method uses `PushNotificationNotSupportedError` and the card advertises
//! false.

use std::sync::Arc;

use axum::extract::State;
use axum::http::{HeaderMap, StatusCode};
use axum::response::{IntoResponse, Response};
use axum::routing::{get, post};
use axum::{Json, Router};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};

use crate::core::{PolicyDecision, PolicyRequest, RunId, Seq, SourceId, Tainted};
use crate::journal::RecordKind;
use crate::manifest::Manifest;
use crate::peers::{AgentCard, ExtendedAgentCard, WELL_KNOWN_PATH};
use crate::runtime::Runtime;

use super::{Authenticator, Caller};

/// JSON-RPC method names, exactly as A2A 1.0 spells them.
///
/// 1.0 renamed these: `message/send` was the 0.3 spelling, and a server
/// answering the old names would silently accept clients that have lost half the
/// protocol. Constants rather than inline literals so the dispatch table and the
/// refusal table cannot disagree.
pub mod method {
    pub const SEND_MESSAGE: &str = "SendMessage";
    pub const GET_TASK: &str = "GetTask";
    pub const CANCEL_TASK: &str = "CancelTask";
    pub const GET_EXTENDED_CARD: &str = "GetExtendedAgentCard";

    /// Optional operations implemented by this server.
    pub const SEND_STREAMING: &str = "SendStreamingMessage";
    pub const SUBSCRIBE: &str = "SubscribeToTask";
    pub const LIST_TASKS: &str = "ListTasks";
    pub const CREATE_PUSH: &str = "CreateTaskPushNotificationConfig";
    pub const GET_PUSH: &str = "GetTaskPushNotificationConfig";
    pub const LIST_PUSH: &str = "ListTaskPushNotificationConfigs";
    pub const DELETE_PUSH: &str = "DeleteTaskPushNotificationConfig";
}

/// A2A-specific JSON-RPC error codes, from the spec's mapping table.
pub mod code {
    pub const PARSE_ERROR: i32 = -32700;
    pub const INVALID_REQUEST: i32 = -32600;
    pub const METHOD_NOT_FOUND: i32 = -32601;
    pub const INVALID_PARAMS: i32 = -32602;
    pub const INTERNAL_ERROR: i32 = -32603;

    pub const TASK_NOT_FOUND: i32 = -32001;
    pub const TASK_NOT_CANCELABLE: i32 = -32002;
    pub const PUSH_NOT_SUPPORTED: i32 = -32003;
    pub const UNSUPPORTED_OPERATION: i32 = -32004;
    pub const CONTENT_TYPE_NOT_SUPPORTED: i32 = -32005;
    pub const EXTENDED_CARD_NOT_CONFIGURED: i32 = -32007;
    pub const VERSION_NOT_SUPPORTED: i32 = -32009;

    /// Admission back-pressure: a quota ceiling refused the request before any
    /// work was admitted.
    ///
    /// Not in A2A 1.0's error table — the spec defines only permanent
    /// missing-capability codes and assigns back-pressure no code at all; its
    /// own guidance stops at "return appropriate error responses when rate
    /// limits are exceeded". Reaching into the table anyway would be worse
    /// than inventing a code: `-32004 UnsupportedOperationError` for a full
    /// quota teaches a compliant caller that the *operation does not exist
    /// here* — the correct response to which is to abandon, never to retry —
    /// when the truthful answer is "not right now". So the code is drawn from
    /// JSON-RPC's implementation-defined server-error range.
    ///
    /// The **number is not the identity**. A2A 1.0 reserves `-32001..-32099`
    /// for its own errors, the same band JSON-RPC gives implementations, so a
    /// future spec revision could assign this numeral a meaning of its own.
    /// What makes the refusal identifiable is the `google.rpc.ErrorInfo`
    /// beside it — [`ERROR_DOMAIN`](crate::peers::ERROR_DOMAIN) +
    /// [`QUOTA_EXHAUSTED_REASON`](crate::peers::QUOTA_EXHAUSTED_REASON), a
    /// domain this project controls — and that pair is what this crate's own
    /// client keys its refuse-and-come-back classification on. A bare
    /// `-32029` from a foreign server proves nothing and is classified as an
    /// unknown fault.
    ///
    /// What this code does NOT carry is the quota arithmetic: declines on this
    /// surface are deliberately uniform, and counters or limits in the message
    /// would hand an unauthenticated prober the tenant's ceilings. The message
    /// beside this code is a fixed sentence with no numbers in it.
    pub const QUOTA_EXHAUSTED: i32 = -32029;

    /// This agent is halted by its operator.
    ///
    /// Its own code, beside [`QUOTA_EXHAUSTED`] and
    /// under the same identification rule — the `(domain, reason)` pair, never
    /// the numeral — because the two ask opposite things of a caller. A ceiling
    /// says *come back*; a halt says *somebody is dealing with an incident*,
    /// and a peer told to back off and retry keeps knocking on the one door
    /// that means stop. The message is fixed and carries none of the
    /// operator's reason: the counterparty gets the outcome, not the plane's
    /// internals.
    pub const HALTED: i32 = -32030;

    /// This instance is shutting down and did not admit the request.
    ///
    /// The third admission refusal, under the same identification rule — the
    /// `(domain, reason)` pair, never the numeral. It is its own code because
    /// it is the only one of the three a caller clears by *moving*: a ceiling
    /// and a halt are facts about the agent, and this is a fact about one
    /// process serving it. A peer told to back off waits out a window it never
    /// needed; a peer told to abandon gives up on an agent that is fine.
    pub const DRAINING: i32 = -32031;
}

/// Actions this surface asks the policy engine about.
pub mod action {
    pub const MESSAGE_SEND: &str = "a2a:message.send";
    pub const TASK_READ: &str = "a2a:task.read";
    pub const TASK_CONTINUE: &str = "a2a:task.continue";
    pub const TASK_CANCEL: &str = "a2a:task.cancel";
    pub const CARD_EXTENDED: &str = "a2a:card.extended";
    /// Registering, reading or removing a webhook for a task.
    pub const TASK_PUSH: &str = "a2a:task.push";

    /// Every action this surface can ask about, so a deployment can enumerate
    /// what it must write rules for.
    pub const ALL: &[&str] = &[
        MESSAGE_SEND,
        TASK_READ,
        TASK_CONTINUE,
        TASK_CANCEL,
        CARD_EXTENDED,
        TASK_PUSH,
    ];
}

/// The `A2A-Version` service parameter.
const VERSION_HEADER: &str = "a2a-version";

/// The one sentence a full quota answers with, beside
/// [`code::QUOTA_EXHAUSTED`].
///
/// A single constant rather than `why.to_string()` at each site, because the
/// quota error's own rendering names the counter and its ceiling — numbers an
/// external caller has no business learning from a decline. Deliberately
/// digit-free; the test on this path asserts exactly that.
const QUOTA_EXHAUSTED_MESSAGE: &str =
    "this agent cannot take the request on right now; retry later";

/// The one sentence a halt answers with, beside [`code::HALTED`]. No reason,
/// no scope: an incident's description is for the operator's own worklist.
const HALTED_MESSAGE: &str =
    "this agent is halted by its operator; do not retry until it is lifted";

/// The one sentence a draining instance answers with, beside [`code::DRAINING`].
///
/// No hostname, no instance id and no grace period: which process is going away
/// is this deployment's topology, and a caller's correct behaviour does not
/// depend on knowing it.
const DRAINING_MESSAGE: &str =
    "this instance is shutting down and did not take the request on; retry";

/// Which of the two admission refusals a quota error is, on the wire.
///
/// One function for the three admission sites, because a halt that reached one
/// of them as a ceiling would be the sibling-divergence shape: a peer told
/// *retry* by `message/send` and *stop* by `message/stream`.
fn quota_refusal(e: &crate::quota::QuotaError) -> RpcError {
    match e {
        crate::quota::QuotaError::Halted { .. } => RpcError::new(code::HALTED, HALTED_MESSAGE),
        _ => RpcError::new(code::QUOTA_EXHAUSTED, QUOTA_EXHAUSTED_MESSAGE),
    }
}

/// A task's lifecycle state, as A2A names them.
///
/// `ProtoJSON` spelling — `TASK_STATE_WORKING`, not `working`. A client matching
/// on the enum gets nothing from a friendlier spelling.
///
/// # Why this is a subset
///
/// A2A also defines `SUBMITTED`, `REJECTED` and `AUTH_REQUIRED`, and this plane
/// never enters any of them. `SUBMITTED` means accepted but not yet started, and
/// there is no such moment here: a run starts inside the call that admits it.
/// The other two are refusals, and a refusal never becomes a task — a declined
/// request is answered with a `Message`, and an unauthenticated one never
/// reaches dispatch.
///
/// Declared and never produced would be worse than absent: a client writing a
/// branch for `SUBMITTED` would be writing dead code against a promise this
/// agent does not keep.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum TaskState {
    #[serde(rename = "TASK_STATE_UNSPECIFIED")]
    Unspecified,
    #[serde(rename = "TASK_STATE_SUBMITTED")]
    Submitted,
    #[serde(rename = "TASK_STATE_WORKING")]
    Working,
    #[serde(rename = "TASK_STATE_COMPLETED")]
    Completed,
    #[serde(rename = "TASK_STATE_FAILED")]
    Failed,
    #[serde(rename = "TASK_STATE_CANCELED")]
    Canceled,
    #[serde(rename = "TASK_STATE_INPUT_REQUIRED")]
    InputRequired,
    #[serde(rename = "TASK_STATE_REJECTED")]
    Rejected,
    #[serde(rename = "TASK_STATE_AUTH_REQUIRED")]
    AuthRequired,
}

/// The A2A state a live run's status surfaces as.
///
/// Two of these are worth stating because the obvious mapping is wrong.
///
/// A **suspended** run is `INPUT_REQUIRED`, not `WORKING`: it is stopped and
/// will not move until something external happens, and a caller polling a
/// `WORKING` task waits forever for a task that is not running.
///
/// A **quarantined** run is `FAILED`, not `REJECTED`. `REJECTED` means the agent
/// declined the work; quarantine means it accepted the work, started, and can no
/// longer be trusted to describe what it did. Reporting that as a refusal tells
/// the caller nothing happened, when something did.
///
/// This and [`sealed_state`] are the **same question asked on two paths**: this
/// one answers the caller who receives the immediate `SendMessage` response, and
/// `sealed_state` answers everyone who reads the task back — `GetTask`,
/// `SubscribeToTask`, and every streamed status update. They must agree, and
/// `a_live_status_and_its_sealed_outcome_agree` holds them to it over every
/// variant.
///
/// **This is the exhaustive one, and that is the point.** The two were unified
/// once by making this function delegate to `sealed_state`, which reads as the
/// tidier direction and is the wrong one: `sealed_state` matches *strings*
/// behind a `_ => Failed`, so delegating to it deleted the only compile-time
/// check on the mapping while leaving a comment claiming the compiler still
/// enforced it. Adding a `RunStatus` variant for something that is **not** a
/// failure — an authorization wait, a rejection — would then have compiled
/// cleanly and reported `Failed` on both paths. That is not agreement; it is
/// the same wrong answer twice, which is strictly harder to notice than two
/// different ones.
///
/// So the enum match is the definition and the string match is checked against
/// it. A new variant fails to compile *here*, which is where the decision
/// belongs.
fn state_of(status: &crate::runtime::RunStatus) -> TaskState {
    use crate::runtime::RunStatus;
    match status {
        RunStatus::Succeeded => TaskState::Completed,
        RunStatus::Suspended(_) => TaskState::InputRequired,
        RunStatus::Cancelled { .. } => TaskState::Canceled,
        RunStatus::Failed(_)
        | RunStatus::Exhausted(_)
        | RunStatus::Quarantined(_)
        // Not `Canceled`: A2A's cancellation means a client asked and the work
        // stopped, which a peer reads as "nothing of mine is standing". An
        // abandoned run is the opposite claim — something may well be standing
        // and nobody could establish what — so it takes the state a peer
        // investigates rather than the one they dismiss.
        | RunStatus::Abandoned { .. }
        | RunStatus::Replanning(_) => TaskState::Failed,
        // Neither is a task, and `REJECTED` is the state that says so: no peer
        // submitted a sweep or a break-glass crossing, and a run id that
        // resolves to one is a caller asking about this plane's record of
        // itself. `FAILED` would claim the agent tried and could not; `CANCELED`
        // would claim somebody's work was stopped. Both invent a task where
        // there was none, and a peer reads either as being about *their*
        // request. Nothing narrows further here on purpose — which of this
        // plane's internal runs exists is not a peer's question, so the answer
        // is the same one for a run that does not exist at all.
        RunStatus::Swept | RunStatus::BrokeGlass { .. } => TaskState::Rejected,
    }
}

/// A2A's `TaskStatus`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TaskStatus {
    pub state: TaskState,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub message: Option<A2aMessage>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub timestamp: Option<String>,
}

/// A2A's `Task` — what this plane calls a run.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct A2aTask {
    pub id: String,
    /// The case, when the run belongs to one.
    ///
    /// A2A's `contextId` is "the thing this conversation is part of", which is
    /// exactly a case: several runs, one matter, shared state. Mapping it to
    /// anything else would give a caller a correlation handle that does not
    /// correlate.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub context_id: Option<String>,
    pub status: TaskStatus,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub artifacts: Option<Vec<A2aArtifact>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub history: Option<Vec<A2aMessage>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Value>,
}

/// One output produced by an A2A task.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct A2aArtifact {
    pub artifact_id: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    pub parts: Vec<Part>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Value>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub extensions: Vec<String>,
}

/// One piece of a message.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Part {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data: Option<Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub raw: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub filename: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub media_type: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Value>,
}

impl Part {
    /// A text part.
    #[must_use]
    pub fn text(text: impl Into<String>) -> Self {
        Self {
            text: Some(text.into()),
            data: None,
            raw: None,
            url: None,
            filename: None,
            media_type: Some("text/plain".to_owned()),
            metadata: None,
        }
    }

    /// A structured-data part.
    #[must_use]
    pub fn data(data: Value) -> Self {
        Self {
            text: None,
            data: Some(data),
            raw: None,
            url: None,
            filename: None,
            media_type: Some("application/json".to_owned()),
            metadata: None,
        }
    }

    /// A file part carrying its bytes inline, base64-encoded per `ProtoJSON`.
    #[must_use]
    pub fn file_raw(
        raw_base64: impl Into<String>,
        media_type: impl Into<String>,
        filename: impl Into<String>,
    ) -> Self {
        Self {
            text: None,
            data: None,
            raw: Some(raw_base64.into()),
            url: None,
            filename: Some(filename.into()),
            media_type: Some(media_type.into()),
            metadata: None,
        }
    }

    /// A file part referring to bytes by URL.
    #[must_use]
    pub fn file_url(
        url: impl Into<String>,
        media_type: impl Into<String>,
        filename: impl Into<String>,
    ) -> Self {
        Self {
            text: None,
            data: None,
            raw: None,
            url: Some(url.into()),
            filename: Some(filename.into()),
            media_type: Some(media_type.into()),
            metadata: None,
        }
    }
}

/// How a skill shapes its A2A answer, when the default projection is not it.
///
/// The default stands for most skills: a string output becomes a text part and
/// anything else a data part, in one artifact. What that projection cannot say
/// is *file content* — inline bytes or a URL with a filename — or that the
/// answer is a quick, stateless `Message` rather than a task's artifact. Both
/// are ordinary A2A response shapes a peer may expect.
///
/// A skill opts in by returning this value (via [`A2aReply::into_value`]) as
/// its outcome. The runtime journals it as it journals any output — the shape
/// is a *projection instruction* read at the protocol boundary, not a second
/// channel around the journal.
///
/// ```no_run
/// # use agentplane::api::a2a::{A2aReply, Part};
/// # use agentplane::core::{Outcome, Tainted};
/// // A task whose artifact is a file reference:
/// let reply = A2aReply::artifact(vec![Part::file_url(
///     "https://example.com/report.pdf",
///     "application/pdf",
///     "report.pdf",
/// )]);
/// # let _ = Outcome::done(Tainted::trusted(reply.into_value()));
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct A2aReply {
    #[serde(skip_serializing_if = "Option::is_none")]
    message: Option<Vec<Part>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    artifacts: Option<Vec<Vec<Part>>>,
}

/// The output key an [`A2aReply`] travels under.
///
/// A `$`-prefixed marker, like `$a2a_message` on the inbound side: ordinary
/// skill output is domain data this runtime never interprets, so the one shape
/// it *does* interpret must be unmistakably deliberate rather than a field
/// name a domain object happens to share.
const REPLY_KEY: &str = "$a2a_reply";

impl A2aReply {
    /// Answer the blocking send with a direct `Message` instead of a task.
    ///
    /// Outside a blocking send — a spawned task, a stream, a later `GetTask` —
    /// there is no message to deliver, and the parts become the task's
    /// artifact instead: the content survives, only the envelope differs.
    #[must_use]
    pub const fn message(parts: Vec<Part>) -> Self {
        Self {
            message: Some(parts),
            artifacts: None,
        }
    }

    /// Answer with one artifact holding these parts.
    #[must_use]
    pub fn artifact(parts: Vec<Part>) -> Self {
        Self {
            message: None,
            artifacts: Some(vec![parts]),
        }
    }

    /// Answer with several artifacts.
    #[must_use]
    pub const fn artifacts(artifacts: Vec<Vec<Part>>) -> Self {
        Self {
            message: None,
            artifacts: Some(artifacts),
        }
    }

    /// The outcome value a skill returns.
    #[must_use]
    pub fn into_value(self) -> Value {
        json!({ REPLY_KEY: self })
    }

    /// Read a reply back out of a run's output, **if the run may declare one**.
    ///
    /// A projection instruction is authority: it decides whether the answer is
    /// a task artifact or a direct `Message`, and what parts it carries —
    /// including a file part naming a URL. Skill output routinely *contains*
    /// untrusted data: a summariser quotes its input, a declarative agent's
    /// answer is a model's words, and an echoing skill returns a peer's own
    /// bytes. So the marker is honoured only from a **trusted** output.
    ///
    /// This was not hypothetical. Before the check, a peer could put the
    /// marker in its message, have an ordinary echoing skill return it, and
    /// choose the envelope its own reply arrived in — a file URL of the
    /// attacker's naming, presented as the agent's answer. Model output is a
    /// proposal, never authority; so is a peer's message.
    ///
    /// An untrusted answer still reaches the caller — as the artifact content
    /// it is, rather than as an instruction about the envelope.
    pub(super) fn of_output(output: &crate::core::Tainted<Value>) -> Option<Self> {
        if output.label().is_untrusted() {
            return None;
        }
        serde_json::from_value(output.peek().get(REPLY_KEY)?.clone()).ok()
    }

    /// The message parts, when this reply is a direct `Message`.
    pub(super) fn message_parts(&self) -> Option<Vec<Part>> {
        self.message.clone()
    }

    /// Every part, for contexts that can only carry artifacts.
    pub(super) fn artifact_parts(&self) -> Vec<Vec<Part>> {
        match (&self.artifacts, &self.message) {
            (Some(artifacts), _) => artifacts.clone(),
            (None, Some(message)) => vec![message.clone()],
            (None, None) => Vec::new(),
        }
    }
}

/// A2A's `Message`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct A2aMessage {
    pub message_id: String,
    pub role: String,
    pub parts: Vec<Part>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub context_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub task_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Value>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub extensions: Vec<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub reference_task_ids: Vec<String>,
}

impl A2aMessage {
    fn validate_parts(&self) -> Result<(), RpcError> {
        if self.role != "ROLE_USER" {
            return Err(RpcError::new(
                code::INVALID_PARAMS,
                "an inbound Message role must be ROLE_USER",
            ));
        }
        // The id is half of the admission key — an empty one would fold every
        // caller's unnamed messages into a single "retry" of the first.
        if self.message_id.is_empty() {
            return Err(RpcError::new(
                code::INVALID_PARAMS,
                "messageId must be non-empty: it is what lets a retry of this \
                 message be recognised as the same message",
            ));
        }
        if self.parts.is_empty() {
            return Err(RpcError::new(
                code::CONTENT_TYPE_NOT_SUPPORTED,
                "the message has no parts this agent can read; it accepts text and data parts",
            ));
        }
        for (index, part) in self.parts.iter().enumerate() {
            // Only the file modalities are refused. A `mediaType` on a text or
            // data part is a *label* the spec allows on every part type — a
            // peer sending `text/markdown` text is conformant, and the card's
            // input modes are a tailoring hint, not a per-part contract the
            // server may bounce messages on.
            if part.raw.is_some() || part.url.is_some() {
                return Err(RpcError::new(
                    code::CONTENT_TYPE_NOT_SUPPORTED,
                    format!(
                        "message.parts[{index}] is file content; this agent card advertises only text/plain and application/json"
                    ),
                ));
            }
            let variants = usize::from(part.text.is_some()) + usize::from(part.data.is_some());
            if variants != 1 {
                return Err(RpcError::new(
                    code::INVALID_PARAMS,
                    format!("message.parts[{index}] must contain exactly one of text or data"),
                ));
            }
        }
        Ok(())
    }

    /// What the runtime receives as input.
    ///
    /// A stable shape, always the same three keys, rather than a clever unwrapping
    /// that hands a skill a bare string sometimes and an object other times. A
    /// skill parsing its own input should not have to branch on how many parts
    /// the caller happened to send. `$a2a_message` preserves the exact protocol
    /// object for task-history reconstruction; `text` and `data` remain the
    /// ergonomic projections skills normally consume.
    fn to_input(&self) -> Value {
        let text: Vec<&str> = self
            .parts
            .iter()
            .filter_map(|p| p.text.as_deref())
            .collect();
        let data: Vec<Value> = self.parts.iter().filter_map(|p| p.data.clone()).collect();
        json!({
            "text": text.join("\n"),
            "data": data,
            "$a2a_message": self,
        })
    }

    /// The skill this message asks for, if it named one.
    fn requested_skill(&self) -> Option<&str> {
        self.metadata.as_ref()?.get("skill")?.as_str()
    }
}

/// A JSON-RPC 2.0 request.
#[derive(Debug, Clone, Deserialize)]
struct RpcRequest {
    #[serde(default)]
    jsonrpc: String,
    #[serde(default)]
    id: Value,
    method: String,
    #[serde(default)]
    params: Value,
}

/// The parts of `SendMessageConfiguration` this server acts on.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
struct SendConfiguration {
    /// Return as soon as the task exists, rather than when it finishes.
    ///
    /// Blocking is the spec's default and the default here: unset means wait.
    #[serde(default)]
    return_immediately: bool,
    #[serde(default)]
    accepted_output_modes: Vec<String>,
    #[serde(default)]
    history_length: Option<usize>,
    #[serde(default)]
    task_push_notification_config: Option<PushRequest>,
}

impl SendConfiguration {
    fn validate(&self) -> Result<(), RpcError> {
        if !self.accepted_output_modes.is_empty()
            && !self
                .accepted_output_modes
                .iter()
                .any(|mode| matches!(mode.as_str(), "text/plain" | "application/json"))
        {
            return Err(RpcError::new(
                code::CONTENT_TYPE_NOT_SUPPORTED,
                "acceptedOutputModes contains no mode this agent can produce",
            ));
        }
        Ok(())
    }
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
struct PushAuthenticationRequest {
    scheme: String,
    #[serde(default)]
    credentials: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
struct PushRequest {
    #[serde(default)]
    id: Option<String>,
    #[serde(default)]
    task_id: Option<String>,
    url: String,
    #[serde(default)]
    token: Option<String>,
    #[serde(default)]
    authentication: Option<PushAuthenticationRequest>,
}

impl PushRequest {
    /// Refuse an id in the namespace an operator destination owns.
    ///
    /// A caller and the deployment share one push store, and the two are told
    /// apart by an id prefix. A caller allowed to write into that namespace could
    /// point one of the deployment's own destinations at an address it chose —
    /// and operator destinations are deliberately exempt from the host
    /// allowlist, HTTPS and the public-address check, because there is supposed
    /// to be no caller involved. This is the check that keeps that supposition
    /// true.
    fn validate(&self) -> Result<(), RpcError> {
        if self.id.as_deref().is_some_and(crate::push::is_operator_id) {
            return Err(RpcError::new(
                code::INVALID_PARAMS,
                format!(
                    "a pushNotificationConfig id may not begin with '{}': that namespace \
                     belongs to destinations this deployment configured for itself",
                    crate::push::OPERATOR_PREFIX
                ),
            ));
        }
        Ok(())
    }

    fn config(&self, task: RunId) -> crate::push::PushConfig {
        crate::push::PushConfig {
            id: self.id.clone().unwrap_or_else(|| format!("push-{task}")),
            task,
            url: self.url.clone(),
            token: self.token.clone().map(crate::core::Secret::new),
            authentication: self.authentication.as_ref().map(|authentication| {
                crate::push::PushAuthentication {
                    scheme: authentication.scheme.clone(),
                    credentials: crate::core::Secret::new(
                        authentication.credentials.clone().unwrap_or_default(),
                    ),
                }
            }),
        }
    }
}

/// What every method's params may carry.
///
/// One struct for every method, which is the same shape the binary's arguments
/// had before they moved onto per-verb structs: a field belonging to one method
/// was **silently accepted** by another and did nothing. On the wire that reads
/// worse than at a command line, because the caller is a stranger who cannot
/// see the source. `ListTasks` was the case that mattered — a request naming
/// `contxtId`, or the `context_id` the protocol's own conformance kit sends,
/// parsed cleanly, dropped the filter, and answered with **every** task the
/// caller may see, shaped exactly like the scoped list that was asked for.
///
/// Two mechanisms close it, and they are different questions.
/// [`deny_unknown_fields`] refuses a name this surface does not know at all
/// (`contxtId`, `task_id`), which the A2A specification licenses
/// outright: A2A §5.5 says JSON field names **MUST** be camelCase, so `context_id` is not an
/// alternative spelling but a violation. [`FIELDS_BY_METHOD`] refuses a name
/// this surface knows and *this method* does not (`pageSize` on `CancelTask`).
///
/// Neither subsumes the other.
///
/// [`deny_unknown_fields`]: https://serde.rs/container-attrs.html
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(deny_unknown_fields)]
struct CommonParams {
    /// A2A's opaque routing identifier.
    #[serde(default)]
    tenant: Option<String>,
    #[serde(default)]
    message: Option<A2aMessage>,
    #[serde(default)]
    id: Option<String>,
    #[serde(default)]
    configuration: Option<SendConfiguration>,
    /// `SendMessageRequest.metadata`, accepted and not interpreted.
    ///
    /// Modelled rather than ignored because the two are different answers now
    /// that unknown fields are refused: the specification defines this field, so
    /// a conforming client may send it and must not meet `-32602`. It is
    /// deliberately not read — opaque caller data has no governed meaning here,
    /// and inventing one would be a control nothing enforces. What the runtime
    /// does record about an inbound message is its authenticated sender, which
    /// is provenance rather than a field the sender chose.
    ///
    /// `dead_code` is allowed here for the one case where it is the point: the
    /// field exists so that deserialization *accepts* the name, and reading it
    /// is what would be wrong.
    #[serde(default)]
    #[allow(dead_code)]
    metadata: Option<Value>,
    #[serde(default, rename = "taskId")]
    push_task: Option<String>,
    #[serde(default)]
    url: Option<String>,
    #[serde(default)]
    token: Option<String>,
    #[serde(default)]
    authentication: Option<PushAuthenticationRequest>,
    #[serde(default, rename = "contextId")]
    context_id: Option<String>,
    #[serde(default)]
    status: Option<TaskState>,
    #[serde(default, rename = "pageSize")]
    page_size: Option<usize>,
    #[serde(default, rename = "pageToken")]
    page_token: Option<String>,
    #[serde(default, rename = "historyLength")]
    history_length: Option<usize>,
    #[serde(default, rename = "statusTimestampAfter")]
    status_timestamp_after: Option<String>,
    #[serde(default, rename = "includeArtifacts")]
    include_artifacts: bool,
}

/// A JSON-RPC error, carrying the HTTP status it should be served with.
#[derive(Debug, Clone)]
pub struct RpcError {
    code: i32,
    message: String,
    /// The id of the request being answered — `null` when it could not be read.
    id: Value,
}

impl RpcError {
    fn new(code: i32, message: impl Into<String>) -> Self {
        Self {
            code,
            message: message.into(),
            id: Value::Null,
        }
    }

    fn with_id(mut self, id: Value) -> Self {
        self.id = id;
        self
    }

    /// The machine-readable reason A2A 1.0's error-handling rules require
    /// beside an A2A-specific code, as a `google.rpc.ErrorInfo` in
    /// `error.data` — `(domain, reason)`.
    ///
    /// Derived from the code rather than declared per call site, because the
    /// two are one fact: the spec's table maps each code to exactly one reason
    /// token, and a site that could set them independently is a site that can
    /// disagree with itself. Standard JSON-RPC codes carry no reason — the
    /// spec assigns them none — so they return `None` and the error omits
    /// `data` rather than inventing a token.
    ///
    /// The spec's codes carry the spec's domain. [`code::QUOTA_EXHAUSTED`]
    /// carries this plane's own — [`ERROR_DOMAIN`](crate::peers::ERROR_DOMAIN)
    /// — and that domain is load-bearing rather than decorative: the numeric
    /// code sits in space A2A 1.0 reserves for its own future errors, so the
    /// code alone is not proof of what it means. The `(domain, reason)` pair
    /// is, and it is what this crate's client keys its back-off
    /// classification on.
    ///
    /// This adds no information a prober does not already have: the reason is
    /// a restatement of the code in the same response. The uniform-refusal
    /// rule governs what a *model* is told; this is the protocol channel to an
    /// authenticated peer.
    const fn reason(&self) -> Option<(&'static str, &'static str)> {
        const A2A: &str = "a2a-protocol.org";
        const SELF_DOMAIN: &str = crate::peers::ERROR_DOMAIN;
        const QUOTA_EXHAUSTED_REASON: &str = crate::peers::QUOTA_EXHAUSTED_REASON;
        const HALTED_REASON: &str = crate::peers::HALTED_REASON;
        const DRAINING_REASON: &str = crate::peers::DRAINING_REASON;
        match self.code {
            code::TASK_NOT_FOUND => Some((A2A, "TASK_NOT_FOUND")),
            code::TASK_NOT_CANCELABLE => Some((A2A, "TASK_NOT_CANCELABLE")),
            code::PUSH_NOT_SUPPORTED => Some((A2A, "PUSH_NOTIFICATION_NOT_SUPPORTED")),
            code::UNSUPPORTED_OPERATION => Some((A2A, "UNSUPPORTED_OPERATION")),
            code::CONTENT_TYPE_NOT_SUPPORTED => Some((A2A, "CONTENT_TYPE_NOT_SUPPORTED")),
            code::EXTENDED_CARD_NOT_CONFIGURED => Some((A2A, "EXTENDED_AGENT_CARD_NOT_CONFIGURED")),
            code::VERSION_NOT_SUPPORTED => Some((A2A, "VERSION_NOT_SUPPORTED")),
            code::QUOTA_EXHAUSTED => Some((SELF_DOMAIN, QUOTA_EXHAUSTED_REASON)),
            code::HALTED => Some((SELF_DOMAIN, HALTED_REASON)),
            code::DRAINING => Some((SELF_DOMAIN, DRAINING_REASON)),
            _ => None,
        }
    }

    /// The JSON-RPC error member, with the required `ErrorInfo` when one
    /// applies.
    fn body(&self) -> Value {
        match self.reason() {
            Some((domain, reason)) => json!({
                "code": self.code,
                "message": self.message,
                "data": [{
                    "@type": "type.googleapis.com/google.rpc.ErrorInfo",
                    "domain": domain,
                    "reason": reason,
                }],
            }),
            None => json!({ "code": self.code, "message": self.message }),
        }
    }
}

impl IntoResponse for RpcError {
    fn into_response(self) -> Response {
        // Always HTTP 200 with a JSON-RPC error body. JSON-RPC carries its own
        // error channel, and a transport-level status for an application-level
        // refusal is how a client ends up retrying a permanent decline: an
        // A2A client reads `error.code`, and many treat a 5xx as retryable
        // without ever parsing the body.
        (
            StatusCode::OK,
            Json(json!({
                "jsonrpc": "2.0",
                "id": self.id,
                "error": self.body(),
            })),
        )
            .into_response()
    }
}

/// This plane, served as an A2A agent.
#[derive(Clone)]
pub struct A2aServer {
    runtime: Arc<Runtime>,
    auth: Arc<dyn Authenticator>,
    policy: Arc<dyn crate::core::PolicyEngine>,
    card: AgentCard,
    extended: ExtendedAgentCard,
    /// Each agent's own card, by agent name.
    per_agent: std::collections::BTreeMap<String, crate::peers::AgentCard>,
    /// The card's advertised skill ids — what a caller may ask for.
    skills: Vec<String>,
    push: Option<PushRuntime>,
    /// How many candidate journals one content-filtered `ListTasks` may read.
    ///
    /// See [`Self::filter_scan_budget`] for why this is a ceiling and not a
    /// page size.
    filter_scan_budget: usize,
    /// How many strict replays one `ListTasks` with `includeArtifacts` may
    /// perform. See [`Self::artifact_replay_budget`].
    artifact_replay_budget: usize,
    /// Artifact projections of **sealed** runs, so a poll loop does not buy a
    /// strict replay per read. See [`ArtifactCache`].
    artifact_cache: Arc<std::sync::Mutex<ArtifactCache>>,
}

/// A bounded in-process cache of sealed runs' artifact projections.
///
/// A completed task's artifacts exist only as a projection of its journal, so
/// every read recovers them by **strict replay** — the most expensive read
/// this surface performs. The cache is sound because it holds only sealed
/// runs: a seal is the last record a run ever gets, so the projection is a
/// pure function of an immutable history and can never go stale. Bounded and
/// evicting oldest-first, because an unbounded cache is a leak with a
/// performance story; insertion order is enough where every entry is equally
/// immutable.
#[derive(Debug, Default)]
struct ArtifactCache {
    map: std::collections::HashMap<RunId, Option<Vec<A2aArtifact>>>,
    order: std::collections::VecDeque<RunId>,
}

/// How many sealed runs' artifact projections stay cached per server.
const ARTIFACT_CACHE_CAPACITY: usize = 256;

/// What one bounded artifact read produced.
enum ArtifactRead {
    /// The projection — from the cache or from one counted replay.
    Artifacts(Option<Vec<A2aArtifact>>),
    /// The request's replay budget is spent; the caller must say so.
    OverBudget,
}

impl ArtifactCache {
    /// A hit, already wrapped as the read it answers.
    fn get(&self, run: RunId) -> Option<ArtifactRead> {
        self.map
            .get(&run)
            .map(|artifacts| ArtifactRead::Artifacts(artifacts.clone()))
    }

    fn insert(&mut self, run: RunId, artifacts: Option<Vec<A2aArtifact>>) {
        if self.map.insert(run, artifacts).is_none() {
            self.order.push_back(run);
        }
        while self.map.len() > ARTIFACT_CACHE_CAPACITY {
            let Some(evicted) = self.order.pop_front() else {
                break;
            };
            self.map.remove(&evicted);
        }
    }
}

#[derive(Debug, Clone)]
struct PushRuntime {
    store: Arc<dyn crate::push::PushStore>,
    transport: Arc<dyn crate::push::PushTransport>,
}

/// Durable A2A webhook delivery, driven by an operator scheduler.
///
/// A name, not a type of its own: [`A2aServer::push_worker`] hands back the
/// [`DeliveryWorker`](crate::push::DeliveryWorker) itself, bound to the A2A
/// projection. The struct this alias replaced was a pure delegation shell — its
/// own docs said so — that re-stated the loop's retry ceiling and its default
/// in a second place, which is two copies of one contract with nothing holding
/// them together. The cursor discipline lives in `push` because it has nothing
/// to do with A2A; what is A2A about this worker is only the projection it was
/// constructed with.
pub type A2aPushWorker = crate::push::DeliveryWorker;

/// Outcome of one bounded push sweep.
///
/// Re-exported from [`crate::push`], which owns the delivery loop now.
pub use crate::push::PushSweepReport;

/// `StreamResponse` payloads, for **caller-registered** webhooks only.
///
/// It claims exactly the registrations an operator destination does not — see
/// [`crate::push::Outbox`] on why the two share one store and must not serve
/// each other's rows.
#[derive(Clone)]
struct A2aProjection {
    runtime: Arc<Runtime>,
}

impl std::fmt::Debug for A2aProjection {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("A2aProjection").finish_non_exhaustive()
    }
}

#[async_trait::async_trait]
impl crate::push::Projection for A2aProjection {
    async fn messages(
        &self,
        record: &crate::journal::Record,
    ) -> Result<Vec<crate::push::PushMessage>, crate::core::StoreError> {
        let case = record.body.case.map(|case| case.to_string());
        let payloads =
            super::a2a_stream::payloads_for_record(&self.runtime, record, case.as_deref())
                .await
                // A projection failure is this plane's own bug and always transient
                // to the worker; the shape it travels in is the store's error type
                // because that is what the seam speaks.
                .map_err(|error| crate::core::StoreError::Backend(error.to_string()))?;
        // One record can produce a status event and an artifact event, so the
        // record's sequence alone is not an identity. The id a receiver
        // deduplicates on is the task, the sequence and the position within
        // the record — stable across every retry of the same message, distinct
        // between the two.
        Ok(payloads
            .into_iter()
            .enumerate()
            .map(|(index, payload)| {
                crate::push::PushMessage::json(
                    format!("{}/{}/{index}", record.body.run, record.body.seq),
                    payload,
                )
                // A2A's media type, so a receiver routes push and streaming
                // through the same parser.
                .typed("application/a2a+json")
            })
            .collect())
    }

    fn namespace(&self) -> crate::push::PushNamespace {
        crate::push::PushNamespace::Caller
    }
}

impl std::fmt::Debug for A2aServer {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("A2aServer")
            .field("agent", &self.card.name)
            .field("skills", &self.skills)
            .finish_non_exhaustive()
    }
}

/// Why a server could not be built.
#[derive(Debug, thiserror::Error)]
pub enum ServerSetupError {
    #[error(
        "the runtime has no policy engine, so every A2A method would be \
         unauthorized. A surface reachable by other agents cannot be the one \
         place that skips the gate"
    )]
    NoPolicy,
    #[error(
        "the runtime has no case layer, so this server cannot mint the \
         contextId A2A 1.0 requires on every task — a generated contextId \
         must be continuable, and continuation here is a case. Build the \
         runtime with `.cases(store)`"
    )]
    NoCases,
    #[error("the agent card could not be derived: {0}")]
    Card(#[from] crate::manifest::ManifestError),
    #[error("push changes the signed Agent Card; configure it before calling signing_cards_with")]
    CardAlreadySigned,
    #[error(
        "an A2A server serves at least one agent, and no manifest was given — the well-known card path must answer with a card describing something"
    )]
    NoAgents,
    #[error(
        "agents '{first}' and '{second}' both advertise skill '{skill}', so a request naming it would be a routing decision the caller did not make. A2A dispatch is named, never inferred: give the skill distinct capability names, or serve the two agents from separate planes"
    )]
    AmbiguousSkill {
        skill: String,
        first: String,
        second: String,
    },
}

impl A2aServer {
    /// Serve `manifest`'s agent at `url`.
    ///
    /// `url` is where callers reach this plane, and it goes on the card — the
    /// same deployment-wiring split as everywhere else: an agent's declaration
    /// must not change when its address does.
    ///
    /// # Errors
    ///
    /// [`ServerSetupError::NoPolicy`] when the runtime has no policy engine, and
    /// [`ServerSetupError::Card`] when the manifest's digest cannot be computed.
    pub fn new(
        runtime: Arc<Runtime>,
        auth: Arc<dyn Authenticator>,
        security: &crate::peers::CardSecurity,
        manifest: &Manifest,
        url: impl Into<String>,
    ) -> Result<Self, ServerSetupError> {
        Self::hosting(runtime, auth, security, &[manifest], url)
    }

    /// Serve several declared agents from one plane.
    ///
    /// A2A's well-known card path is singular per host, so the alternative to
    /// this is a server per agent. The first manifest is the one the **well-known card
    /// describes** — a room's orchestrator, in the shape the CLI already uses —
    /// and every agent additionally gets its own full card at
    /// [`agent_card_path`](crate::peers::agent_card_path), listed in the
    /// [`EXT_AGENT_DIRECTORY`](crate::peers::EXT_AGENT_DIRECTORY) extension so
    /// a caller can find them.
    ///
    /// Skill dispatch spans every agent, because they are all on the runtime
    /// already — what was missing was only discovery. Two agents advertising
    /// one skill id is **refused**: dispatch names a skill, and a name that
    /// resolves to two agents is a routing decision the caller did not make.
    ///
    /// # Errors
    ///
    /// [`ServerSetupError::NoPolicy`], [`ServerSetupError::NoCases`],
    /// [`ServerSetupError::NoAgents`] for an empty slice, or
    /// [`ServerSetupError::AmbiguousSkill`].
    pub fn hosting(
        runtime: Arc<Runtime>,
        auth: Arc<dyn Authenticator>,
        security: &crate::peers::CardSecurity,
        manifests: &[&Manifest],
        url: impl Into<String>,
    ) -> Result<Self, ServerSetupError> {
        let policy = runtime.policy().ok_or(ServerSetupError::NoPolicy)?.clone();
        if runtime.cases().is_none() {
            return Err(ServerSetupError::NoCases);
        }
        let [primary, rest @ ..] = manifests else {
            return Err(ServerSetupError::NoAgents);
        };
        let url = url.into();

        // Every agent's own card, derived exactly as a lone agent's would be —
        // same digest, same skills, same ceilings. A card that differed because
        // its agent shared a plane would make the plane part of the identity a
        // consumer pins, which the room work already refused for manifests.
        let mut directory = Vec::new();
        let mut per_agent = std::collections::BTreeMap::new();
        let mut owner_of_skill: std::collections::BTreeMap<String, String> =
            std::collections::BTreeMap::new();
        for m in manifests {
            let name = m.metadata.name.clone();
            let mut agent_card = AgentCard::derive(m, url.clone())?;
            security.apply(&mut agent_card);
            for skill in &agent_card.skills {
                if let Some(other) = owner_of_skill.insert(skill.id.clone(), name.clone())
                    && other != name
                {
                    return Err(ServerSetupError::AmbiguousSkill {
                        skill: skill.id.clone(),
                        first: other,
                        second: name,
                    });
                }
            }
            directory.push(serde_json::json!({
                "name": name,
                "version": m.metadata.version,
                "cardPath": crate::peers::agent_card_path(&name),
                "manifestDigest": m.digest()?.to_hex(),
                "skills": agent_card.skills.iter().map(|s| s.id.clone()).collect::<Vec<_>>(),
            }));
            per_agent.insert(name, agent_card);
        }

        let mut card = AgentCard::derive(primary, url.clone())?;
        let mut extended = ExtendedAgentCard::derive(primary, url)?;
        security.apply(&mut card);
        security.apply(&mut extended.public);

        // Only when there is more than one, so a single-agent plane's card is
        // byte-for-byte what it was: an extension nobody needs is a claim a
        // verifier has to understand for nothing.
        if !rest.is_empty() {
            let ext = crate::peers::AgentExtension {
                uri: crate::peers::EXT_AGENT_DIRECTORY.to_owned(),
                description: Some(
                    "Every agent this plane serves, and where each agent's own card is.".to_owned(),
                ),
                required: false,
                params: Some(serde_json::json!({ "agents": directory })),
            };
            card.capabilities.extensions.push(ext.clone());
            extended.public.capabilities.extensions.push(ext);
        }

        // The card names the tenant only when there is one to route on. A2A's
        // rule is that a client echoes this value back in every request, so
        // advertising `default` would make every caller send a routing
        // identifier that routes nowhere.
        let tenant = runtime.tenant();
        if tenant.as_str() != crate::core::TenantId::DEFAULT {
            for iface in &mut card.supported_interfaces {
                iface.tenant = Some(tenant.to_string());
            }
            for iface in &mut extended.public.supported_interfaces {
                iface.tenant = Some(tenant.to_string());
            }
        }

        // The union, because every agent is already on the runtime and a skill
        // that dispatches but is not accepted here would be a refusal the plane
        // could have answered.
        let skills = owner_of_skill.keys().cloned().collect();
        Ok(Self {
            runtime,
            auth,
            policy,
            card,
            extended,
            per_agent,
            skills,
            push: None,
            filter_scan_budget: FILTER_SCAN_BUDGET,
            artifact_replay_budget: ARTIFACT_REPLAY_BUDGET,
            artifact_cache: Arc::new(std::sync::Mutex::new(ArtifactCache::default())),
        })
    }

    /// Bound what one content-filtered `ListTasks` may cost.
    ///
    /// A `status` or `contextId` filter can only be evaluated by reading a
    /// candidate task's journal, and the spec's `totalSize` is the exact total
    /// — so a filtered listing over a large tenant is a request whose cost the
    /// *caller* chooses. Unbounded, that is the same scan the paged index
    /// removed, reachable by any authenticated peer who adds one field.
    ///
    /// Over budget, the request is refused with the narrowing lever named —
    /// `statusTimestampAfter` is answered from the index, so tightening it
    /// shrinks the candidate set without reading anything. A refusal is honest
    /// where a truncated total would be a lie shaped like an answer: the spec
    /// requires the exact count, and a bound that quietly stopped counting
    /// would report a smaller tenant, not a bounded scan.
    #[must_use]
    pub fn filter_scan_budget(mut self, budget: usize) -> Self {
        self.filter_scan_budget = budget.max(1);
        self
    }

    /// Bound what one `ListTasks` with `includeArtifacts` may cost.
    ///
    /// A completed task's artifacts are recovered by strict replay, and a page
    /// holds up to a hundred tasks — so without a ceiling, one authenticated
    /// request buys a hundred full replays, per request, forever. Replays
    /// served from the sealed-run cache cost nothing and do not count; past
    /// the budget a task's artifacts are **omitted and marked** (see
    /// [`ARTIFACTS_OMITTED_KEY`]) rather than the request refused, because
    /// unlike `totalSize` an artifact list is per-task enrichment: omitting
    /// one is honest as long as it does not look complete, and `GetTask` on
    /// the marked id recovers exactly that task's artifacts.
    #[must_use]
    pub fn artifact_replay_budget(mut self, budget: usize) -> Self {
        self.artifact_replay_budget = budget.max(1);
        self
    }

    /// A task's artifacts, replaying at most once per sealed run.
    ///
    /// Consults [`ArtifactCache`] first and fills it for completed runs; the
    /// uncached fall-through is [`task_artifacts`]. `budget` is decremented on
    /// every actual replay, and `None` for the budget means unmetered — the
    /// single-task paths, where one replay is the request's stated cost.
    ///
    /// A budget hit comes back as [`ArtifactRead::OverBudget`], never as an
    /// absent list, so the caller must decide how to mark it — silence here
    /// would be a bounded result shaped exactly like a complete one.
    async fn artifacts_bounded(
        &self,
        run: RunId,
        state: TaskState,
        budget: Option<&mut usize>,
    ) -> Result<ArtifactRead, crate::core::RuntimeError> {
        if state != TaskState::Completed {
            return Ok(ArtifactRead::Artifacts(None));
        }
        if let Some(cached) = self
            .artifact_cache
            .lock()
            .expect("the artifact cache mutex is never poisoned")
            .get(run)
        {
            return Ok(cached);
        }
        if let Some(budget) = &budget
            && **budget == 0
        {
            return Ok(ArtifactRead::OverBudget);
        }
        let artifacts = task_artifacts(&self.runtime, run, state).await?;
        if let Some(budget) = budget {
            *budget -= 1;
        }
        self.artifact_cache
            .lock()
            .expect("the artifact cache mutex is never poisoned")
            .insert(run, artifacts.clone());
        Ok(ArtifactRead::Artifacts(artifacts))
    }

    /// Publish a **signed** card.
    ///
    /// The card is served unauthenticated from a host a caller may not control.
    /// TLS says the bytes came from that host; it says nothing about whether the
    /// host is the party whose capabilities the card describes. A signature says
    /// that, and it keeps saying it after the card has been copied into a
    /// registry, a cache, or somebody's repository.
    ///
    /// Signed here rather than at derivation because the signature covers the
    /// **published** card, interface URL and tenant included — those are
    /// deployment facts, and a signature taken before they were set would cover
    /// a document nobody serves.
    ///
    /// # Errors
    ///
    /// If the card cannot be canonicalized.
    pub fn signing_cards_with(
        mut self,
        signer: &dyn crate::peers::CardSigner,
    ) -> Result<Self, crate::peers::CardSignatureError> {
        self.card.sign(signer)?;
        self.extended.public.sign(signer)?;
        Ok(self)
    }

    /// Enable A2A push configuration and expose a durable delivery worker.
    ///
    /// The worker uses the task journal itself as its outbox. A registration's
    /// cursor advances only after a receiver returns 2xx, so a crash between
    /// POST and acknowledgement persistence repeats an event and never loses
    /// one. Call [`A2aServer::push_worker`] before consuming the server into its
    /// router and schedule
    /// [`DeliveryWorker::run_once`](crate::push::DeliveryWorker::run_once) from
    /// every instance.
    pub fn with_push(
        mut self,
        store: Arc<dyn crate::push::PushStore>,
        transport: Arc<dyn crate::push::PushTransport>,
    ) -> Result<Self, ServerSetupError> {
        if !self.card.signatures.is_empty() || !self.extended.public.signatures.is_empty() {
            return Err(ServerSetupError::CardAlreadySigned);
        }
        self.card.capabilities.push_notifications = true;
        self.extended.public.capabilities.push_notifications = true;
        self.push = Some(PushRuntime { store, transport });
        Ok(self)
    }

    /// A cloneable worker handle, when push is configured.
    ///
    /// The worker is [`crate::push::DeliveryWorker`] itself, bound to the A2A
    /// projection — rows belonging to an operator
    /// [`Outbox`](crate::push::Outbox) are left alone, because the projection
    /// declares the caller namespace and the store's due query filters on it.
    /// Retry ceiling, backoff and abandonment reporting are the loop's own;
    /// see its docs rather than a restatement here.
    #[must_use]
    pub fn push_worker(&self) -> Option<A2aPushWorker> {
        self.push.clone().map(|push| {
            crate::push::DeliveryWorker::new(
                Arc::clone(self.runtime.journal()),
                push.store,
                push.transport,
                Arc::new(A2aProjection {
                    runtime: Arc::clone(&self.runtime),
                }),
            )
        })
    }

    /// The router.
    ///
    /// The card path is unauthenticated by design and everything else is not.
    ///
    /// The RPC endpoint answers with and without a trailing slash, and that is
    /// an interoperability fact rather than a courtesy: mainstream HTTP clients
    /// that take a base URL — httpx among them, which is what the official A2A
    /// conformance kit and the reference Python SDK are built on — resolve a
    /// request for `"/"` against the card's interface URL per RFC 3986, so the
    /// wire carries `POST {interface}/`. A router that 404s the slash form
    /// passes every test written here and fails the first real peer. Exactness
    /// elsewhere (method names, version headers) guards protocol *semantics*;
    /// a trailing slash is a client-side join artifact with none.
    pub fn router(self) -> Router {
        Router::new()
            .route(WELL_KNOWN_PATH, get(agent_card))
            // Unauthenticated like the well-known card, and for the same
            // reason: a card a caller must already be trusted to read is a card
            // that cannot be discovered.
            .route("/agents/{agent}/agent-card.json", get(one_agent_card))
            .route("/a2a", post(rpc))
            .route("/a2a/", post(rpc))
            .with_state(self)
    }

    /// Authenticate, then authorize.
    async fn gate(
        &self,
        headers: &HeaderMap,
        action: &str,
        resource: &str,
    ) -> Result<Caller, RpcError> {
        let caller = self.auth.authenticate(headers).await.map_err(|e| {
            // Refused, not "invalid request": a caller that cannot authenticate
            // must not be told its request was malformed and try again with a
            // different body.
            RpcError::new(code::INVALID_REQUEST, e.to_string())
        })?;
        // The caller's tenant is the second half of the check `check_tenant`
        // starts. That one compares what the *request* asked for against what
        // the card advertises; this compares it against what the *credential*
        // says. A peer that authenticates into one tenant must not be served
        // from another's runs by naming it in a field, and a peer holding a
        // valid credential for a different tenant is exactly who would try.
        if caller.tenant != *self.runtime.tenant() {
            return Err(RpcError::new(
                code::INVALID_PARAMS,
                "this endpoint does not serve your tenant",
            ));
        }

        let context = json!({
            "roles": caller.roles,
            "peer": caller.actor,
            "tenant": caller.tenant.as_str(),
        });
        match self.policy.authorize(&PolicyRequest {
            principal: &caller.actor,
            action,
            resource,
            context: &context,
        }) {
            PolicyDecision::Permit => Ok(caller),
            PolicyDecision::Deny { reason } => {
                // The determining policy and its reason stay operator-side. A
                // Cedar denial names the action, the resource, and the policy
                // ids that fired; returned to an external caller that is a
                // probe-able map of the authorization vocabulary. A decline
                // carries no reason on the wire — the runtime's own denial
                // already names the action and resource the gate keyed on. The
                // caller learns only that it was declined; the reason reaches
                // whoever runs the plane.
                tracing::warn!(
                    target: "agentplane::a2a",
                    action,
                    resource,
                    reason,
                    "A2A request denied at admission"
                );
                Err(RpcError::new(
                    code::INVALID_REQUEST,
                    "this request was not permitted",
                ))
            }
            // The rules could not be evaluated. The caller is declined
            // exactly as for a denial — telling a peer that the plane's
            // policy set is broken is a fact about our operations, and a
            // probe would learn which shapes break it — but the operator's
            // side says defect rather than refusal, because the fix is the
            // policy set and nobody should be reading rules looking for the
            // one that fired.
            PolicyDecision::Malformed { reason } => {
                tracing::error!(
                    target: "agentplane::a2a",
                    action,
                    resource,
                    policy_error = true,
                    reason,
                    "A2A request refused because the policy set could not be evaluated"
                );
                Err(RpcError::new(
                    code::INVALID_REQUEST,
                    "this request was not permitted",
                ))
            }
        }
    }

    fn permits(&self, caller: &Caller, action: &str, resource: &str) -> bool {
        let context = json!({
            "roles": caller.roles,
            "peer": caller.actor,
            "tenant": caller.tenant.as_str(),
        });
        matches!(
            self.policy.authorize(&PolicyRequest {
                principal: &caller.actor,
                action,
                resource,
                context: &context,
            }),
            PolicyDecision::Permit
        )
    }

    /// Refuse a version this server does not speak.
    ///
    /// An **absent** header is a refusal, not a default. The spec says an empty
    /// value means 0.3, so a missing header is a 0.3 client — and answering it
    /// with 1.0 semantics is how a caller silently loses half the protocol.
    /// Matching is on `Major.Minor`, as the spec requires.
    fn check_version(headers: &HeaderMap) -> Result<(), RpcError> {
        let claimed = headers
            .get(VERSION_HEADER)
            .and_then(|v| v.to_str().ok())
            .unwrap_or("");
        let claimed_version = crate::peers::protocol_major_minor(claimed);
        if claimed_version == crate::peers::protocol_major_minor(crate::peers::PROTOCOL_VERSION)
            && claimed_version.is_some()
        {
            return Ok(());
        }
        let seen = if claimed.is_empty() {
            "0.3 (no A2A-Version header, which the spec reads as 0.3)".to_owned()
        } else {
            claimed.to_owned()
        };
        Err(RpcError::new(
            code::VERSION_NOT_SUPPORTED,
            format!(
                "this agent speaks A2A {}, and the request asked for {seen}",
                crate::peers::PROTOCOL_VERSION
            ),
        ))
    }

    /// Refuse a request routed to a different tenant.
    ///
    /// A2A's rule is that the client echoes the `tenant` from the interface it
    /// selected on the card, omitting it when the card omits it. So a value that
    /// does not match ours is a request meant for somebody else — plausibly
    /// another plane behind the same address — and answering it would serve one
    /// tenant's caller from another tenant's runs.
    fn check_tenant(&self, params: &CommonParams) -> Result<(), RpcError> {
        let ours = self.runtime.tenant().as_str();
        let advertised = if ours == crate::core::TenantId::DEFAULT {
            ""
        } else {
            ours
        };
        let sent = params.tenant.as_deref().unwrap_or("");
        if sent == advertised {
            return Ok(());
        }
        Err(RpcError::new(
            code::INVALID_PARAMS,
            format!(
                "this endpoint serves the tenant advertised on its card, and \
                 the request named '{sent}'. A2A clients echo the `tenant` from \
                 the interface they selected; a different value is a request \
                 for a different agent"
            ),
        ))
    }
}

/// The public Agent Card.
///
/// Unauthenticated on purpose — see the module docs. It is derived from the
/// manifest, so it cannot describe a capability the plane would refuse to
/// dispatch, which is what makes publishing it safe.
async fn agent_card(State(server): State<A2aServer>) -> Json<AgentCard> {
    Json(server.card)
}

/// One agent's own card.
///
/// A 404 for an unknown name, deliberately naming nothing: the directory
/// extension on the well-known card is how a caller learns which names exist,
/// and answering an unknown one with the list would make this path a way to
/// enumerate a plane without reading the card that governs it.
async fn one_agent_card(
    State(server): State<A2aServer>,
    axum::extract::Path(agent): axum::extract::Path<String>,
) -> Response {
    server.per_agent.get(&agent).map_or_else(
        || (StatusCode::NOT_FOUND, "no such agent on this plane").into_response(),
        |card| Json(card.clone()).into_response(),
    )
}

async fn rpc(
    State(server): State<A2aServer>,
    headers: HeaderMap,
    body: Result<Json<RpcRequest>, axum::extract::rejection::JsonRejection>,
) -> Response {
    let req = match body {
        Ok(Json(req)) => req,
        // The two refusals are different spec rows and must not share a code:
        // a body that is not `application/json` is `ContentTypeNotSupported`
        // (-32005) in A2A's own mapping table, while a body that *claims* JSON
        // and is not is JSON-RPC's ParseError. Collapsing them tells a caller
        // with a wrong header that its serializer is broken.
        Err(rejection) => {
            let error = match &rejection {
                axum::extract::rejection::JsonRejection::MissingJsonContentType(_) => {
                    RpcError::new(
                        code::CONTENT_TYPE_NOT_SUPPORTED,
                        "the request body must be application/json",
                    )
                }
                _ => RpcError::new(code::PARSE_ERROR, "the request body is not valid JSON-RPC"),
            };
            return error.into_response();
        }
    };
    let id = req.id.clone();

    if req.jsonrpc != "2.0" {
        return RpcError::new(
            code::INVALID_REQUEST,
            format!("`jsonrpc` must be \"2.0\", not {:?}", req.jsonrpc),
        )
        .with_id(id)
        .into_response();
    }
    if let Err(e) = A2aServer::check_version(&headers) {
        return e.with_id(id).into_response();
    }

    // Streaming methods are dispatched first because they answer with a
    // different *kind* of response: an SSE body, not a JSON-RPC envelope. Folding
    // them into `dispatch` would mean a function whose return type is "a value
    // or an entire HTTP response", which is how one of the two paths quietly
    // stops setting its content type.
    if matches!(
        req.method.as_str(),
        method::SEND_STREAMING | method::SUBSCRIBE
    ) {
        return match stream_method(server, headers, req).await {
            Ok(sse) => sse.into_response(),
            Err(e) => e.with_id(id).into_response(),
        };
    }

    match dispatch(&server, &headers, &req).await {
        Ok(result) => Json(json!({ "jsonrpc": "2.0", "id": id, "result": result })).into_response(),
        Err(e) => e.with_id(id).into_response(),
    }
}

/// `SendStreamingMessage` and `SubscribeToTask`.
///
/// Both are the same thing once the run exists: a view of the journal from a
/// point onward. The only difference is whether this call is what created it.
async fn stream_method(
    server: A2aServer,
    headers: HeaderMap,
    req: RpcRequest,
) -> Result<
    axum::response::sse::Sse<
        impl futures_util::stream::Stream<
            Item = Result<axum::response::sse::Event, std::convert::Infallible>,
        >,
    >,
    RpcError,
> {
    let params = parse_params(&req.method, &req.params)?;
    server.check_tenant(&params)?;
    if req.method == method::SEND_STREAMING
        && let Some(configuration) = &params.configuration
    {
        configuration.validate()?;
    }

    let run = if req.method == method::SUBSCRIBE {
        let id = task_id(&params)?;
        server
            .gate(&headers, action::TASK_READ, &id.to_string())
            .await?;
        id
    } else {
        let Some(message) = params.message.clone() else {
            return Err(RpcError::new(
                code::INVALID_PARAMS,
                "`message` is required by SendStreamingMessage",
            ));
        };
        message.validate_parts()?;
        if message.task_id.is_some() {
            continue_task(&server, &headers, &message).await?
        } else {
            let skill = resolve_skill(&server, &message)?;
            let caller = server.gate(&headers, action::MESSAGE_SEND, &skill).await?;
            if let Some(push) = params
                .configuration
                .as_ref()
                .and_then(|configuration| configuration.task_push_notification_config.as_ref())
            {
                validate_inline_push(&server, &headers, &skill, push).await?;
            }
            // Admitted before the stream opens. A stream that begins and *then*
            // reports a refusal has already told the client the work started —
            // and an SSE body cannot carry a JSON-RPC error the client is looking
            // for at that point.
            let source = super::peer_source(&caller.actor);
            let input = Tainted::from_source(message.to_input(), SourceId::new(&source));
            match spawn_a2a(&server, &skill, input, &message, &caller).await {
                Ok(run) => {
                    if let Some(push) = params.configuration.as_ref().and_then(|configuration| {
                        configuration.task_push_notification_config.as_ref()
                    }) {
                        register_push(&server, push, run, 1).await?;
                    }
                    run
                }
                Err(
                    crate::core::RuntimeError::PolicyDenied(_)
                    | crate::core::RuntimeError::Delegation(_),
                ) => {
                    return Err(RpcError::new(
                        code::UNSUPPORTED_OPERATION,
                        "this agent declined the request",
                    ));
                }
                Err(crate::core::RuntimeError::QuotaExceeded(e)) => {
                    return Err(quota_refusal(&e));
                }
                Err(crate::core::RuntimeError::Draining) => {
                    return Err(RpcError::new(code::DRAINING, DRAINING_MESSAGE));
                }
                Err(e) => return Err(RpcError::new(code::INTERNAL_ERROR, e.to_string())),
            }
        }
    };

    let Some((task, case, from)) = super::a2a_stream::current(&server.runtime, run).await else {
        return Err(RpcError::new(
            code::TASK_NOT_FOUND,
            format!("no such task: {run}"),
        ));
    };
    // `closes` and not a second `matches!` with the same four states: this
    // decides whether a subscription is *refused*, and `closes` decides whether
    // a stream *ends*. Two spellings of one rule disagree the day somebody adds
    // a terminal state to one of them, and the result is either a subscription
    // accepted that shuts immediately or one refused that would have streamed.
    if req.method == method::SUBSCRIBE && super::a2a_stream::closes(task.status.state) {
        return Err(RpcError::new(
            code::UNSUPPORTED_OPERATION,
            "SubscribeToTask requires a non-terminal task",
        ));
    }

    Ok(super::a2a_stream::tail(
        Arc::clone(&server.runtime),
        run,
        case,
        req.id,
        task,
        from,
    ))
}

async fn dispatch(
    server: &A2aServer,
    headers: &HeaderMap,
    req: &RpcRequest,
) -> Result<Value, RpcError> {
    let params = parse_params(&req.method, &req.params)?;
    server.check_tenant(&params)?;

    match req.method.as_str() {
        method::SEND_MESSAGE => send_message(server, headers, params).await,
        method::GET_TASK => get_task(server, headers, params).await,
        method::CANCEL_TASK => cancel_task(server, headers, params).await,
        method::GET_EXTENDED_CARD => get_extended_card(server, headers).await,

        // Streaming is handled before dispatch; reaching here means the router
        // changed and this arm did not.
        method::SEND_STREAMING | method::SUBSCRIBE => Err(RpcError::new(
            code::INTERNAL_ERROR,
            "a streaming method reached the non-streaming dispatcher",
        )),
        method::LIST_TASKS => list_tasks(server, headers, &params).await,
        method::CREATE_PUSH => push_create(server, headers, &params).await,
        method::GET_PUSH => push_get(server, headers, &params).await,
        method::LIST_PUSH => push_list(server, headers, &params).await,
        method::DELETE_PUSH => push_delete(server, headers, &params).await,
        other => Err(RpcError::new(
            code::METHOD_NOT_FOUND,
            format!("no such A2A method: {other}"),
        )),
    }
}

/// Which parameter names each method actually reads.
///
/// `tenant` is on every row rather than special-cased: A2A's routing identifier
/// is orthogonal to the method, and leaving it out of one row would refuse a
/// correctly-routed request for that method alone — the kind of hole a table
/// exists to make visible.
const FIELDS_BY_METHOD: &[(&str, &[&str])] = &[
    (
        method::SEND_MESSAGE,
        &["tenant", "message", "configuration", "metadata"],
    ),
    (
        method::SEND_STREAMING,
        &["tenant", "message", "configuration", "metadata"],
    ),
    (method::GET_TASK, &["tenant", "id", "historyLength"]),
    (method::CANCEL_TASK, &["tenant", "id"]),
    (method::SUBSCRIBE, &["tenant", "id"]),
    (method::GET_EXTENDED_CARD, &["tenant"]),
    (
        method::LIST_TASKS,
        &[
            "tenant",
            "contextId",
            "status",
            "pageSize",
            "pageToken",
            "historyLength",
            "statusTimestampAfter",
            "includeArtifacts",
        ],
    ),
    (
        method::CREATE_PUSH,
        &["tenant", "taskId", "id", "url", "token", "authentication"],
    ),
    (method::GET_PUSH, &["tenant", "taskId", "id"]),
    (
        method::LIST_PUSH,
        &["tenant", "taskId", "pageSize", "pageToken"],
    ),
    (method::DELETE_PUSH, &["tenant", "taskId", "id"]),
];

fn parse_params(method: &str, value: &Value) -> Result<CommonParams, RpcError> {
    if value.is_null() {
        return Ok(CommonParams::default());
    }
    let Some(object) = value.as_object() else {
        return Err(RpcError::new(
            code::INVALID_PARAMS,
            "A2A method parameters must be a JSON object",
        ));
    };

    // Before deserializing, because the union struct would accept the field and
    // the method would then ignore it. An unknown method falls through to the
    // dispatcher's own `METHOD_NOT_FOUND`, which is a better answer than a
    // parameter complaint about a method that does not exist.
    if let Some((_, allowed)) = FIELDS_BY_METHOD.iter().find(|(m, _)| *m == method)
        && let Some(stray) = object.keys().find(|k| !allowed.contains(&k.as_str()))
    {
        return Err(RpcError::new(
            code::INVALID_PARAMS,
            format!(
                "'{stray}' is not a parameter of {method}; it takes {}",
                allowed.join(", ")
            ),
        ));
    }

    serde_json::from_value(value.clone()).map_err(|error| {
        RpcError::new(
            code::INVALID_PARAMS,
            format!("request parameters do not match the A2A method schema: {error}"),
        )
    })
}

/// Answer a message aimed at a task that has already sealed.
///
/// Decided from the task's own journal: the event store's subscription may
/// already be retired, and routing a retransmit through `deliver_to` would
/// answer a legitimate retry with a terminal-state error. The journal records
/// every delivered continuation message verbatim, so the retry of the message
/// that completed the task is recognisable there — and a *new* message aimed
/// at a finished task stays refused.
fn continue_sealed_task(
    run: RunId,
    records: &[crate::journal::Record],
    message: &A2aMessage,
) -> Result<RunId, RpcError> {
    let delivered_before = records.iter().any(|record| {
        matches!(
            record.kind(),
            RecordKind::EffectDone { output, .. }
                if output
                    .get("$a2a_message")
                    .and_then(|m| m.get("messageId"))
                    .and_then(Value::as_str)
                    == Some(message.message_id.as_str())
        )
    });
    if delivered_before {
        return Ok(run);
    }
    Err(RpcError::new(
        code::UNSUPPORTED_OPERATION,
        "this task has completed and is not waiting for input",
    ))
}

/// Continue one interrupted A2A task with a client message.
///
/// The run remains append-only: the message becomes the output of the exact
/// `event.await` effect on which the task stopped, then ordinary resume replay
/// carries execution forward. `EventStore::deliver_to` is task-addressed and
/// atomic, so another run sharing the same business correlation key cannot
/// consume this message.
async fn continue_task(
    server: &A2aServer,
    headers: &HeaderMap,
    message: &A2aMessage,
) -> Result<RunId, RpcError> {
    let raw = message
        .task_id
        .as_deref()
        .ok_or_else(|| RpcError::new(code::INVALID_PARAMS, "`taskId` is required"))?;
    let run = RunId::parse(raw)
        .map_err(|_| RpcError::new(code::TASK_NOT_FOUND, format!("no such task: {raw}")))?;
    let caller = server
        .gate(headers, action::TASK_CONTINUE, &run.to_string())
        .await?;
    let records = server
        .runtime
        .journal()
        .read(run, 1)
        .await
        .map_err(|_| RpcError::new(code::INTERNAL_ERROR, "the journal could not be read"))?;
    let Some(last) = records.last() else {
        return Err(RpcError::new(
            code::TASK_NOT_FOUND,
            format!("no such task: {run}"),
        ));
    };
    if matches!(
        last.kind(),
        RecordKind::RunSuspended {
            reason: crate::core::SuspendReason::AwaitingTime { .. }
        }
    ) {
        return Err(RpcError::new(
            code::UNSUPPORTED_OPERATION,
            "this task is sleeping until a timer fires and cannot accept input",
        ));
    }
    if !matches!(
        last.kind(),
        RecordKind::RunSuspended { .. } | RecordKind::RunConcluded { .. }
    ) {
        return Err(RpcError::new(
            code::UNSUPPORTED_OPERATION,
            "this task is not waiting for input",
        ));
    }
    if matches!(last.kind(), RecordKind::RunConcluded { .. }) {
        return continue_sealed_task(run, &records, message);
    }
    // Search history rather than only the last record so a transport retry of
    // the message that completed a task can still be recognized as the same
    // `(source, messageId)` and return the current task instead of a spurious
    // terminal-task error. A different message id finds no live subscription
    // and remains refused.
    let (kind, correlation) = records
        .iter()
        .rev()
        .find_map(|record| match record.kind() {
            RecordKind::RunSuspended {
                reason:
                    crate::core::SuspendReason::AwaitingEvent {
                        kind, correlation, ..
                    },
            } => Some((kind.clone(), correlation.clone())),
            _ => None,
        })
        .ok_or_else(|| {
            RpcError::new(
                code::UNSUPPORTED_OPERATION,
                "this task has no input wait to continue",
            )
        })?;
    let context = records
        .iter()
        .find_map(|record| record.body.case.map(|case| case.to_string()));
    if let Some(sent) = message.context_id.as_deref()
        && context.as_deref() != Some(sent)
    {
        return Err(RpcError::new(
            code::INVALID_PARAMS,
            "message.contextId does not match the referenced task",
        ));
    }

    let event = crate::core::InboundEvent {
        // `peer:{actor}`, the one spelling a counterparty's provenance has on
        // every transport — see [`super::peer_source`]. This source becomes the
        // delivered value's provenance, so a transport-qualified variant here
        // would give one counterparty two names.
        source: super::peer_source(&caller.actor),
        id: message.message_id.clone(),
        kind,
        correlation,
        payload: message.to_input(),
    };
    match server.runtime.deliver_to(run, &event).await {
        // `Buffered` is a success too: when the owner's lease is stalled the
        // input is held durably and the sweep resumes the run — an internal
        // error here would tell the caller a continuation failed that
        // actually succeeded-pending.
        Ok(
            crate::core::Delivery::Resumed { .. }
            | crate::core::Delivery::Duplicate
            | crate::core::Delivery::Buffered,
        ) => Ok(run),
        Err(crate::core::RuntimeError::PlanContract(_)) => Err(RpcError::new(
            code::UNSUPPORTED_OPERATION,
            "this task is no longer waiting for input",
        )),
        Err(error) => Err(RpcError::new(code::INTERNAL_ERROR, error.to_string())),
    }
}

#[allow(clippy::too_many_lines)]
async fn send_message(
    server: &A2aServer,
    headers: &HeaderMap,
    params: CommonParams,
) -> Result<Value, RpcError> {
    if let Some(configuration) = &params.configuration {
        configuration.validate()?;
    }
    let inline_push = params
        .configuration
        .as_ref()
        .and_then(|configuration| configuration.task_push_notification_config.clone());
    let Some(message) = params.message else {
        return Err(RpcError::new(
            code::INVALID_PARAMS,
            "`message` is required by SendMessage",
        ));
    };
    message.validate_parts()?;
    if message.task_id.is_some() {
        let history_length = params
            .configuration
            .as_ref()
            .and_then(|configuration| configuration.history_length);
        let run = continue_task(server, headers, &message).await?;
        return get_task(
            server,
            headers,
            CommonParams {
                id: Some(run.to_string()),
                history_length,
                ..CommonParams::default()
            },
        )
        .await
        .map(|task| json!({ "task": task }));
    }
    let skill = resolve_skill(server, &message)?;
    let caller = server.gate(headers, action::MESSAGE_SEND, &skill).await?;
    if let Some(push) = &inline_push {
        validate_inline_push(server, headers, &skill, push).await?;
    }

    // Untrusted, and provenanced to the peer that sent it. A protected sink
    // field can then name the one counterparty it will take an amount from, and
    // a skill that wants to act on this has to pass a gate to do it.
    let source = super::peer_source(&caller.actor);
    let input = Tainted::from_source(message.to_input(), SourceId::new(&source));

    // Non-blocking: the spec requires returning as soon as the task exists,
    // with an in-progress state, leaving the caller to poll `GetTask`. Admission
    // still happens synchronously, so a refusal is still an immediate answer —
    // returning a task id for a run the gate rejected would hand the caller a
    // handle to nothing and turn a decline into a task that never appears.
    if params
        .configuration
        .as_ref()
        .is_some_and(|c| c.return_immediately)
    {
        return match spawn_a2a(server, &skill, input, &message, &caller).await {
            Ok(run) => {
                if let Some(push) = &inline_push {
                    register_push(server, push, run, 1).await?;
                }
                let case = task_context(server, run).await?;
                Ok(json!({
                    "task": task_of(run, TaskState::Working, "accepted", case)
                }))
            }
            Err(
                crate::core::RuntimeError::PolicyDenied(_)
                | crate::core::RuntimeError::Delegation(_),
            ) => Ok(json!({ "message": declined(&skill) })),
            Err(crate::core::RuntimeError::QuotaExceeded(e)) => Err(quota_refusal(&e)),
            Err(crate::core::RuntimeError::Draining) => {
                Err(RpcError::new(code::DRAINING, DRAINING_MESSAGE))
            }
            Err(crate::core::RuntimeError::PlanContract(why)) if message.context_id.is_some() => {
                Err(RpcError::new(code::TASK_NOT_FOUND, why))
            }
            Err(e) => Err(RpcError::new(code::INTERNAL_ERROR, e.to_string())),
        };
    }

    let admission = match run_a2a(server, &skill, input, &message, &caller).await {
        Ok(admission) => admission,
        // A policy denial is the agent *declining*, not the agent breaking.
        // Reported as `-32603 Internal error` it reads as "this server is
        // faulty, retry later", and the caller retries a decision that will
        // never change.
        //
        // Answered as a `Message` rather than a rejected `Task` because no task
        // exists: nothing was admitted, so there is no id to poll and no
        // history to fetch. A2A's response is a oneof for exactly this.
        Err(
            crate::core::RuntimeError::PolicyDenied(_) | crate::core::RuntimeError::Delegation(_),
        ) => {
            return Ok(json!({ "message": declined(&skill) }));
        }
        // Back-pressure, not a fault. `-32603` reads as "the far side is
        // broken, retry later" and a caller may well retry the same second;
        // this says *the agent cannot take this on right now*, which is what a
        // ceiling means and what a caller should back off from. The code and
        // message are fixed — see `code::QUOTA_EXHAUSTED` for why neither is
        // the spec's `-32004` and why the quota arithmetic stays out of it.
        Err(crate::core::RuntimeError::QuotaExceeded(e)) => {
            return Err(quota_refusal(&e));
        }
        // Not a fault and not back-pressure from the agent: this process is
        // going away and admitted nothing. A caller retrying now reaches a
        // different instance and is served.
        Err(crate::core::RuntimeError::Draining) => {
            return Err(RpcError::new(code::DRAINING, DRAINING_MESSAGE));
        }
        Err(crate::core::RuntimeError::PlanContract(why)) if message.context_id.is_some() => {
            return Err(RpcError::new(code::TASK_NOT_FOUND, why));
        }
        Err(e) => return Err(RpcError::new(code::INTERNAL_ERROR, e.to_string())),
    };
    let outcome = match admission {
        crate::runtime::Admission::Fresh(outcome)
        | crate::runtime::Admission::Replayed(outcome) => outcome,
        // Another instance is executing this message right now. The honest
        // answer to a retry is *accepted, already in progress* — a Working
        // task naming the run — never a retry-provoking failure.
        crate::runtime::Admission::InFlight(run) => {
            let case = task_context(server, run).await?;
            return Ok(json!({
                "task": task_of(run, TaskState::Working, "accepted", case)
            }));
        }
    };

    let case = task_context(server, outcome.run_id).await?;
    // A declared `Message` reply answers the blocking send directly — A2A's
    // response is a oneof for exactly this, and it is the only path with a
    // caller still waiting to hand a message to. Returned before push
    // registration, because a response with no task has no task to push about;
    // the run and its journal exist either way.
    if matches!(outcome.status, crate::runtime::RunStatus::Succeeded)
        && let Some(reply) = outcome.output.as_ref().and_then(A2aReply::of_output)
        && let Some(parts) = reply.message_parts()
    {
        return Ok(json!({
            "message": A2aMessage {
                message_id: format!("reply-{}", outcome.run_id),
                role: "ROLE_AGENT".to_owned(),
                parts,
                context_id: case,
                task_id: None,
                metadata: None,
                extensions: Vec::new(),
                reference_task_ids: Vec::new(),
            }
        }));
    }
    if let Some(push) = &inline_push {
        register_push(server, push, outcome.run_id, 1).await?;
    }
    let mut task = task_of_outcome(&outcome);
    task.context_id = case;
    // Unset means the full (capped) history, per the protocol's default —
    // only an explicit `0` skips the read.
    let history_length = params
        .configuration
        .as_ref()
        .and_then(|configuration| configuration.history_length);
    if history_length != Some(0) {
        let records = server
            .runtime
            .journal()
            .read(outcome.run_id, 1)
            .await
            .map_err(|_| {
                RpcError::new(code::INTERNAL_ERROR, "the task journal could not be read")
            })?;
        task.history = task_history(
            outcome.run_id,
            &records,
            history_length,
            task.context_id.as_deref(),
        );
    }
    Ok(json!({ "task": task }))
}

async fn run_a2a(
    server: &A2aServer,
    skill: &str,
    input: Tainted<Value>,
    message: &A2aMessage,
    caller: &Caller,
) -> Result<crate::runtime::Admission, crate::core::RuntimeError> {
    server
        .runtime
        .run_under(skill, input, run_terms(message, caller)?)
        .await
}

async fn spawn_a2a(
    server: &A2aServer,
    skill: &str,
    input: Tainted<Value>,
    message: &A2aMessage,
    caller: &Caller,
) -> Result<RunId, crate::core::RuntimeError> {
    // Producer-scoped and deduplicating, for the reasons `run_terms` states.
    // A duplicate answers with the run the key already admitted, which is
    // exactly what a retrying caller needs back.
    Ok(server
        .runtime
        .spawn_under(skill, input, run_terms(message, caller)?)
        .await?
        .run)
}

/// The terms every A2A admission runs under: keyed by the producer-scoped
/// message id, inside the case the caller named or a fresh one, and **acting
/// as the caller** where the credential carried a chain.
///
/// The key carries its producer, in the spelling `InboundEvent::dedup_key`
/// blesses: a bare `messageId` would let two counterparties swallow each
/// other's messages as apparent retries — or *join* each other's cases, since
/// correlation matches any open case in the tenant. And it is an **admission**
/// key, not only a correlation key: this crate's own client keeps `messageId`
/// stable across retries precisely so a peer can deduplicate, and a server
/// that correlates without deduplicating starts a second run inside the right
/// case.
///
/// The chain is the caller's, never the plane's: a plane that admitted every
/// peer's run under its own chain would answer "on whose behalf" with the same
/// name for all of them, and act for a caller whose credential permits less.
fn run_terms(
    message: &A2aMessage,
    caller: &Caller,
) -> Result<crate::runtime::RunTerms, crate::core::RuntimeError> {
    let source = super::peer_source(&caller.actor);
    let keyed = format!("{source}\u{1f}{}", message.message_id);
    let mut terms = crate::runtime::RunTerms::default().once(&keyed);
    if let Some(chain) = caller.acting_as.as_ref() {
        terms = terms.acting_as(chain.clone());
    }
    Ok(match message.context_id.as_deref() {
        Some(context) => {
            let case = crate::core::CaseId::parse(context).map_err(|_| {
                crate::core::RuntimeError::PlanContract(
                    "contextId is not a case issued here".into(),
                )
            })?;
            terms.in_case(case)
        }
        // Always correlated: `A2aServer::new` refuses a runtime without a case
        // layer, so every task gets a real, continuable context — the
        // contextId returned is one a client can send back, not a string that
        // satisfies a schema and continues nothing.
        None => terms.correlated(
            "a2a.context",
            &[crate::core::CorrelationKey::new("a2a-message", &keyed)],
        ),
    })
}

async fn task_context(server: &A2aServer, run: RunId) -> Result<Option<String>, RpcError> {
    server
        .runtime
        .journal()
        .read(run, 1)
        .await
        .map_err(|_| RpcError::new(code::INTERNAL_ERROR, "the task journal could not be read"))
        .map(|records| {
            records
                .iter()
                .find_map(|record| record.body.case.map(|case| case.to_string()))
        })
}

pub(super) fn task_of_outcome(outcome: &crate::runtime::RunOutcome) -> A2aTask {
    // A declared reply carries its own parts; otherwise the default projection
    // stands — a string is a text part, anything else a data part.
    let artifacts_parts: Vec<Vec<Part>> =
        match outcome.output.as_ref().and_then(A2aReply::of_output) {
            Some(reply) => reply.artifact_parts(),
            None => vec![vec![match outcome
                .output
                .as_ref()
                .map_or(Value::Null, |o| o.peek().clone())
            {
                Value::String(text) => Part::text(text),
                data => Part::data(data),
            }]],
        };
    A2aTask {
        id: outcome.run_id.to_string(),
        context_id: None,
        status: TaskStatus {
            state: state_of(&outcome.status),
            message: None,
            timestamp: None,
        },
        artifacts: matches!(outcome.status, crate::runtime::RunStatus::Succeeded).then(|| {
            artifacts_parts
                .into_iter()
                .enumerate()
                .map(|(i, parts)| A2aArtifact {
                    artifact_id: format!("{}-result-{i}", outcome.run_id),
                    name: None,
                    description: None,
                    parts,
                    metadata: None,
                    extensions: Vec::new(),
                })
                .collect()
        }),
        history: None,
        metadata: None,
    }
}

/// Which capability this message asks for.
///
/// Named or unambiguous — never inferred. See the module docs: picking a
/// capability from the content of an untrusted message is a dispatch decision
/// made by reading attacker-controlled text.
fn resolve_skill(server: &A2aServer, message: &A2aMessage) -> Result<String, RpcError> {
    if let Some(asked) = message.requested_skill() {
        if server.skills.iter().any(|s| s == asked) {
            return Ok(asked.to_owned());
        }
        return Err(RpcError::new(
            code::INVALID_PARAMS,
            format!(
                "this agent has no skill '{asked}'. Its card advertises: {}",
                server.skills.join(", ")
            ),
        ));
    }
    match server.skills.as_slice() {
        [only] => Ok(only.clone()),
        [] => Err(RpcError::new(
            code::UNSUPPORTED_OPERATION,
            "this agent advertises no skills, so there is nothing to send a \
             message to",
        )),
        many => Err(RpcError::new(
            code::INVALID_PARAMS,
            format!(
                "this agent advertises {} skills, so `message.metadata.skill` \
                 must name one of: {}. It is not inferred from the message — \
                 choosing what to run by reading the text would let the sender \
                 pick the capability",
                many.len(),
                many.join(", ")
            ),
        )),
    }
}

async fn get_task(
    server: &A2aServer,
    headers: &HeaderMap,
    params: CommonParams,
) -> Result<Value, RpcError> {
    let id = task_id(&params)?;
    server
        .gate(headers, action::TASK_READ, &id.to_string())
        .await?;

    load_task(server, id, params.history_length).await
}

async fn load_task(
    server: &A2aServer,
    id: RunId,
    history_length: Option<usize>,
) -> Result<Value, RpcError> {
    let records = server
        .runtime
        .journal()
        .read(id, 1)
        .await
        .map_err(|_| RpcError::new(code::INTERNAL_ERROR, "the journal could not be read"))?;
    // No records is no such task: a run this plane never admitted and a task id
    // a caller invented are the same fact from here.
    let (state, detail) = state_from_history(&records)
        .ok_or_else(|| RpcError::new(code::TASK_NOT_FOUND, format!("no such task: {id}")))?;
    let case = records
        .iter()
        .find_map(|r| r.body.case.map(|c| c.to_string()));

    let mut task = task_of(id, state, &detail, case.clone());
    task.history = task_history(id, &records, history_length, case.as_deref());
    // Unmetered: one task, one replay, and the sealed-run cache spares the
    // poll loop that reads the same finished task every few seconds.
    task.artifacts = match server
        .artifacts_bounded(id, state, None)
        .await
        .map_err(|error| RpcError::new(code::INTERNAL_ERROR, error.to_string()))?
    {
        ArtifactRead::Artifacts(artifacts) => artifacts,
        ArtifactRead::OverBudget => unreachable!("an unmetered read has no budget to exceed"),
    };
    serde_json::to_value(task)
        .map_err(|error| RpcError::new(code::INTERNAL_ERROR, error.to_string()))
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct TaskCursor {
    updated_at: u64,
    run: String,
    context_id: Option<String>,
    status: Option<TaskState>,
    status_timestamp_after: Option<String>,
}

/// How many index rows `list_tasks` pulls per store round trip.
///
/// Bounded so no path holds the tenant's whole index in memory — which is what
/// the unbounded read this replaced did on *every* call, before going on to
/// read the complete journal of every run it returned.
const TASK_SCAN: usize = 256;

/// Default for [`A2aServer::filter_scan_budget`]: the most candidate journals
/// one content-filtered `ListTasks` may read before being refused as too broad.
///
/// The number is a cost ceiling, not a result limit — results are bounded by
/// `pageSize` already. At the default, the worst request a peer can make costs
/// on the order of a thousand journal reads, once, and is told how to narrow;
/// without it the cost was every run the tenant ever wrote, per request,
/// forever.
const FILTER_SCAN_BUDGET: usize = 1024;

/// Default for [`A2aServer::artifact_replay_budget`]: the most strict replays
/// one `ListTasks` with `includeArtifacts` may perform.
///
/// A cost ceiling in the same spirit as [`FILTER_SCAN_BUDGET`], for the other
/// caller-priced read: each completed task's artifacts are a full strict
/// replay, a page holds up to a hundred tasks, and the sealed-run cache means
/// only first sight of a run pays it. Sixteen replays is a bounded worst case
/// per request; a page that wanted more marks the remainder omitted, and a
/// second request finds the first sixteen cached.
const ARTIFACT_REPLAY_BUDGET: usize = 16;

/// The task-metadata key marking artifacts withheld by the replay budget.
///
/// A bounded result must not be shaped like a complete one — a silent
/// truncation reads as an answer. A
/// task past the budget is returned without artifacts — indistinguishable from
/// several honest states — so the omission says its own name, in `Task.metadata`
/// because that is the field A2A gives a server for exactly this kind of
/// annotation; a new top-level response member would be a schema no client
/// expects. `GetTask` on the marked id recovers the artifacts, and warms the
/// cache doing it.
pub const ARTIFACTS_OMITTED_KEY: &str = "io.agentplane.a2a/artifactsOmitted";

#[allow(clippy::too_many_lines)]
async fn list_tasks(
    server: &A2aServer,
    headers: &HeaderMap,
    params: &CommonParams,
) -> Result<Value, RpcError> {
    let caller = server.gate(headers, action::TASK_READ, "tasks").await?;
    let page_size = params.page_size.unwrap_or(50);
    if !(1..=100).contains(&page_size) {
        return Err(RpcError::new(
            code::INVALID_PARAMS,
            "pageSize must be between 1 and 100",
        ));
    }
    let after = params
        .status_timestamp_after
        .as_deref()
        .map(|value| {
            time::OffsetDateTime::parse(value, &time::format_description::well_known::Rfc3339)
                .map_err(|_| {
                    RpcError::new(
                        code::INVALID_PARAMS,
                        "statusTimestampAfter must be an RFC 3339 timestamp",
                    )
                })
        })
        .transpose()?;
    let cursor = params
        .page_token
        .as_deref()
        .map(decode_task_cursor)
        .transpose()?;
    if let Some(cursor) = &cursor
        && (cursor.context_id != params.context_id
            || cursor.status != params.status
            || cursor.status_timestamp_after != params.status_timestamp_after)
    {
        return Err(RpcError::new(
            code::INVALID_PARAMS,
            "pageToken was issued for different ListTasks filters",
        ));
    }

    // Whether the caller asked anything that can only be answered by reading a
    // run's journal. `statusTimestampAfter` is not one of those — it compares
    // against the activity index's own timestamp — and neither is the
    // permission check, which sees only the run id.
    //
    // That split is the whole performance story. The expensive operation is
    // `read`, which pulls a run's complete journal; everything else here is
    // index data the store hands back beside the id. So an unfiltered listing
    // reads exactly the journals that appear on the page, and a content-filtered
    // one reads the candidates it must examine to answer honestly.
    let content_filtered = params.context_id.is_some() || params.status.is_some();

    let mut cursor_pos = cursor
        .as_ref()
        .and_then(|c| RunId::parse(&c.run).ok().map(|run| (c.updated_at, run)));
    let mut page: Vec<(RunId, u64, A2aTask)> = Vec::new();
    let mut matched: u64 = 0;
    let mut has_more = false;
    let mut reads: usize = 0;

    loop {
        let batch = server
            .runtime
            .journal()
            .recent_runs(cursor_pos, TASK_SCAN)
            .await
            .map_err(|_| RpcError::new(code::INTERNAL_ERROR, "the task index could not be read"))?;
        if batch.is_empty() {
            break;
        }
        cursor_pos = batch.last().map(|(run, updated)| (*updated, *run));

        for (run, updated) in batch {
            // Both of these read the index only, and the first is load-bearing
            // for more than cost: a run the caller may not read must not reach
            // the total either, or `totalSize` discloses the existence of tasks
            // the policy just refused to show them.
            if !server.permits(&caller, action::TASK_READ, &run.to_string()) {
                continue;
            }
            if after.is_some_and(|cutoff| {
                i64::try_from(updated)
                    .ok()
                    .and_then(|seconds| time::OffsetDateTime::from_unix_timestamp(seconds).ok())
                    .is_none_or(|value| value < cutoff)
            }) {
                continue;
            }

            // Read only when the answer needs it: to evaluate a content filter,
            // or to build a task that will actually be returned.
            let wanted = page.len() < page_size;
            if !content_filtered && !wanted {
                matched += 1;
                has_more = true;
                continue;
            }

            // The ceiling on what one filtered listing may cost. A `status` or
            // `contextId` filter is answerable only by reading the candidate's
            // journal, and the spec's `totalSize` is the exact pre-pagination
            // total — so without a bound, one authenticated request costs every
            // run the tenant ever wrote, which is the scan the paged index
            // exists to prevent. Refused rather than truncated: a total that
            // quietly stopped counting is a smaller tenant, not a bounded scan,
            // and the refusal names the lever that narrows without reading —
            // `statusTimestampAfter` is answered from the index.
            reads += 1;
            if content_filtered && reads > server.filter_scan_budget {
                return Err(RpcError::new(
                    code::INVALID_PARAMS,
                    format!(
                        "this filter would require examining more than {} tasks to answer \
                         exactly — narrow it with statusTimestampAfter and page from there",
                        server.filter_scan_budget
                    ),
                ));
            }
            let records = server.runtime.journal().read(run, 1).await.map_err(|_| {
                RpcError::new(code::INTERNAL_ERROR, "a task journal could not be read")
            })?;
            let task = task_from_records(run, &records, updated, params.history_length);
            if params
                .context_id
                .as_ref()
                .is_some_and(|context| task.context_id.as_ref() != Some(context))
                || params
                    .status
                    .as_ref()
                    .is_some_and(|status| &task.status.state != status)
            {
                continue;
            }
            matched += 1;
            if wanted {
                page.push((run, updated, task));
            } else {
                has_more = true;
            }
        }
    }

    // Exact, and counted over the same rows the caller was allowed to see. The
    // easy mistake is reporting the page's length, which tells every caller the
    // total is whatever fits on a screen; the dangerous one is counting the
    // store's index directly, which is cheaper and reveals the tasks policy
    // just hid. Saturated at the wire type's ceiling: the proto field is an
    // `int32`, and a count past it must not overflow a conformant client's
    // deserializer.
    let total_size = matched.min(u64::try_from(i32::MAX).unwrap_or(u64::MAX));

    let visible = &page[..];
    let next_page_token = if has_more {
        let (run, updated, _) = visible.last().expect("a page with more has a last item");
        encode_task_cursor(&TaskCursor {
            updated_at: *updated,
            run: run.to_string(),
            context_id: params.context_id.clone(),
            status: params.status,
            status_timestamp_after: params.status_timestamp_after.clone(),
        })?
    } else {
        String::new()
    };
    let mut tasks = Vec::with_capacity(visible.len());
    // The replay budget for this whole request. Cache hits are free; each
    // cache miss is a strict replay and spends one. Past it a task's artifacts
    // are omitted **and marked** — see [`ARTIFACTS_OMITTED_KEY`] for why the
    // omission must say its own name.
    let mut replays_left = server.artifact_replay_budget;
    for (run, _, task) in visible {
        let mut task = task.clone();
        if params.include_artifacts {
            match server
                .artifacts_bounded(*run, task.status.state, Some(&mut replays_left))
                .await
                .map_err(|error| RpcError::new(code::INTERNAL_ERROR, error.to_string()))?
            {
                ArtifactRead::Artifacts(artifacts) => task.artifacts = artifacts,
                ArtifactRead::OverBudget => {
                    task.metadata = Some(json!({ ARTIFACTS_OMITTED_KEY: true }));
                }
            }
        }
        tasks.push(task);
    }
    Ok(json!({
        "tasks": tasks,
        "nextPageToken": next_page_token,
        "pageSize": page_size,
        "totalSize": total_size,
    }))
}

fn encode_task_cursor(cursor: &TaskCursor) -> Result<String, RpcError> {
    crate::core::canon::to_bytes(cursor)
        .map(crate::core::b64::encode_url)
        .map_err(|_| RpcError::new(code::INTERNAL_ERROR, "the task cursor could not be encoded"))
}

fn decode_task_cursor(token: &str) -> Result<TaskCursor, RpcError> {
    crate::core::b64::decode_url(token)
        .and_then(|bytes| serde_json::from_slice(&bytes).ok())
        .ok_or_else(|| RpcError::new(code::INVALID_PARAMS, "pageToken is not a valid task cursor"))
}

fn task_from_records(
    run: RunId,
    records: &[crate::journal::Record],
    updated: u64,
    history_length: Option<usize>,
) -> A2aTask {
    // A run with no records is one whose first append has not landed. It is
    // reported as working rather than refused, because this builds a row in a
    // listing where a single unreadable run must not fail the page.
    let (state, detail) =
        state_from_history(records).unwrap_or_else(|| (TaskState::Working, "running".to_owned()));
    let case = records
        .iter()
        .find_map(|record| record.body.case.map(|case| case.to_string()));
    let timestamp = i64::try_from(updated)
        .ok()
        .and_then(|seconds| time::OffsetDateTime::from_unix_timestamp(seconds).ok())
        .and_then(|value| {
            value
                .format(&time::format_description::well_known::Rfc3339)
                .ok()
        });
    let history = task_history(run, records, history_length, case.as_deref());
    let mut task = task_of(run, state, &detail, case);
    task.status.timestamp = timestamp;
    task.history = history;
    task
}

/// The most messages an unbounded history request returns.
///
/// The protocol reads an **unset** `historyLength` as "the full history", so
/// the bound is the server's, stated here rather than left to whatever the
/// journal happens to hold — the same shape as the artifact replay budget.
const HISTORY_CAP: usize = 128;

fn task_history(
    run: RunId,
    records: &[crate::journal::Record],
    history_length: Option<usize>,
    case: Option<&str>,
) -> Option<Vec<A2aMessage>> {
    // Unset means full (capped); `0` is the explicit request for none —
    // the protocol's own default, which a conformant client expecting its
    // conversation back depends on.
    let limit = history_length.unwrap_or(HISTORY_CAP);
    {
        if limit == 0 {
            return None;
        }
        let mut history = Vec::new();
        for record in records {
            let input = match record.kind() {
                RecordKind::RunAdmitted { input, .. } => Some(input),
                RecordKind::EffectDone { output, .. } if output.get("$a2a_message").is_some() => {
                    Some(output)
                }
                _ => None,
            };
            let Some(input) = input else { continue };
            if let Some(message) = input.get("$a2a_message")
                && let Ok(mut message) = serde_json::from_value::<A2aMessage>(message.clone())
            {
                message.task_id = Some(run.to_string());
                if message.context_id.is_none() {
                    message.context_id = case.map(ToOwned::to_owned);
                }
                history.push(message);
                continue;
            }
            // Non-A2A admission retained for old/directly-created tasks.
            if history.is_empty() {
                let text = input
                    .get("text")
                    .and_then(Value::as_str)
                    .map(ToOwned::to_owned);
                let media_type = if text.is_some() {
                    "text/plain"
                } else {
                    "application/json"
                };
                history.push(A2aMessage {
                    message_id: format!("{run}-input"),
                    role: "ROLE_USER".to_owned(),
                    parts: vec![Part {
                        data: text.is_none().then(|| input.clone()),
                        text,
                        raw: None,
                        url: None,
                        filename: None,
                        media_type: Some(media_type.to_owned()),
                        metadata: None,
                    }],
                    context_id: case.map(ToOwned::to_owned),
                    task_id: Some(run.to_string()),
                    metadata: None,
                    extensions: Vec::new(),
                    reference_task_ids: Vec::new(),
                });
            }
        }
        let keep_from = history.len().saturating_sub(limit);
        (!history.is_empty()).then(|| history.split_off(keep_from))
    }
}

/// The uncached artifact projection: one strict replay of a completed run.
///
/// Server request paths go through [`A2aServer::artifacts_bounded`], which
/// caches sealed runs and meters `ListTasks`; this stays the raw read for the
/// stream module, whose per-record use is bounded by the stream itself.
pub(super) async fn task_artifacts(
    runtime: &Runtime,
    run: RunId,
    state: TaskState,
) -> Result<Option<Vec<A2aArtifact>>, crate::core::RuntimeError> {
    if state != TaskState::Completed {
        return Ok(None);
    }
    runtime
        .replay(run, crate::runtime::Mode::Strict)
        .await
        .map(|outcome| task_of_outcome(&outcome).artifacts)
}

/// A sealed run's outcome word, as an A2A state.
///
/// The outcome is the same string [`RunStatus::as_str`](crate::runtime::RunStatus::as_str)
/// produces, which is what the executor seals with — so this is [`state_of`]
/// reached through a string, and the two are held to agreement by
/// `a_live_status_and_its_sealed_outcome_agree`.
///
/// The `_` arm is a *wire* decision rather than a modelling shortcut: an A2A
/// client must be told some state, and a word this build cannot interpret is not
/// something it may describe as completed or waiting. It is deliberately **not**
/// how the runtime itself treats an unrecognised outcome — `resume_is_closed`
/// quarantines on one, because refusing to guess is available there and is not
/// available here. The agreement test is what keeps this arm from quietly
/// swallowing a variant somebody added and forgot to map.
pub(super) fn sealed_state(outcome: &str) -> TaskState {
    match outcome {
        "succeeded" => TaskState::Completed,
        "cancelled" => TaskState::Canceled,
        "suspended" => TaskState::InputRequired,
        // Not tasks at all: nobody submitted this plane's record of a sweep or
        // of an operator crossing a tenant boundary. `state_of` decides that
        // and this agrees, which is the direction the test beside it enforces.
        "swept" | "broke-glass" => TaskState::Rejected,
        _ => TaskState::Failed,
    }
}

/// The A2A state of a run, read from the last record of its history.
///
/// Every surface that reports a task's state answers here: `tasks/get`,
/// `tasks/list`, and the event stream a client subscribes to. They are three
/// views of one fact, and three copies of this match would agree until somebody
/// added a record kind or reworded a suspension — after which a client polling
/// and the same client streaming would be told different things about the same
/// run, which is worse than either answer being wrong.
///
/// **The last record, not any record.** A run that waited, was resumed and
/// carried on has a suspension in its history and is not suspended now.
///
/// An empty history has no state to report and is not this function's to
/// invent: the caller decides whether that is a task that does not exist or one
/// whose first record has not landed yet, and those get different answers.
pub(super) fn state_from_history(
    records: &[crate::journal::Record],
) -> Option<(TaskState, String)> {
    let last = records.last()?;
    Some(match last.kind() {
        RecordKind::RunSuspended { reason } => (TaskState::InputRequired, reason.to_string()),
        RecordKind::RunConcluded { outcome, .. } => (sealed_state(outcome), outcome.clone()),
        _ => (TaskState::Working, "running".to_owned()),
    })
}

async fn cancel_task(
    server: &A2aServer,
    headers: &HeaderMap,
    params: CommonParams,
) -> Result<Value, RpcError> {
    let id = task_id(&params)?;
    let caller = server
        .gate(headers, action::TASK_CANCEL, &id.to_string())
        .await?;

    let records = server
        .runtime
        .journal()
        .read(id, 1)
        .await
        .map_err(|_| RpcError::new(code::INTERNAL_ERROR, "the journal could not be read"))?;
    let Some(last) = records.last() else {
        return Err(RpcError::new(
            code::TASK_NOT_FOUND,
            format!("no such task: {id}"),
        ));
    };
    // A sealed run is finished, and A2A has a code for exactly this. Accepting
    // the request and reporting success would tell the caller a completed run
    // is about to stop.
    if let RecordKind::RunConcluded { outcome, .. } = last.kind() {
        return Err(RpcError::new(
            code::TASK_NOT_CANCELABLE,
            format!("this task already finished as '{outcome}'"),
        ));
    }

    server
        .runtime
        .request_cancel(id, &caller.actor, "cancelled over A2A")
        .await
        .map_err(|e| RpcError::new(code::INTERNAL_ERROR, e.to_string()))?;

    // The same resolution every other path uses, from the records already in
    // hand: A2A 1.0 puts `contextId` on every task, and the one place that
    // hard-coded it absent handed a canceling caller a task it could not
    // continue or correlate.
    let case = records
        .iter()
        .find_map(|record| record.body.case.map(|case| case.to_string()));

    // Still `WORKING`, deliberately. The request is durable, and the run stops
    // at its next step boundary — reporting `CANCELED` here would claim it had
    // already stopped and unwound, which is exactly what has not happened yet.
    serde_json::to_value(task_of(
        id,
        TaskState::Working,
        "cancellation requested",
        case,
    ))
    .map_err(|error| RpcError::new(code::INTERNAL_ERROR, error.to_string()))
}

async fn get_extended_card(server: &A2aServer, headers: &HeaderMap) -> Result<Value, RpcError> {
    server
        .gate(headers, action::CARD_EXTENDED, &server.card.name)
        .await?;
    serde_json::to_value(&server.extended)
        .map_err(|e| RpcError::new(code::INTERNAL_ERROR, e.to_string()))
}

fn task_id(params: &CommonParams) -> Result<RunId, RpcError> {
    let Some(raw) = params.id.as_deref() else {
        return Err(RpcError::new(code::INVALID_PARAMS, "`id` is required"));
    };
    RunId::parse(raw).map_err(|_| {
        // Not found rather than invalid params: whether a string is a run id
        // this plane issued is not something a caller should learn from the
        // shape of the refusal.
        RpcError::new(code::TASK_NOT_FOUND, format!("no such task: {raw}"))
    })
}

/// The agent declining, with nothing about *why*.
///
/// The reason is deliberately absent. A denial reason describes the rule that
/// fired, and a rule describes the classification it protects — so a caller who
/// can send messages and read refusals can map the policy by probing it. The
/// operator sees the reason in the journal, where it belongs; the peer sees that
/// it was declined, which is all it can act on anyway.
fn declined(skill: &str) -> A2aMessage {
    A2aMessage {
        message_id: format!("declined-{skill}"),
        role: "ROLE_AGENT".to_owned(),
        parts: vec![Part {
            text: Some("this agent declined the request".to_owned()),
            data: None,
            raw: None,
            url: None,
            filename: None,
            media_type: Some("text/plain".to_owned()),
            metadata: None,
        }],
        context_id: None,
        task_id: None,
        metadata: None,
        extensions: Vec::new(),
        reference_task_ids: Vec::new(),
    }
}

pub(super) fn task_of(run: RunId, state: TaskState, detail: &str, case: Option<String>) -> A2aTask {
    A2aTask {
        id: run.to_string(),
        context_id: case,
        status: TaskStatus {
            state,
            message: Some(A2aMessage {
                message_id: format!("{run}-status"),
                role: "ROLE_AGENT".to_owned(),
                parts: vec![Part {
                    text: Some(detail.to_owned()),
                    data: None,
                    raw: None,
                    url: None,
                    filename: None,
                    media_type: Some("text/plain".to_owned()),
                    metadata: None,
                }],
                context_id: None,
                task_id: Some(run.to_string()),
                metadata: None,
                extensions: Vec::new(),
                reference_task_ids: Vec::new(),
            }),
            timestamp: None,
        },
        artifacts: None,
        history: None,
        metadata: None,
    }
}

fn push_runtime(server: &A2aServer) -> Result<&PushRuntime, RpcError> {
    server.push.as_ref().ok_or_else(push_not_supported_error)
}

fn push_not_supported_error() -> RpcError {
    RpcError::new(
        code::PUSH_NOT_SUPPORTED,
        "this agent does not implement push notifications; its card advertises pushNotifications as false",
    )
}

async fn push_task(server: &A2aServer, raw: Option<&str>) -> Result<RunId, RpcError> {
    let raw = raw.ok_or_else(|| RpcError::new(code::INVALID_PARAMS, "`taskId` is required"))?;
    let task = RunId::parse(raw)
        .map_err(|_| RpcError::new(code::TASK_NOT_FOUND, format!("no such task: {raw}")))?;
    let records = server
        .runtime
        .journal()
        .read(task, 1)
        .await
        .map_err(|_| RpcError::new(code::INTERNAL_ERROR, "the journal could not be read"))?;
    if records.is_empty() {
        return Err(RpcError::new(
            code::TASK_NOT_FOUND,
            format!("no such task: {task}"),
        ));
    }
    Ok(task)
}

fn push_request(params: &CommonParams) -> Result<PushRequest, RpcError> {
    let url = params
        .url
        .clone()
        .ok_or_else(|| RpcError::new(code::INVALID_PARAMS, "`url` is required"))?;
    Ok(PushRequest {
        id: params.id.clone(),
        task_id: params.push_task.clone(),
        url,
        token: params.token.clone(),
        authentication: params.authentication.clone(),
    })
}

fn validate_push_request(server: &A2aServer, request: &PushRequest) -> Result<(), RpcError> {
    let push = push_runtime(server)?;
    request.validate()?;
    let config = request.config(RunId::generate());
    if let Some(authentication) = &config.authentication {
        authentication
            .validate()
            .map_err(|error| RpcError::new(code::INVALID_PARAMS, error.to_string()))?;
    }
    push.transport
        .validate(&config)
        .map_err(|error| RpcError::new(code::INVALID_PARAMS, error.to_string()))
}

async fn validate_inline_push(
    server: &A2aServer,
    headers: &HeaderMap,
    skill: &str,
    request: &PushRequest,
) -> Result<(), RpcError> {
    if request
        .task_id
        .as_deref()
        .is_some_and(|task| !task.is_empty())
    {
        return Err(RpcError::new(
            code::INVALID_PARAMS,
            "taskPushNotificationConfig.taskId must be empty in SendMessage",
        ));
    }
    server
        .gate(headers, action::TASK_PUSH, &format!("new:{skill}"))
        .await?;
    validate_push_request(server, request)
}

async fn register_push(
    server: &A2aServer,
    request: &PushRequest,
    task: RunId,
    next_seq: Seq,
) -> Result<crate::push::PushConfig, RpcError> {
    let push = push_runtime(server)?;
    if request
        .task_id
        .as_deref()
        .is_some_and(|configured| !configured.is_empty() && configured != task.to_string())
    {
        return Err(RpcError::new(
            code::INVALID_PARAMS,
            "push configuration taskId does not match its task",
        ));
    }
    request.validate()?;
    let config = request.config(task);
    if let Some(authentication) = &config.authentication {
        authentication
            .validate()
            .map_err(|error| RpcError::new(code::INVALID_PARAMS, error.to_string()))?;
    }
    push.transport
        .validate(&config)
        .map_err(|error| RpcError::new(code::INVALID_PARAMS, error.to_string()))?;
    push.store
        .put(&config, next_seq)
        .await
        .map_err(|error| RpcError::new(code::INTERNAL_ERROR, error.to_string()))?;
    Ok(config)
}

async fn push_create(
    server: &A2aServer,
    headers: &HeaderMap,
    params: &CommonParams,
) -> Result<Value, RpcError> {
    let resource = params.push_task.as_deref().unwrap_or("push");
    server.gate(headers, action::TASK_PUSH, resource).await?;
    push_runtime(server)?;
    let task = push_task(server, params.push_task.as_deref()).await?;
    let request = push_request(params)?;
    let head = server
        .runtime
        .journal()
        .head(task)
        .await
        .map_err(|error| RpcError::new(code::INTERNAL_ERROR, error.to_string()))?;
    let tail = server
        .runtime
        .journal()
        .read(task, head.seq)
        .await
        .map_err(|error| RpcError::new(code::INTERNAL_ERROR, error.to_string()))?;
    let next_seq = if tail
        .last()
        .is_some_and(|record| matches!(record.kind(), RecordKind::RunConcluded { .. }))
    {
        head.seq
    } else {
        head.seq.saturating_add(1)
    };
    Ok(register_push(server, &request, task, next_seq)
        .await?
        .redacted())
}

async fn push_get(
    server: &A2aServer,
    headers: &HeaderMap,
    params: &CommonParams,
) -> Result<Value, RpcError> {
    let resource = params.push_task.as_deref().unwrap_or("push");
    server.gate(headers, action::TASK_PUSH, resource).await?;
    let push = push_runtime(server)?;
    let task = push_task(server, params.push_task.as_deref()).await?;
    let id = params
        .id
        .as_deref()
        .ok_or_else(|| RpcError::new(code::INVALID_PARAMS, "`id` is required"))?;
    push.store
        .get(task, id)
        .await
        .map_err(|error| RpcError::new(code::INTERNAL_ERROR, error.to_string()))?
        .map(|config| config.redacted())
        .ok_or_else(|| {
            RpcError::new(
                code::TASK_NOT_FOUND,
                format!("no push configuration '{id}' for task {task}"),
            )
        })
}

async fn push_list(
    server: &A2aServer,
    headers: &HeaderMap,
    params: &CommonParams,
) -> Result<Value, RpcError> {
    let resource = params.push_task.as_deref().unwrap_or("push");
    server.gate(headers, action::TASK_PUSH, resource).await?;
    let push = push_runtime(server)?;
    let task = push_task(server, params.push_task.as_deref()).await?;
    let configs = push
        .store
        .list(task)
        .await
        .map_err(|error| RpcError::new(code::INTERNAL_ERROR, error.to_string()))?;
    Ok(json!({
        "configs": configs.iter().map(crate::push::PushConfig::redacted).collect::<Vec<_>>(),
        "nextPageToken": "",
    }))
}

async fn push_delete(
    server: &A2aServer,
    headers: &HeaderMap,
    params: &CommonParams,
) -> Result<Value, RpcError> {
    let resource = params.push_task.as_deref().unwrap_or("push");
    server.gate(headers, action::TASK_PUSH, resource).await?;
    let push = push_runtime(server)?;
    let task = push_task(server, params.push_task.as_deref()).await?;
    let id = params
        .id
        .as_deref()
        .ok_or_else(|| RpcError::new(code::INVALID_PARAMS, "`id` is required"))?;
    push.store
        .delete(task, id)
        .await
        .map_err(|error| RpcError::new(code::INTERNAL_ERROR, error.to_string()))?;
    Ok(json!({}))
}

#[cfg(test)]
mod state_agreement_tests {
    use super::{TaskState, sealed_state, state_of};

    /// The same task must not have two states depending on which path a client took.
    ///
    /// `state_of` answers the caller holding the immediate `SendMessage`
    /// response; `sealed_state` answers `GetTask`, `SubscribeToTask` and every
    /// streamed status update. They read the same run.
    ///
    /// The check runs over the crate's one `RunStatus` list, so adding a variant
    /// fails to compile in `state_of` (the match is exhaustive) and, once
    /// somebody maps it there, fails *here* until `sealed_state` is taught the
    /// same answer. That is the ordering the defect needs: the enum decides, the
    /// string agrees. Unifying them the other way — `state_of` delegating to
    /// `sealed_state` — makes both paths return the `_ => Failed` fallback for a
    /// new variant, with nothing to notice, and that is what this test exists to
    /// stop being reintroduced as a tidy-up.
    #[test]
    fn a_live_status_and_its_sealed_outcome_agree() {
        let statuses = crate::runtime::every_status();
        assert_eq!(
            statuses.len(),
            10,
            "a RunStatus variant was added or removed — decide which A2A state it \
             surfaces as, in `state_of` and in `sealed_state` both"
        );
        for status in &statuses {
            assert_eq!(
                state_of(status),
                sealed_state(status.as_str()),
                "'{}' surfaces as one state live and another once sealed",
                status.as_str()
            );
        }
    }

    /// And the mapping is not one answer for everything.
    ///
    /// Without this, `sealed_state` and `state_of` could both be changed to
    /// return `Failed` unconditionally and the agreement test above would pass
    /// perfectly — every A2A client would see every task as failed.
    #[test]
    fn the_mapping_distinguishes_more_than_failure() {
        let seen: std::collections::BTreeSet<_> = crate::runtime::every_status()
            .iter()
            .map(|status| format!("{:?}", state_of(status)))
            .collect();
        assert!(
            seen.len() >= 4,
            "the run-status mapping collapsed to {seen:?}; a client cannot tell \
             completed from cancelled from waiting"
        );
        assert_eq!(
            state_of(&crate::runtime::RunStatus::Succeeded),
            TaskState::Completed
        );
    }
}