gate4agent 0.4.5

Transport library for CLI AI agents — first tier: Claude Code, Codex, Kimi, Grok. Pipe, PTY, ACP (Agent Client Protocol), and Daemon transports.
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
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
//! ACP-specific message parameter/result structs.
//!
//! These are the typed params used on top of the generic JSON-RPC wire types
//! in [`crate::rpc::message`]. The RPC wire types (`RpcRequest`, `RpcResponse`,
//! `classify_line`) are reused as-is; only the ACP payload shapes live here.

use std::collections::HashMap;

use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::core::types::{
    AgentEvent, AnnouncementInfo, AvailableCommandInfo, AvailableModelInfo, ConfigOptionChoiceInfo,
    ConfigOptionInfo, HookRunResult, McpServerSummary, PlanStep, PlanStepPriority, PlanStepStatus,
    ReasoningEffortInfo, StopReason,
};
use crate::core::types::ConfigOptionKind as CoreConfigOptionKind;

// ---------------------------------------------------------------------------
// Outbound: host → agent
// ---------------------------------------------------------------------------

/// `initialize` request params (host → agent, id=0 per ACP convention).
///
/// Outbound-only: serialized to JSON and sent to the agent subprocess.
#[derive(Debug, Serialize)]
pub struct InitializeParams {
    /// ACP protocol version — must be an integer (1), not a string.
    #[serde(rename = "protocolVersion")]
    pub protocol_version: u32,
    #[serde(rename = "clientCapabilities")]
    pub client_capabilities: ClientCapabilities,
    #[serde(rename = "clientInfo")]
    pub client_info: ClientInfo,
}

/// Capabilities advertised by the host to the agent during `initialize`.
///
/// Outbound-only.
#[derive(Debug, Serialize)]
pub struct ClientCapabilities {
    pub fs: FsCapabilities,
    pub terminal: bool,
}

/// File-system capability flags within [`ClientCapabilities`].
///
/// Outbound-only.
#[derive(Debug, Serialize)]
pub struct FsCapabilities {
    #[serde(rename = "readTextFile")]
    pub read_text_file: bool,
    #[serde(rename = "writeTextFile")]
    pub write_text_file: bool,
}

/// Identifies the host client in the `initialize` request.
///
/// Outbound-only.
#[derive(Debug, Serialize)]
pub struct ClientInfo {
    pub name: &'static str,
    /// Human-readable display name (optional).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<&'static str>,
    pub version: &'static str,
}

/// One `{name, value}` pair on the ACP wire -- the shape ACP v1 mandates
/// for both a stdio server's `env` and an SSE server's `headers` (a plain
/// JSON object is not the wire shape; `{"name":...,"value":...}` array
/// entries are).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct McpServerEnvVar {
    pub name: String,
    pub value: String,
}

/// A single MCP server entry for `session/new`.
///
/// Matches ACP v1's `McpServer` union exactly, confirmed by reading the
/// spec after a live capture showed a downstream ACP client never receiving
/// `tools/list`: **no `"transport"` discriminator, and stdio carries no
/// tag at all** -- `{name, command, args, env}`. An SSE (or, if ever
/// needed, HTTP) entry is what carries an explicit `"type"` field instead
/// (`"sse"` / `"http"`). `#[serde(untagged)]` reproduces this: it tries
/// each variant against the incoming JSON in declaration order, and the
/// two variants never overlap on required fields (`command` vs. `url`), so
/// there is no ambiguity either way.
///
/// `env`/`headers` are wire-mandated arrays of [`McpServerEnvVar`] pairs,
/// not a JSON object -- a stdio entry serialized with a map there is what
/// that downstream client silently dropped before this fix (nameless,
/// wrong-shaped `env`, no `session/new` field the adapter's registration
/// code recognized). Order is insertion order: whatever order the caller
/// passes to [`McpServerConfig::stdio`] / [`McpServerConfig::sse`], not
/// sorted.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum McpServerConfig {
    /// stdio-based MCP server launched as a subprocess.
    Stdio {
        name: String,
        command: String,
        #[serde(default)]
        args: Vec<String>,
        #[serde(default)]
        env: Vec<McpServerEnvVar>,
    },
    /// SSE-based MCP server at a URL.
    Sse {
        #[serde(rename = "type")]
        kind: String,
        name: String,
        url: String,
        #[serde(default)]
        headers: Vec<McpServerEnvVar>,
    },
}

impl McpServerConfig {
    /// Build a stdio entry: `{name, command, args, env: [{name,value}]}`.
    /// `env_pairs`' order is preserved as given, not sorted.
    pub fn stdio(
        name: impl Into<String>,
        command: impl Into<String>,
        args: impl IntoIterator<Item = String>,
        env_pairs: impl IntoIterator<Item = (String, String)>,
    ) -> Self {
        Self::Stdio {
            name: name.into(),
            command: command.into(),
            args: args.into_iter().collect(),
            env: env_pairs
                .into_iter()
                .map(|(name, value)| McpServerEnvVar { name, value })
                .collect(),
        }
    }

    /// Build an SSE entry: `{type:"sse", name, url, headers:
    /// [{name,value}]}`. `header_pairs`' order is preserved as given, not
    /// sorted.
    pub fn sse(
        name: impl Into<String>,
        url: impl Into<String>,
        header_pairs: impl IntoIterator<Item = (String, String)>,
    ) -> Self {
        Self::Sse {
            kind: "sse".to_string(),
            name: name.into(),
            url: url.into(),
            headers: header_pairs
                .into_iter()
                .map(|(name, value)| McpServerEnvVar { name, value })
                .collect(),
        }
    }

    /// The server's registration name -- the only field safe to log:
    /// never `env`/`headers`, which may carry tokens.
    pub fn name(&self) -> &str {
        match self {
            Self::Stdio { name, .. } | Self::Sse { name, .. } => name,
        }
    }
}

/// `session/new` request params. `additional_directories` is the outbound
/// side of the `sessionCapabilities.additionalDirectories` flag every
/// captured agent advertises (`acp-claude.jsonl`, `acp-codex.jsonl`,
/// `acp-kimi.jsonl`) -- UNVERIFIED wire shape: no live capture ever sends
/// a non-empty request, only the capability flag, so the field name
/// follows this file's camelCase convention and the ACP spec's own
/// `mcpServers` precedent (a sibling array of extra paths the agent may
/// access beyond `cwd`), not a captured request payload.
#[derive(Debug, Serialize, Deserialize)]
pub struct SessionNewParams {
    pub cwd: String,
    #[serde(rename = "mcpServers", default)]
    pub mcp_servers: Vec<McpServerConfig>,
    #[serde(rename = "additionalDirectories", default)]
    pub additional_directories: Vec<String>,
}

/// A content block in a `session/prompt` request.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum ContentBlock {
    #[serde(rename = "text")]
    Text { text: String },
}

/// `session/prompt` request params.
#[derive(Debug, Serialize, Deserialize)]
pub struct SessionPromptParams {
    #[serde(rename = "sessionId")]
    pub session_id: String,
    pub prompt: Vec<ContentBlock>,
}

/// Turn-level token usage as reported on a `session/prompt` response,
/// directly under the top-level `usage` key. Verified live on
/// claude-agent-acp 0.72.0 (`turn-claude.jsonl`): camelCase field names,
/// NOT the snake_case `input_tokens`/`output_tokens` this file's
/// [`extract_token_usage`] previously guessed for an unconfirmed
/// "Claude-nested" shape. `cachedReadTokens`/`cachedWriteTokens` are
/// Anthropic prompt-cache bookkeeping (tokens read from vs. written to the
/// cache this turn); a provider with no such concept simply omits them.
/// codex-acp 1.8.0, Kimi Code CLI 0.39.1, and Grok CLI (build channel)
/// send NO `usage` key at all on this response -- every field here is
/// therefore optional, and [`SessionPromptResult::usage`] itself is
/// `None` for those three.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct PromptUsage {
    #[serde(rename = "inputTokens", default)]
    pub input_tokens: Option<u64>,
    #[serde(rename = "outputTokens", default)]
    pub output_tokens: Option<u64>,
    #[serde(rename = "cachedReadTokens", default)]
    pub cached_read_tokens: Option<u64>,
    #[serde(rename = "cachedWriteTokens", default)]
    pub cached_write_tokens: Option<u64>,
    #[serde(rename = "totalTokens", default)]
    pub total_tokens: Option<u64>,
    #[serde(flatten)]
    pub extra: HashMap<String, Value>,
}

/// The `_meta` sidecar on a `session/prompt` response, when the
/// provider's token breakdown rides there instead of a top-level `usage`
/// key. Verified live on Grok CLI, build channel (`turn-grok.jsonl`): the
/// breakdown sits directly on `_meta` -- `sessionId`, `requestId`,
/// `promptId`, `modelId`, `totalTokens`, `inputTokens`, `outputTokens`,
/// `cachedReadTokens`, `reasoningTokens` -- alongside a nested `_meta.
/// usage` carrying the same numbers again plus a per-model breakdown; that
/// nested object is not modeled separately here (nothing in this build
/// needs the per-model split) and lands in `extra` instead of being
/// dropped. claude-agent-acp additionally sends a `_meta.quota` sidecar
/// with none of these field names -- it also lands in `extra`. codex-acp
/// and Kimi Code CLI send no token-bearing `_meta` on this response at
/// all.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct PromptResultMeta {
    #[serde(rename = "sessionId", default)]
    pub session_id: Option<String>,
    #[serde(rename = "requestId", default)]
    pub request_id: Option<String>,
    #[serde(rename = "promptId", default)]
    pub prompt_id: Option<String>,
    #[serde(rename = "modelId", default)]
    pub model_id: Option<String>,
    #[serde(rename = "totalTokens", default)]
    pub total_tokens: Option<u64>,
    #[serde(rename = "inputTokens", default)]
    pub input_tokens: Option<u64>,
    #[serde(rename = "outputTokens", default)]
    pub output_tokens: Option<u64>,
    #[serde(rename = "cachedReadTokens", default)]
    pub cached_read_tokens: Option<u64>,
    #[serde(rename = "reasoningTokens", default)]
    pub reasoning_tokens: Option<u64>,
    #[serde(flatten)]
    pub extra: HashMap<String, Value>,
}

/// `session/prompt` response result (agent → host). `stopReason` is the
/// only field all four captured providers agree on
/// (`turn-{claude,codex,grok,kimi}.jsonl`). Token usage rides on two
/// mutually-exclusive-in-practice locations depending on the provider:
/// Claude nests it under `usage` ([`PromptUsage`]); Grok flattens it onto
/// `_meta` ([`PromptResultMeta`]); Codex and Kimi send neither -- both
/// fields are therefore optional, and `super::session::emit_prompt_result`
/// falls back to [`extract_token_usage`] for any shape neither one
/// matches. Losing this breakdown on prompt-response parsing would leave
/// Grok and Claude turns with zeroed-out token counts even though the
/// numbers are right there on the wire -- this struct exists so neither
/// caller has to re-derive the shape by hand.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct SessionPromptResult {
    #[serde(rename = "stopReason", default)]
    pub stop_reason: Option<StopReason>,
    #[serde(default)]
    pub usage: Option<PromptUsage>,
    #[serde(rename = "_meta", default)]
    pub meta: Option<PromptResultMeta>,
    #[serde(flatten)]
    pub extra: HashMap<String, Value>,
}

/// `session/cancel` notification params (host → agent, no response expected).
#[derive(Debug, Serialize, Deserialize)]
pub struct SessionCancelParams {
    #[serde(rename = "sessionId")]
    pub session_id: String,
}

/// `session/load` request params (host → agent).
#[derive(Debug, Serialize, Deserialize)]
pub struct SessionLoadParams {
    #[serde(rename = "sessionId")]
    pub session_id: String,
}

/// `session/load` response result (agent → host) -- also reused to parse
/// `session/new`'s result, since both carry the same "here is the session
/// I made ready for you" shape per the ACP spec: `sessionId`, and
/// optionally `modes` (current + available session modes),
/// `availableCommands` (the agent's slash-command catalog), `configOptions`
/// (current session configuration -- model, reasoning effort, ...), and
/// `models` (the agent's model catalog -- verified live on codex-acp 1.8.0
/// and Grok CLI 1.0.13, `acp-codex.jsonl`/`acp-grok.jsonl`; previously not
/// parsed at all). Every field beyond `sessionId` defaults to empty so an
/// agent that predates any of them still parses.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct SessionLoadResult {
    #[serde(rename = "sessionId", default)]
    pub session_id: String,
    #[serde(default)]
    pub modes: SessionModeState,
    #[serde(rename = "availableCommands", default)]
    pub available_commands: Vec<AvailableCommand>,
    #[serde(rename = "configOptions", default)]
    pub config_options: Vec<SessionConfigOption>,
    #[serde(default)]
    pub models: SessionModelState,
}

/// One reasoning-effort level offered for a [`SessionModel`]. Verified
/// live on Grok CLI 1.0.13, identical on both `session/new`'s `models`
/// field and the vendor `_x.ai/models/update` notification
/// (`acp-grok.jsonl`).
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ReasoningEffortOption {
    #[serde(default)]
    pub id: String,
    #[serde(default)]
    pub value: String,
    #[serde(default)]
    pub label: String,
    #[serde(default)]
    pub description: Option<String>,
    #[serde(default)]
    pub default: bool,
}

/// A model's `_meta` sidecar, as carried per-entry in Grok's `models`
/// field and `_x.ai/models/update` notification (`acp-grok.jsonl`).
/// Codex's model catalog entries carry no `_meta` at all; every field
/// here defaults to absent so that shape still parses.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SessionModelMeta {
    #[serde(rename = "totalContextTokens", default)]
    pub total_context_tokens: Option<u64>,
    #[serde(rename = "agentType", default)]
    pub agent_type: Option<String>,
    #[serde(rename = "supportsReasoningEffort", default)]
    pub supports_reasoning_effort: Option<bool>,
    #[serde(rename = "reasoningEffort", default)]
    pub reasoning_effort: Option<String>,
    #[serde(rename = "reasoningEfforts", default)]
    pub reasoning_efforts: Vec<ReasoningEffortOption>,
    #[serde(flatten)]
    pub extra: HashMap<String, Value>,
}

/// One model the agent can select for a session. Field names verified
/// live on codex-acp 1.8.0 (`session/new`'s `models.availableModels`) and
/// Grok CLI 1.0.13 (`session/new`'s `models.availableModels` and the
/// vendor `_x.ai/models/update` notification) -- `acp-codex.jsonl`,
/// `acp-grok.jsonl`.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SessionModel {
    #[serde(rename = "modelId", default)]
    pub model_id: String,
    #[serde(default)]
    pub name: String,
    #[serde(default)]
    pub description: Option<String>,
    #[serde(rename = "_meta", default)]
    pub meta: Option<SessionModelMeta>,
    #[serde(flatten)]
    pub extra: HashMap<String, Value>,
}

/// The model catalog block returned by `session/new`/`session/load` and
/// kept current by the vendor `_x.ai/models/update` notification (Grok).
/// Field names verified live on codex-acp 1.8.0 and Grok CLI 1.0.13.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SessionModelState {
    #[serde(rename = "currentModelId", default)]
    pub current_model_id: Option<String>,
    #[serde(rename = "availableModels", default)]
    pub available_models: Vec<SessionModel>,
}

/// `session/list` request params (host → agent). Verified live by direct
/// invocation on claude-agent-acp 0.71.0 and Grok CLI 1.0.13: both an
/// empty object and `{"cwd": "<path>"}` are accepted, and Grok answered
/// identically either way -- `cwd` is an optional filter, not a required
/// field. `#[serde(skip_serializing_if)]` keeps the default call shaped
/// exactly as verified (`{}`) when no filter is requested.
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct SessionListParams {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cwd: Option<String>,
}

/// One session summary entry in a `session/list` response. Verified live
/// by direct invocation on claude-agent-acp 0.71.0 and Grok CLI 1.0.13:
/// both agree on `sessionId`, `cwd`, `updatedAt`; Claude additionally
/// sends `title` (Grok does not), and Grok additionally sends `_meta`
/// (`x.ai/session` with `kind` and `facets` -- `branch`/`cwd`/`gitRoot`/
/// `repo`; Claude does not send `_meta` at all) -- both are therefore
/// optional. `updatedAt` is kept as a raw string rather than parsed: the
/// two providers use different timestamp formats on the same field
/// (Grok `"2026-09-01T19:00:20.154340+00:00"`, six-digit microseconds
/// and an explicit `+00:00` offset; Claude
/// `"2026-09-01T19:02:19.365Z"`, three-digit milliseconds and a `Z`
/// suffix) -- both are valid RFC 3339 but a single fixed-precision parser
/// would reject one of them, so this build keeps the field opaque
/// instead of picking a parser that only works for one provider.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SessionSummary {
    #[serde(rename = "sessionId", default)]
    pub session_id: String,
    #[serde(default)]
    pub cwd: Option<String>,
    /// Claude-only.
    #[serde(default)]
    pub title: Option<String>,
    #[serde(rename = "updatedAt", default)]
    pub updated_at: Option<String>,
    /// Grok-only (`x.ai/session`: `kind`, `facets` -- `branch`, `cwd`,
    /// `gitRoot`, `repo`). Kept as raw JSON: this build has no use for
    /// the facet breakdown today, only for not dropping it.
    #[serde(rename = "_meta", default)]
    pub meta: Option<Value>,
    #[serde(flatten)]
    pub extra: HashMap<String, Value>,
}

/// `session/list` response result (agent → host). Verified live: both
/// claude-agent-acp 0.71.0 and Grok CLI 1.0.13 wrap the summaries in a
/// `sessions` array under this exact key.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SessionListResult {
    #[serde(default)]
    pub sessions: Vec<SessionSummary>,
    #[serde(flatten)]
    pub extra: HashMap<String, Value>,
}

/// `session/close` request params (host → agent). Verified live by
/// direct invocation on claude-agent-acp 0.71.0 and Grok CLI 1.0.13:
/// `{"sessionId": "<id>"}`, matching this file's `{sessionId}`-request
/// convention (`session/cancel`, `session/load`, ...).
#[derive(Debug, Serialize, Deserialize)]
pub struct SessionCloseParams {
    #[serde(rename = "sessionId")]
    pub session_id: String,
}

/// `session/close` response result (agent → host). Verified live: Claude
/// returns an empty object; Grok returns `{"_meta": {"x.ai/
/// closeOutcome": "closed"}}`. Both parse here -- `meta` is `None` for
/// Claude's empty response.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SessionCloseResult {
    #[serde(rename = "_meta", default)]
    pub meta: Option<Value>,
    #[serde(flatten)]
    pub extra: HashMap<String, Value>,
}

/// `session/delete` request params (host → agent) -- UNVERIFIED wire
/// shape (see [`SessionCloseParams`]). Not exercised by any live
/// invocation -- only `session/list`, `session/close`, and `session/fork`
/// were called against a real agent.
#[derive(Debug, Serialize, Deserialize)]
pub struct SessionDeleteParams {
    #[serde(rename = "sessionId")]
    pub session_id: String,
}

/// `session/fork` request params (host → agent). Verified live by direct
/// invocation on claude-agent-acp 0.71.0: calling with only `{"sessionId":
/// "<id>"}` (this file's earlier guess) was REJECTED with a `-32602
/// Invalid params` error naming the missing field explicitly:
/// `{"_errors": [], "cwd": {"_errors": ["Invalid input: expected string,
/// received undefined"]}}}`. `cwd` is therefore required, not optional --
/// forking creates a new session rooted at a working directory, not a
/// bare clone by id, mirroring `session/new`'s own required `cwd`. The
/// success response shape remains UNVERIFIED (the only live call made
/// errored on the missing field before returning one); this file still
/// parses it with [`SessionLoadResult`], the same "here is a session I
/// made ready for you" shape `session/new`/`session/load` use, since
/// nothing contradicts that guess -- just nothing confirms it either.
#[derive(Debug, Serialize, Deserialize)]
pub struct SessionForkParams {
    #[serde(rename = "sessionId")]
    pub session_id: String,
    pub cwd: String,
}

/// `session/set_mode` request params (host → agent) -- switch the agent's
/// current session mode. Permitted at any time per the ACP spec, including
/// mid-generation.
#[derive(Debug, Serialize, Deserialize)]
pub struct SessionSetModeParams {
    #[serde(rename = "sessionId")]
    pub session_id: String,
    #[serde(rename = "modeId")]
    pub mode_id: String,
}

/// `session/set_config_option` request params (host → agent) -- the
/// generic mechanism that supersedes session modes for per-session
/// settings such as model selection and reasoning effort. Field names
/// (`optionId`, `value`) follow this file's camelCase convention and this
/// crate's own [`SessionConfigOption`] naming; unverified against a live
/// agent capture.
#[derive(Debug, Serialize, Deserialize)]
pub struct SessionSetConfigOptionParams {
    #[serde(rename = "sessionId")]
    pub session_id: String,
    #[serde(rename = "optionId")]
    pub option_id: String,
    pub value: Value,
}

// ---------------------------------------------------------------------------
// SessionState — live state assembled at handshake, kept current by
// session/update notifications
// ---------------------------------------------------------------------------

/// Context-window consumption and cost, as last reported by a
/// `usage_update`. Field names here are this crate's own Rust
/// identifiers, decoupled from the wire key names -- see
/// [`SessionUpdate::UsageUpdate`] for what is actually verified live on
/// the wire.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct SessionUsage {
    pub used_tokens: Option<u64>,
    pub context_window: Option<u64>,
    pub cost_amount: Option<f64>,
    pub cost_currency: Option<String>,
}

/// Live ACP session state: modes, command catalog, config options, model
/// catalog, and context usage. Assembled from the `session/new`/`session/
/// load` handshake result via [`SessionState::from_handshake`] and kept
/// current by `current_mode_update`, `available_commands_update`,
/// `config_option_update`, `session_info_update`, and `usage_update`
/// notifications via [`apply_session_update`], plus (for `models`) Grok's
/// vendor `_x.ai/models/update` notification via
/// `super::reader::acp_reader_loop`. Exposed to callers through
/// [`super::session::AcpSession`]'s accessor methods.
#[derive(Debug, Clone, Default)]
pub struct SessionState {
    pub modes: SessionModeState,
    pub available_commands: Vec<AvailableCommand>,
    pub config_options: Vec<SessionConfigOption>,
    pub models: SessionModelState,
    pub title: Option<String>,
    pub usage: Option<SessionUsage>,
}

impl SessionState {
    /// Seed state from a `session/new`/`session/load` handshake result.
    pub(crate) fn from_handshake(result: &SessionLoadResult) -> Self {
        Self {
            modes: result.modes.clone(),
            available_commands: result.available_commands.clone(),
            config_options: result.config_options.clone(),
            models: result.models.clone(),
            title: None,
            usage: None,
        }
    }
}

/// Fold a `session/update` notification into [`SessionState`], for the
/// subset of update kinds that represent durable session state rather
/// than a one-shot stream event. `plan`, message chunks, tool calls, and
/// `stop` do not touch state and are ignored here.
pub(crate) fn apply_session_update(state: &mut SessionState, update: &SessionUpdate) {
    match update {
        SessionUpdate::CurrentModeUpdate { current_mode_id } => {
            state.modes.current_mode_id = Some(current_mode_id.clone());
        }
        SessionUpdate::AvailableCommandsUpdate { available_commands } => {
            state.available_commands = available_commands.clone();
        }
        SessionUpdate::ConfigOptionUpdate { config_options } => {
            state.config_options = config_options.clone();
        }
        SessionUpdate::SessionInfoUpdate { title, .. } => {
            if let Some(title) = title {
                state.title = Some(title.clone());
            }
        }
        SessionUpdate::UsageUpdate { used_tokens, context_window, cost, .. } => {
            state.usage = Some(SessionUsage {
                used_tokens: *used_tokens,
                context_window: *context_window,
                cost_amount: cost.as_ref().and_then(|c| c.amount),
                cost_currency: cost.as_ref().and_then(|c| c.currency.clone()),
            });
        }
        _ => {}
    }
}

// ---------------------------------------------------------------------------
// Inbound: agent → host
// ---------------------------------------------------------------------------

/// `session/update` notification params (agent → host streaming events).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionUpdateParams {
    #[serde(rename = "sessionId")]
    pub session_id: String,
    pub update: SessionUpdate,
}

/// Discriminated union of all known `session/update` payload variants.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "sessionUpdate")]
pub enum SessionUpdate {
    #[serde(rename = "agent_message_chunk")]
    AgentMessageChunk {
        /// A single content block object `{"type": "text", "text": "..."}`
        /// on every real single-turn capture from all four providers,
        /// claude-agent-acp 0.72.0 included (`turn-{claude,codex,grok,
        /// kimi}.jsonl`) -- contradicting this field's earlier "Claude ACP
        /// sends an array" note, which no live capture ever confirmed. The
        /// array-of-content-blocks case is kept as an unverified fallback
        /// (`extract_text_from_content` handles both), not removed --
        /// nothing disproves an agent sending it under different
        /// circumstances, only that none of these four turns did.
        #[serde(default)]
        content: Value,
    },
    #[serde(rename = "agent_thought_chunk")]
    AgentThoughtChunk {
        /// A single content block object `{"type": "text", "text": "..."}`
        /// on every real thought chunk observed -- Grok CLI and Kimi Code
        /// CLI both (`turn-grok.jsonl`, `turn-kimi.jsonl`), the SAME shape
        /// as `agent_message_chunk`, NOT the `{"thought": "..."}` this
        /// field previously guessed and had never confirmed live.
        #[serde(default)]
        content: Value,
    },
    #[serde(rename = "tool_call")]
    ToolCall {
        #[serde(rename = "toolCallId", default)]
        tool_call_id: String,
        #[serde(default)]
        title: String,
        #[serde(default)]
        kind: String,
        #[serde(default)]
        status: String,
        #[serde(rename = "rawInput", default)]
        raw_input: Value,
        #[serde(default)]
        locations: Vec<Value>,
    },
    #[serde(rename = "tool_call_update")]
    ToolCallUpdate {
        #[serde(rename = "toolCallId", default)]
        tool_call_id: String,
        #[serde(default)]
        status: String,
        #[serde(default)]
        content: Vec<Value>,
        /// Claude's own sidecar naming WHY the tool never actually ran --
        /// see [`ToolCallUpdateMeta`]'s own doc comment.
        #[serde(rename = "_meta", default)]
        meta: Option<ToolCallUpdateMeta>,
    },
    #[serde(rename = "stop")]
    Stop {
        #[serde(rename = "stopReason", default)]
        stop_reason: String,
        #[serde(rename = "inputTokens", default)]
        input_tokens: u64,
        #[serde(rename = "outputTokens", default)]
        output_tokens: u64,
        #[serde(default)]
        usage: Option<Value>,
    },
    /// Echo of the user's own prompt content. Verified live on Grok CLI
    /// (`turn-grok.jsonl`): sent as the very first `session/update` of an
    /// ordinary turn, not only when replaying a loaded session's history
    /// as this file previously assumed -- `{"type": "text", "text":
    /// "..."}`, the same content shape as `agent_message_chunk`, plus a
    /// Grok-only `_meta` sidecar (`modelId`, `promptIndex`) that this
    /// variant has no named or `extra` slot for and so drops -- nothing in
    /// this build needs it today.
    #[serde(rename = "user_message_chunk")]
    UserMessageChunk {
        #[serde(default)]
        content: Value,
    },
    /// The agent's execution plan. Always a full snapshot replacing any
    /// plan sent before it, never a delta. NOT OBSERVED in any of the four
    /// providers' single-turn captures (`turn-{claude,codex,grok,
    /// kimi}.jsonl`) -- a plain "reply with one word" turn never produces
    /// a plan, so this shape remains an unverified guess pending a
    /// capture that does exercise planning.
    #[serde(rename = "plan")]
    Plan {
        #[serde(default)]
        entries: Vec<PlanEntry>,
    },
    /// The agent's slash-command catalog changed.
    #[serde(rename = "available_commands_update")]
    AvailableCommandsUpdate {
        #[serde(rename = "availableCommands", default)]
        available_commands: Vec<AvailableCommand>,
    },
    /// The session's active mode changed. NOT OBSERVED in any of the four
    /// providers' single-turn captures (`turn-{claude,codex,grok,
    /// kimi}.jsonl`) -- a plain "reply with one word" turn never switches
    /// mode mid-flight, so this shape remains an unverified guess pending a
    /// capture that does exercise a mode switch.
    #[serde(rename = "current_mode_update")]
    CurrentModeUpdate {
        #[serde(rename = "currentModeId", default)]
        current_mode_id: String,
    },
    /// Session metadata changed (e.g. title). Only the fields that
    /// actually changed are present on the wire; anything not named below
    /// lands in `extra` rather than being dropped. All four providers
    /// disagree on the exact shape, confirmed by direct comparison
    /// (`turn-{claude,codex,grok,kimi}.jsonl`): Grok and Kimi send bare
    /// `{"title": "..."}`; Claude additionally sends `updatedAt` (kept in
    /// `extra`, not modeled -- see [`SessionSummary`] for why this file
    /// does not parse ACP timestamp strings); codex-acp sends
    /// NO `title` at all, only `{"_meta": {"codex": {"threadStatus":
    /// {...}}}}` -- `title: Option<String>` with `#[serde(default)]`
    /// already tolerates that (defaults to `None`), and `extra` keeps the
    /// `_meta` sidecar intact.
    #[serde(rename = "session_info_update")]
    SessionInfoUpdate {
        #[serde(default)]
        title: Option<String>,
        #[serde(flatten)]
        extra: HashMap<String, Value>,
    },
    /// Context-window consumption and, when present, turn cost. Field
    /// names verified live on claude-agent-acp 0.72.0 and Kimi Code CLI
    /// 0.39.1 (`turn-claude.jsonl`, `turn-kimi.jsonl`): the wire keys are
    /// the bare `used`/`size`, NOT the previously guessed camelCase
    /// `usedTokens`/`contextWindow` -- that guess never matched a real
    /// payload, so the context-usage bar silently stayed empty on every
    /// turn. `cost` is real too, but rarer: claude-agent-acp sends it only
    /// on the last `usage_update` of a turn (two earlier ones in the same
    /// turn had no `cost` at all), matching `{"amount", "currency"}`
    /// exactly as this file had guessed; Kimi Code CLI never sends it;
    /// Grok CLI and codex-acp never send a `usage_update` notification at
    /// all -- both report usage on the `session/prompt` response instead
    /// ([`SessionPromptResult`]). `extra` keeps anything that lands under
    /// a different real key name from being silently dropped.
    #[serde(rename = "usage_update")]
    UsageUpdate {
        #[serde(rename = "used", default)]
        used_tokens: Option<u64>,
        #[serde(rename = "size", default)]
        context_window: Option<u64>,
        #[serde(default)]
        cost: Option<UsageCost>,
        #[serde(flatten)]
        extra: HashMap<String, Value>,
    },
    /// The full current set of session configuration options -- the
    /// mechanism that supersedes session modes. Sent whole on every
    /// update, like `plan`.
    #[serde(rename = "config_option_update")]
    ConfigOptionUpdate {
        #[serde(rename = "configOptions", default)]
        config_options: Vec<SessionConfigOption>,
    },
    #[serde(other)]
    Unknown,
}

/// The `_meta` sidecar on a `tool_call_update`, sourced from the Claude
/// Agent SDK's `tool_result_meta` (`claude-agent-acp` src,
/// `docs/gate4agent/research/gate4agent-blocked-action-signals-2026-09-02.md`
/// §1a): `nonExecutionKind` is WHY the tool never actually ran --
/// `"user-rejected"`, `"permission-rule"`, `"interrupted"`, `"cancelled"` --
/// so a client can render the denial/cancellation distinctly from a real
/// tool failure. The exact wire key for a companion user-typed rejection
/// comment is UNCONFIRMED from the research (only "a companion free-text
/// field" is documented, no field name); every plausible spelling is tried
/// here so whichever one a live agent actually sends still surfaces, rather
/// than committing to a guess and silently dropping the others.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ToolCallUpdateMeta {
    #[serde(rename = "nonExecutionKind", default)]
    pub non_execution_kind: Option<String>,
    #[serde(default)]
    pub comment: Option<String>,
    #[serde(rename = "userComment", default)]
    pub user_comment: Option<String>,
    #[serde(rename = "user_comment", default)]
    pub user_comment_snake: Option<String>,
}

impl ToolCallUpdateMeta {
    /// The first user-typed rejection comment found under any of the
    /// plausible wire spellings -- see this type's own doc comment.
    fn comment_text(&self) -> Option<&str> {
        self.comment
            .as_deref()
            .or(self.user_comment.as_deref())
            .or(self.user_comment_snake.as_deref())
    }
}

/// Priority of a single [`PlanEntry`] within a `plan` update.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PlanEntryPriority {
    High,
    Medium,
    Low,
}

/// Status of a single [`PlanEntry`] within a `plan` update.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PlanEntryStatus {
    Pending,
    InProgress,
    Completed,
}

/// One step of the agent's execution plan, as carried in
/// [`SessionUpdate::Plan`].
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PlanEntry {
    pub content: String,
    pub priority: PlanEntryPriority,
    pub status: PlanEntryStatus,
}

/// An input hint attached to an [`AvailableCommand`], e.g.
/// `{"hint": "<file>"}`. The exact shape of this sub-object has not been
/// captured from a live agent; `hint` is read defensively and `extra`
/// keeps anything else intact.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct AvailableCommandInput {
    #[serde(default)]
    pub hint: Option<String>,
    #[serde(flatten)]
    pub extra: HashMap<String, Value>,
}

/// A single slash-style command the agent advertises, either at handshake
/// time (`session/new`/`session/load`'s result) or via
/// `available_commands_update`. `extra` keeps vendor-specific sidecar
/// data intact -- verified live shapes include Codex's `_meta.
/// commandAction` (`/plan`'s config-option wiring) and Grok's `_meta.
/// scope`/`path`/`bareName`/`qualifiedName` (skill-backed commands).
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct AvailableCommand {
    #[serde(default)]
    pub name: String,
    #[serde(default)]
    pub description: String,
    #[serde(default)]
    pub input: Option<AvailableCommandInput>,
    #[serde(flatten)]
    pub extra: HashMap<String, Value>,
}

/// A mode the agent can operate in -- one entry of
/// [`SessionModeState::available_modes`].
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SessionMode {
    #[serde(default)]
    pub id: String,
    #[serde(default)]
    pub name: String,
    #[serde(default)]
    pub description: Option<String>,
}

/// The mode block returned by `session/new`/`session/load` and kept
/// current by `current_mode_update`.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SessionModeState {
    #[serde(rename = "currentModeId", default)]
    pub current_mode_id: Option<String>,
    #[serde(rename = "availableModes", default)]
    pub available_modes: Vec<SessionMode>,
}

/// The kind of a [`SessionConfigOption`] -- `select` (choose one of
/// `options`) or `boolean` (toggle `value`). Falls back to `Unknown` for a
/// kind string a future ACP revision adds that this build does not know
/// yet, matching the [`ToolKind`] tolerance pattern used elsewhere in this
/// file.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum ConfigOptionKind {
    Select,
    Boolean,
    #[serde(other)]
    #[default]
    Unknown,
}

/// One selectable value of a `select`-kind [`SessionConfigOption`]. Field
/// names verified live against `session/new`'s result on
/// claude-agent-acp 0.71.0, codex-acp 1.8.0, and Kimi Code CLI 0.39.1
/// (`acp-claude.jsonl`, `acp-codex.jsonl`, `acp-kimi.jsonl`): the choice's
/// display label is the wire key `"name"`, not `"label"`.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ConfigOptionChoice {
    #[serde(default)]
    pub value: Value,
    #[serde(rename = "name", default)]
    pub label: Option<String>,
    #[serde(flatten)]
    pub extra: HashMap<String, Value>,
}

/// One session configuration setting -- the mechanism that supersedes
/// session modes for things like model selection and reasoning effort.
/// `config_option_update` carries the FULL current set on every update,
/// same as `plan`. Field names verified live against `session/new`'s
/// result on claude-agent-acp 0.71.0, codex-acp 1.8.0, and Kimi Code CLI
/// 0.39.1 (`acp-claude.jsonl`, `acp-codex.jsonl`, `acp-kimi.jsonl`): the
/// kind discriminator is the wire key `"type"` (previously guessed as
/// `"kind"`, which never matched a real payload and silently defaulted
/// every option to `ConfigOptionKind::Unknown`), and the current
/// selection is the wire key `"currentValue"` (previously guessed as
/// `"value"`, which likewise never matched and left every option's value
/// at `Value::Null`). `extra` keeps anything under a different real key
/// name from being silently dropped.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SessionConfigOption {
    // ACP v2 + Grok agent-mode docs use `configId`; older captures used `id`.
    #[serde(default, alias = "configId")]
    pub id: String,
    #[serde(default)]
    pub name: String,
    #[serde(default)]
    pub description: Option<String>,
    #[serde(default)]
    pub category: Option<String>,
    #[serde(rename = "type", default)]
    pub kind: ConfigOptionKind,
    #[serde(rename = "currentValue", default)]
    pub value: Value,
    #[serde(default)]
    pub options: Vec<ConfigOptionChoice>,
    #[serde(flatten)]
    pub extra: HashMap<String, Value>,
}

/// Amount/currency pair attached to a `usage_update`, when the agent
/// reports cost. Field names verified live on claude-agent-acp 0.72.0
/// (`turn-claude.jsonl`, the last `usage_update` of the turn:
/// `{"amount": 0.17858, "currency": "USD"}`). Kimi Code CLI 0.39.1 never
/// sends this sub-object; Grok CLI and codex-acp never send `usage_update`
/// at all.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct UsageCost {
    #[serde(default)]
    pub amount: Option<f64>,
    #[serde(default)]
    pub currency: Option<String>,
    #[serde(flatten)]
    pub extra: HashMap<String, Value>,
}

/// `fs/read_text_file` request params (agent → host).
///
/// `line` (1-based) and `limit` restrict the read to a line window, matching
/// the ACP spec's optional partial-read fields; both default to "whole
/// file" when absent, which is what every agent that predates this feature
/// sends.
#[derive(Debug, Serialize, Deserialize)]
pub struct FsReadParams {
    pub path: String,
    #[serde(rename = "sessionId", default)]
    pub session_id: String,
    #[serde(default)]
    pub line: Option<u32>,
    #[serde(default)]
    pub limit: Option<u32>,
}

/// `fs/write_text_file` request params (agent → host).
#[derive(Debug, Serialize, Deserialize)]
pub struct FsWriteParams {
    pub path: String,
    #[serde(rename = "sessionId", default)]
    pub session_id: String,
    pub content: String,
}

/// A `name`/`value` environment variable entry, as the ACP wire form for
/// `terminal/create`'s `env` uses (an array of pairs, not a JSON object).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EnvVariable {
    pub name: String,
    pub value: String,
}

/// `terminal/create` request params (agent → host).
#[derive(Debug, Serialize, Deserialize)]
pub struct TerminalCreateParams {
    #[serde(rename = "sessionId", default)]
    pub session_id: String,
    pub command: String,
    #[serde(default)]
    pub args: Vec<String>,
    #[serde(default)]
    pub env: Vec<EnvVariable>,
    #[serde(default)]
    pub cwd: Option<String>,
    #[serde(rename = "outputByteLimit", default)]
    pub output_byte_limit: Option<u64>,
}

/// Shared `{sessionId, terminalId}` params for `terminal/output`,
/// `terminal/wait_for_exit`, `terminal/kill`, and `terminal/release`.
#[derive(Debug, Serialize, Deserialize)]
pub struct TerminalIdParams {
    #[serde(rename = "sessionId", default)]
    pub session_id: String,
    #[serde(rename = "terminalId", default)]
    pub terminal_id: String,
}

/// A terminal's exit condition — result of `terminal/wait_for_exit`, and
/// carried inside `terminal/output`'s result once the command has finished.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct TerminalExitStatus {
    #[serde(rename = "exitCode", default)]
    pub exit_code: Option<i32>,
    #[serde(default)]
    pub signal: Option<String>,
}

/// `terminal/output` result (host → agent).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TerminalOutputResult {
    pub output: String,
    pub truncated: bool,
    #[serde(rename = "exitStatus", default, skip_serializing_if = "Option::is_none")]
    pub exit_status: Option<TerminalExitStatus>,
}

/// The kind of operation a tool call performs, carried on
/// [`PermissionToolCall::kind`] so a host policy can decide by intent (e.g.
/// "read" is safe to auto-allow, "execute" is not) without inspecting
/// vendor-specific tool names. `Other` is both the literal wire value for
/// "none of the above" AND the fallback for any kind string a future ACP
/// revision adds that this build does not know yet.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum ToolKind {
    Read,
    Edit,
    Delete,
    Move,
    Search,
    Execute,
    Think,
    Fetch,
    SwitchMode,
    #[serde(other)]
    #[default]
    Other,
}

impl ToolKind {
    /// Whether this kind only observes state rather than changing it or
    /// running arbitrary code — the set a `ReadOnly` host policy auto-allows.
    pub(crate) fn is_read_only(self) -> bool {
        matches!(self, ToolKind::Read | ToolKind::Search | ToolKind::Think | ToolKind::Fetch)
    }
}

/// A file-system location a tool call touches, as carried on
/// [`PermissionToolCall::locations`].
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolCallLocation {
    pub path: String,
    #[serde(default)]
    pub line: Option<u32>,
}

/// The tool-call summary embedded in a `session/request_permission` request
/// — just enough for a host policy to decide, not the full `session/update`
/// tool-call shape. Every field defaults so an agent that omits some of
/// them (or all of them) still parses.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct PermissionToolCall {
    #[serde(rename = "toolCallId", default)]
    pub tool_call_id: String,
    #[serde(default)]
    pub title: String,
    #[serde(default)]
    pub kind: ToolKind,
    #[serde(default)]
    pub locations: Vec<ToolCallLocation>,
    /// Raw tool-specific input the agent attached to this permission
    /// request, when it chose to include one -- e.g. `{"command": "rm -rf
    /// /"}` for an `execute`-kind tool call. The ACP spec does not mandate
    /// this field be present on a permission request the way it is on a
    /// `tool_call` session update; many agents omit it here. Defaults to
    /// `Value::Null`, which the dangerous-command gate
    /// (`super::gate::evaluate_permission_tool_call`) treats as "nothing to
    /// inspect" rather than as an empty/safe command.
    #[serde(rename = "rawInput", default)]
    pub raw_input: Value,
}

/// The four option kinds the ACP spec defines for
/// [`PermissionOption::kind`], plus [`Unknown`](Self::Unknown) for any
/// `kind` string a third-party agent sends that is none of them. An agent
/// is not required to offer all four -- see [`PermissionRequestParams`]
/// and the host policy that selects among whichever subset arrives.
///
/// `Unknown` matters for the same reason `ToolKind::Other` does: without a
/// `#[serde(other)]` catch-all here, ONE option in the offered list with an
/// unfamiliar `kind` string used to fail this enum's `Deserialize`, which
/// failed the whole [`PermissionOption`], which failed the whole
/// `Vec<PermissionOption>`, which failed the whole
/// [`PermissionRequestParams`] -- so a host never even saw the request, let
/// alone the kinds it DID recognise, and every `session/request_permission`
/// call from an adapter that words even one option differently ended up
/// answered `PermissionOutcome::Cancelled` (a refusal) with the actual
/// cause logged nowhere. `Unknown` is never selected by kind preference
/// (`super::host::select_offered_option` only ever matches one of the
/// other four); the only path that can still pick an option shaped like
/// this is the allow-ish name/`optionId` fallback in
/// `super::host::HostPolicy::select_permission_option`, and only when
/// policy prefers allow and none of the four known kinds were offered.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PermissionOptionKind {
    AllowOnce,
    AllowAlways,
    RejectOnce,
    RejectAlways,
    /// Any `kind` string the four variants above don't name. Serializes
    /// back out as the literal `"unknown"` (`rename_all = "snake_case"`
    /// applies to every variant including this one); nothing round-trips
    /// through that string today since a host only ever deserializes this
    /// type off an incoming agent request and never sends its own value
    /// for it.
    #[serde(other)]
    Unknown,
}

/// One option the agent is offering the host for a `session/request_
/// permission` call.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PermissionOption {
    #[serde(rename = "optionId")]
    pub option_id: String,
    pub name: String,
    pub kind: PermissionOptionKind,
}

/// `session/request_permission` request params (agent → host) — the real
/// ACP shape: a `toolCall` summary of what is being asked for, and the
/// concrete `options` the agent is willing to accept a decision from. There
/// is no bare `allowed: bool` on the wire; the host must pick one of
/// `options` (or decline to pick any of them).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PermissionRequestParams {
    #[serde(rename = "sessionId", default)]
    pub session_id: String,
    #[serde(rename = "toolCall", default)]
    pub tool_call: PermissionToolCall,
    #[serde(default)]
    pub options: Vec<PermissionOption>,
}

/// `session/request_permission` result (host → agent) — the host either
/// selects one of the request's `options` by ID, or cancels without
/// selecting any of them (used e.g. when none of the offered options match
/// the host's policy).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "outcome", rename_all = "snake_case")]
pub enum PermissionOutcome {
    Selected {
        #[serde(rename = "optionId")]
        option_id: String,
    },
    Cancelled,
}

// ---------------------------------------------------------------------------
// Agent capabilities returned by `initialize`
// ---------------------------------------------------------------------------

/// Full `initialize` response returned by the agent.
///
/// The ACP spec wraps capabilities under `agentCapabilities`; this struct
/// mirrors the top-level response shape. All fields are `#[serde(default)]`
/// so that we tolerate agents that omit optional fields.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct AgentCapabilities {
    /// Protocol version echoed by the agent (integer, e.g. `1`).
    #[serde(rename = "protocolVersion", default)]
    pub protocol_version: u32,
    /// Agent-specific capability flags.
    #[serde(rename = "agentCapabilities", default)]
    pub agent_capabilities: AgentCapabilityFlags,
    /// Information about the agent binary.
    #[serde(rename = "agentInfo", default)]
    pub agent_info: AgentInfo,
    /// Authentication methods supported by the agent.
    #[serde(rename = "authMethods", default)]
    pub auth_methods: Vec<Value>,
}

/// Flags inside `agentCapabilities`.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct AgentCapabilityFlags {
    #[serde(rename = "loadSession", default)]
    pub load_session: bool,
    /// Per-session lifecycle capabilities. Verified live on
    /// claude-agent-acp 0.71.0, codex-acp 1.8.0, Kimi Code CLI 0.39.1, and
    /// Grok CLI 1.0.13 (`acp-claude.jsonl`, `acp-codex.jsonl`,
    /// `acp-kimi.jsonl`, `acp-grok.jsonl`).
    #[serde(rename = "sessionCapabilities", default)]
    pub session_capabilities: SessionCapabilities,
    /// Remaining capability fields (future-proofing).
    #[serde(flatten)]
    pub extra: std::collections::HashMap<String, Value>,
}

/// The `sessionCapabilities` block inside `agentCapabilities` -- each key
/// present means the agent advertises that lifecycle operation; its value
/// is an (currently always empty) object reserved for future per-
/// capability configuration, so presence/absence of the key is the signal
/// this build reads, not its contents. Verified live: claude-agent-acp
/// 0.71.0 and codex-acp 1.8.0 advertise all seven keys including
/// `subagents`; Kimi Code CLI 0.39.1 advertises six (no `subagents`); Grok
/// CLI 1.0.13 advertises only `list`/`resume`/`close`.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SessionCapabilities {
    #[serde(default)]
    pub list: Option<Value>,
    #[serde(default)]
    pub resume: Option<Value>,
    #[serde(default)]
    pub close: Option<Value>,
    #[serde(default)]
    pub delete: Option<Value>,
    #[serde(default)]
    pub fork: Option<Value>,
    #[serde(rename = "additionalDirectories", default)]
    pub additional_directories: Option<Value>,
    /// Whether the agent may spawn subordinate agent turns ("subagents")
    /// during a session. Verified live as an advertised capability flag on
    /// claude-agent-acp 0.71.0 and codex-acp 1.8.0 -- but neither capture
    /// exercises a full prompt turn, so no subagent lifecycle event or
    /// request shape has been observed on the wire; see
    /// `super::session::AcpSession::supports_subagents` for what this
    /// build can and cannot do with the flag today.
    #[serde(default)]
    pub subagents: Option<Value>,
    #[serde(flatten)]
    pub extra: std::collections::HashMap<String, Value>,
}

/// Agent identity returned in the `initialize` response.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct AgentInfo {
    #[serde(default)]
    pub name: String,
    #[serde(default)]
    pub title: String,
    #[serde(default)]
    pub version: String,
}

// ---------------------------------------------------------------------------
// update_to_event
// ---------------------------------------------------------------------------

/// Extract token counts from a raw ACP response value. This is the
/// generic fallback for shapes that predate the typed
/// [`SessionPromptResult`]/[`PromptUsage`]/[`PromptResultMeta`] parse
/// (`super::session::emit_prompt_result` tries those first); it is also
/// used by the still-unverified `SessionUpdate::Stop` variant, which no
/// live capture has ever exercised.
///
/// Tries multiple known shapes:
/// 1. ACP canonical camelCase: `{"inputTokens": N, "outputTokens": N}`
/// 2. Nested under `usage`, camelCase -- verified live on claude-agent-acp
///    0.72.0 (`turn-claude.jsonl`): `{"usage": {"inputTokens": N,
///    "outputTokens": N}}`.
/// 3. Nested under `usage`, snake_case -- UNVERIFIED, kept from this
///    function's earlier guess; no live capture has ever sent this exact
///    shape, only the Anthropic Messages API's own history-file format
///    (`src/history/claude.rs`), which is a different transport entirely.
/// 4. Stats-nested: `{"stats": {"input_tokens": N, "output_tokens": N}}`
///    -- likewise UNVERIFIED.
///
/// Returns `(0, 0)` if nothing matches.
pub(crate) fn extract_token_usage(v: &Value) -> (u64, u64) {
    // 1. Top-level camelCase (ACP canonical)
    if let (Some(i), Some(o)) = (
        v.get("inputTokens").and_then(|x| x.as_u64()),
        v.get("outputTokens").and_then(|x| x.as_u64()),
    ) {
        return (i, o);
    }

    if let Some(usage) = v.get("usage") {
        // 2. Nested under "usage", camelCase (verified: claude-agent-acp)
        if let (Some(i), Some(o)) = (
            usage.get("inputTokens").and_then(|x| x.as_u64()),
            usage.get("outputTokens").and_then(|x| x.as_u64()),
        ) {
            return (i, o);
        }
        // 3. Nested under "usage", snake_case (unverified)
        if let (Some(i), Some(o)) = (
            usage.get("input_tokens").and_then(|x| x.as_u64()),
            usage.get("output_tokens").and_then(|x| x.as_u64()),
        ) {
            return (i, o);
        }
    }

    // 4. Nested under "stats" (unverified)
    if let Some(stats) = v.get("stats") {
        if let (Some(i), Some(o)) = (
            stats.get("input_tokens").and_then(|x| x.as_u64()),
            stats.get("output_tokens").and_then(|x| x.as_u64()),
        ) {
            return (i, o);
        }
    }

    (0, 0)
}

/// Extract text from a content value that may be:
/// - A single object `{"type": "text", "text": "..."}` (some ACP agents)
/// - An array of content blocks `[{"type": "text", "text": "..."}, ...]` (Claude ACP)
/// - A plain string
fn extract_text_from_content(content: &Value) -> String {
    // Case 1: single object with a "text" field
    if let Some(t) = content.get("text").and_then(|v| v.as_str()) {
        return t.to_owned();
    }
    // Case 2: array of content blocks
    if let Some(arr) = content.as_array() {
        return arr
            .iter()
            .filter_map(|b| b.get("text").and_then(|v| v.as_str()))
            .collect::<Vec<_>>()
            .join("");
    }
    // Case 3: plain string
    if let Some(s) = content.as_str() {
        return s.to_owned();
    }
    String::new()
}

/// Convert `session/update` notification params to zero or more [`AgentEvent`]s.
///
/// Returns a `Vec` because `stop` with reason `end_turn` maps to both
/// `TurnComplete` and `SessionEnd`. Returns an empty vec for unknown update
/// types — callers should emit an `AgentEvent::RpcNotification` passthrough
/// in that case.
pub(crate) fn update_to_event(params: &SessionUpdateParams) -> Vec<AgentEvent> {
    match &params.update {
        SessionUpdate::AgentMessageChunk { content } => {
            let text = extract_text_from_content(content);
            if text.is_empty() {
                vec![]
            } else {
                vec![AgentEvent::Text { text, is_delta: true }]
            }
        }

        SessionUpdate::AgentThoughtChunk { content } => {
            // `{"thought": "..."}` was this file's original guess and is
            // checked first so it still wins if some agent sends it; real
            // Grok CLI and Kimi Code CLI both send the SAME content shape
            // as `agent_message_chunk` instead --
            // `{"type": "text", "text": "..."}` (`turn-grok.jsonl`,
            // `turn-kimi.jsonl`) -- which the `thought`-only lookup below
            // used to miss entirely, silently emitting empty thinking text
            // on every real thought chunk from either provider.
            let text = content
                .get("thought")
                .and_then(|v| v.as_str())
                .map(str::to_owned)
                .unwrap_or_else(|| extract_text_from_content(content));
            vec![AgentEvent::Thinking { text }]
        }

        SessionUpdate::ToolCall { tool_call_id, title, raw_input, .. } => {
            vec![AgentEvent::ToolStart {
                id: tool_call_id.clone(),
                name: title.clone(),
                input: raw_input.clone(),
            }]
        }

        SessionUpdate::ToolCallUpdate { tool_call_id, status, content, meta } => {
            let mut output = content
                .iter()
                .filter_map(|v| v.as_str())
                .collect::<Vec<_>>()
                .join("");
            let non_execution_kind = meta.as_ref().and_then(|m| m.non_execution_kind.clone());
            if let Some(comment) = meta.as_ref().and_then(ToolCallUpdateMeta::comment_text) {
                let comment = crate::utils::truncate_str(
                    comment,
                    gate4agent_types::PROVIDER_EVENT_TEXT_MAX_BYTES,
                );
                if !comment.is_empty() {
                    if !output.is_empty() {
                        output.push('\n');
                    }
                    output.push_str(comment);
                }
            }
            // ACP's own status vocabulary is `pending | in_progress |
            // completed | failed` (this file's `ToolCallStatus`-shaped
            // uses elsewhere) -- a declined/denied call resolves as
            // `"failed"` on every provider surveyed (Codex's codex-acp
            // maps a decline to `ToolCallStatus::Failed` the same way a
            // real execution failure is). `"error"` is kept as a
            // tolerated alias: no live capture has ever sent it, but
            // nothing in the spec forbids a future/vendor agent doing so,
            // and accepting it costs nothing a real `"failed"`/`"error"`
            // provider would notice.
            let is_error = status == "failed" || status == "error";
            vec![AgentEvent::ToolResult {
                id: tool_call_id.clone(),
                output,
                is_error,
                duration_ms: None,
                non_execution_kind,
            }]
        }

        SessionUpdate::Stop { stop_reason, input_tokens, output_tokens, usage } => {
            // Prefer direct fields; fall back to the usage sub-object.
            let (tok_in, tok_out) = if *input_tokens > 0 || *output_tokens > 0 {
                (*input_tokens, *output_tokens)
            } else if let Some(u) = usage {
                extract_token_usage(u)
            } else {
                (0, 0)
            };
            let parsed_stop_reason = StopReason::from_wire_str(stop_reason);
            let is_error = parsed_stop_reason.is_refusal();
            vec![
                AgentEvent::TurnComplete {
                    input_tokens: tok_in,
                    output_tokens: tok_out,
                    cache_read_tokens: 0,
                    cache_write_tokens: 0,
                    reasoning_tokens: 0,
                    context_window: None,
                    is_cumulative: false,
                },
                AgentEvent::SessionEnd {
                    result: stop_reason.clone(),
                    cost_usd: None,
                    is_error,
                    stop_reason: Some(parsed_stop_reason),
                },
            ]
        }

        SessionUpdate::UserMessageChunk { content } => {
            let text = extract_text_from_content(content);
            if text.is_empty() {
                vec![]
            } else {
                vec![AgentEvent::UserMessage { text, is_delta: true }]
            }
        }

        SessionUpdate::Plan { entries } => {
            let steps = entries
                .iter()
                .map(|entry| PlanStep {
                    content: entry.content.clone(),
                    priority: match entry.priority {
                        PlanEntryPriority::High => PlanStepPriority::High,
                        PlanEntryPriority::Medium => PlanStepPriority::Medium,
                        PlanEntryPriority::Low => PlanStepPriority::Low,
                    },
                    status: match entry.status {
                        PlanEntryStatus::Pending => PlanStepStatus::Pending,
                        PlanEntryStatus::InProgress => PlanStepStatus::InProgress,
                        PlanEntryStatus::Completed => PlanStepStatus::Completed,
                    },
                })
                .collect();
            vec![AgentEvent::Plan { steps }]
        }

        SessionUpdate::AvailableCommandsUpdate { available_commands } => {
            let commands = available_commands
                .iter()
                .map(|command| AvailableCommandInfo {
                    name: command.name.clone(),
                    description: command.description.clone(),
                    input_hint: command.input.as_ref().and_then(|input| input.hint.clone()),
                })
                .collect();
            vec![AgentEvent::AvailableCommandsUpdate { commands }]
        }

        SessionUpdate::CurrentModeUpdate { current_mode_id } => {
            vec![AgentEvent::ModeChanged { mode_id: current_mode_id.clone() }]
        }

        SessionUpdate::SessionInfoUpdate { title, .. } => {
            vec![AgentEvent::SessionInfoUpdate { title: title.clone() }]
        }

        SessionUpdate::UsageUpdate { used_tokens, context_window, cost, .. } => {
            vec![AgentEvent::UsageUpdate {
                used_tokens: *used_tokens,
                context_window: *context_window,
                cost_amount: cost.as_ref().and_then(|c| c.amount),
                cost_currency: cost.as_ref().and_then(|c| c.currency.clone()),
            }]
        }

        SessionUpdate::ConfigOptionUpdate { config_options } => {
            let options = config_options
                .iter()
                .map(|option| ConfigOptionInfo {
                    id: option.id.clone(),
                    name: option.name.clone(),
                    description: option.description.clone(),
                    category: option.category.clone(),
                    kind: match option.kind {
                        ConfigOptionKind::Select => CoreConfigOptionKind::Select,
                        ConfigOptionKind::Boolean => CoreConfigOptionKind::Boolean,
                        ConfigOptionKind::Unknown => CoreConfigOptionKind::Unknown,
                    },
                    value: option.value.clone(),
                    choices: option
                        .options
                        .iter()
                        .map(|choice| ConfigOptionChoiceInfo {
                            value: choice.value.clone(),
                            label: choice.label.clone(),
                        })
                        .collect(),
                })
                .collect();
            vec![AgentEvent::ConfigOptionsUpdate { options }]
        }

        SessionUpdate::Unknown => vec![],
    }
}

// ---------------------------------------------------------------------------
// Vendor extensions: Grok's `_x.ai/*` namespace
// ---------------------------------------------------------------------------
//
// xAI's Grok CLI (ACP transport) sends a family of provider-specific
// notifications outside the ACP spec's own method names, all under the
// `_x.ai/` prefix -- captured live from a real `grok agent stdio` run
// (`acp-grok.jsonl`). [`parse_vendor_notification`] is the single entry
// point the reader loop calls for any notification method that is not
// `session/update`; it returns `None` for anything it does not
// recognize -- either a method outside `_x.ai/` entirely, or an
// `_x.ai/*` method this build has never seen, or one whose payload
// failed to parse -- so an unrecognized extension always falls back to
// the generic `AgentEvent::RpcNotification` passthrough rather than
// breaking parsing.

/// `_x.ai/models/update` notification params -- the flat sibling of
/// [`SessionModelState`] (no wrapping `models` key). Verified live on
/// Grok CLI 1.0.13 (`acp-grok.jsonl`).
#[derive(Debug, Clone, Deserialize)]
struct VendorModelsUpdateParams {
    #[serde(rename = "currentModelId", default)]
    current_model_id: Option<String>,
    #[serde(rename = "availableModels", default)]
    available_models: Vec<SessionModel>,
}

/// Status of one hook run inside `_x.ai/session_notification`'s
/// `hook_execution` update. Verified live on Grok CLI 1.0.13.
#[derive(Debug, Clone, Default, Deserialize)]
struct VendorHookStatus {
    #[serde(default)]
    status: String,
    #[serde(rename = "elapsed_ms", default)]
    elapsed_ms: Option<u64>,
    #[serde(default)]
    error: Option<String>,
}

/// One hook run inside `_x.ai/session_notification`'s `hook_execution`
/// update. Verified live on Grok CLI 1.0.13.
#[derive(Debug, Clone, Default, Deserialize)]
struct VendorHookRun {
    #[serde(default)]
    name: String,
    #[serde(default)]
    status: VendorHookStatus,
}

/// `_x.ai/session_notification`'s `update` sub-object -- a discriminated
/// union of the two kinds verified live on Grok CLI 1.0.13
/// (`hook_execution`, `model_changed`). `Unknown` covers any other kind
/// this build has never seen.
#[derive(Debug, Clone, Deserialize)]
#[serde(tag = "sessionUpdate")]
enum VendorSessionNotification {
    #[serde(rename = "hook_execution")]
    HookExecution {
        #[serde(default)]
        event_name: String,
        #[serde(default)]
        runs: Vec<VendorHookRun>,
    },
    #[serde(rename = "model_changed")]
    ModelChanged {
        #[serde(rename = "model_id", default)]
        model_id: String,
        #[serde(rename = "reasoning_effort", default)]
        reasoning_effort: Option<String>,
    },
    #[serde(other)]
    Unknown,
}

/// `_x.ai/session_notification` notification params. Verified live on
/// Grok CLI 1.0.13.
#[derive(Debug, Clone, Deserialize)]
struct VendorSessionNotificationParams {
    update: VendorSessionNotification,
}

/// One entry of `_x.ai/mcp/servers_updated`'s `mcpServers` array.
/// Verified live on Grok CLI 1.0.13.
#[derive(Debug, Clone, Default, Deserialize)]
struct VendorMcpServerEntry {
    #[serde(default)]
    name: String,
    #[serde(default)]
    source: String,
    #[serde(rename = "type", default)]
    transport: String,
}

/// `_x.ai/mcp/servers_updated` notification params. Verified live on
/// Grok CLI 1.0.13.
#[derive(Debug, Clone, Default, Deserialize)]
struct VendorMcpServersUpdatedParams {
    #[serde(rename = "mcpServers", default)]
    mcp_servers: Vec<VendorMcpServerEntry>,
}

/// `_x.ai/mcp/init_progress` notification params. Verified live on Grok
/// CLI 1.0.13.
#[derive(Debug, Clone, Default, Deserialize)]
struct VendorMcpInitProgressParams {
    #[serde(default)]
    total: u32,
    #[serde(default)]
    connected: u32,
}

/// `_x.ai/mcp_initialized` notification params. Verified live on Grok CLI
/// 1.0.13.
#[derive(Debug, Clone, Default, Deserialize)]
struct VendorMcpInitializedParams {
    #[serde(rename = "mcpToolCount", default)]
    mcp_tool_count: u32,
    #[serde(rename = "elapsedMs", default)]
    elapsed_ms: u64,
}

/// One entry of `_x.ai/announcements/update`'s `announcements` array.
/// Verified live on Grok CLI 1.0.13.
#[derive(Debug, Clone, Default, Deserialize)]
struct VendorAnnouncement {
    #[serde(default)]
    id: String,
    #[serde(default)]
    title: Option<String>,
    #[serde(default)]
    message: String,
    #[serde(default)]
    severity: Option<String>,
}

/// `_x.ai/announcements/update` notification params. Verified live on
/// Grok CLI 1.0.13.
#[derive(Debug, Clone, Default, Deserialize)]
struct VendorAnnouncementsUpdateParams {
    #[serde(default)]
    announcements: Vec<VendorAnnouncement>,
}

/// Convert a [`SessionModel`] (the `session/new`/`session/load`/vendor
/// wire shape) into the transport-neutral [`AvailableModelInfo`] carried
/// on [`AgentEvent::ModelsUpdate`].
fn session_model_to_info(model: SessionModel) -> AvailableModelInfo {
    let meta = model.meta.unwrap_or_default();
    AvailableModelInfo {
        model_id: model.model_id,
        name: model.name,
        description: model.description,
        context_tokens: meta.total_context_tokens,
        reasoning_efforts: meta
            .reasoning_efforts
            .into_iter()
            .map(|effort| ReasoningEffortInfo {
                id: effort.id,
                label: effort.label,
                description: effort.description,
                is_default: effort.default,
            })
            .collect(),
    }
}

/// Parse an `_x.ai/*` vendor notification into an [`AgentEvent`],
/// updating `state.models` when the method is `_x.ai/models/update` so
/// `AcpSession::available_models`/`current_model_id` stay current the
/// same way `session/update` keeps the rest of [`SessionState`] current.
/// Returns `None` for a method this build does not recognize -- see this
/// section's module-level doc comment above.
pub(crate) fn parse_vendor_notification(
    state: &mut SessionState,
    method: &str,
    params: &Value,
) -> Option<AgentEvent> {
    match method {
        "_x.ai/models/update" => {
            let parsed: VendorModelsUpdateParams = serde_json::from_value(params.clone()).ok()?;
            state.models = SessionModelState {
                current_model_id: parsed.current_model_id.clone(),
                available_models: parsed.available_models.clone(),
            };
            Some(AgentEvent::ModelsUpdate {
                current_model_id: parsed.current_model_id,
                available_models: parsed
                    .available_models
                    .into_iter()
                    .map(session_model_to_info)
                    .collect(),
            })
        }
        "_x.ai/settings/update" => Some(AgentEvent::SettingsUpdate {
            permission_mode: params
                .get("permission_mode")
                .and_then(Value::as_str)
                .map(str::to_owned),
            auto_permission_mode_enabled: params
                .get("auto_permission_mode_enabled")
                .and_then(Value::as_bool),
            raw: params.clone(),
        }),
        "_x.ai/session_notification" => {
            let parsed: VendorSessionNotificationParams =
                serde_json::from_value(params.clone()).ok()?;
            match parsed.update {
                VendorSessionNotification::HookExecution { event_name, runs } => {
                    Some(AgentEvent::HookExecutionUpdate {
                        event_name,
                        runs: runs
                            .into_iter()
                            .map(|run| HookRunResult {
                                name: run.name,
                                status: run.status.status,
                                elapsed_ms: run.status.elapsed_ms,
                                error: run.status.error,
                            })
                            .collect(),
                    })
                }
                VendorSessionNotification::ModelChanged { model_id, reasoning_effort } => {
                    Some(AgentEvent::ProviderModelChanged { model_id, reasoning_effort })
                }
                VendorSessionNotification::Unknown => None,
            }
        }
        "_x.ai/mcp/servers_updated" => {
            let parsed: VendorMcpServersUpdatedParams =
                serde_json::from_value(params.clone()).ok()?;
            Some(AgentEvent::McpServersUpdate {
                servers: parsed
                    .mcp_servers
                    .into_iter()
                    .map(|entry| McpServerSummary {
                        name: entry.name,
                        source: entry.source,
                        transport: entry.transport,
                    })
                    .collect(),
            })
        }
        "_x.ai/mcp/init_progress" => {
            let parsed: VendorMcpInitProgressParams =
                serde_json::from_value(params.clone()).ok()?;
            Some(AgentEvent::McpInitProgress {
                total: parsed.total,
                connected: parsed.connected,
            })
        }
        "_x.ai/mcp_initialized" => {
            let parsed: VendorMcpInitializedParams =
                serde_json::from_value(params.clone()).ok()?;
            Some(AgentEvent::McpInitialized {
                tool_count: parsed.mcp_tool_count,
                elapsed_ms: parsed.elapsed_ms,
            })
        }
        "_x.ai/announcements/update" => {
            let parsed: VendorAnnouncementsUpdateParams =
                serde_json::from_value(params.clone()).ok()?;
            Some(AgentEvent::AnnouncementsUpdate {
                announcements: parsed
                    .announcements
                    .into_iter()
                    .map(|a| AnnouncementInfo {
                        id: a.id,
                        title: a.title,
                        message: a.message,
                        severity: a.severity,
                    })
                    .collect(),
            })
        }
        _ => None,
    }
}

// ---------------------------------------------------------------------------
// Unit tests
// ---------------------------------------------------------------------------

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

    fn make_update(update: SessionUpdate) -> SessionUpdateParams {
        SessionUpdateParams { session_id: "s1".to_string(), update }
    }

    #[test]
    fn update_to_event_text_delta_array() {
        // Claude ACP: content is an array of content blocks
        let p = make_update(SessionUpdate::AgentMessageChunk {
            content: json!([{"type": "text", "text": "hello"}]),
        });
        let events = update_to_event(&p);
        assert_eq!(events.len(), 1);
        assert!(matches!(&events[0], AgentEvent::Text { text, is_delta: true } if text == "hello"));
    }

    #[test]
    fn update_to_event_text_delta_single_object() {
        // Some ACP agents: content is a single object, not an array
        let p = make_update(SessionUpdate::AgentMessageChunk {
            content: json!({"type": "text", "text": "hello"}),
        });
        let events = update_to_event(&p);
        assert_eq!(events.len(), 1);
        assert!(matches!(&events[0], AgentEvent::Text { text, is_delta: true } if text == "hello"));
    }

    #[test]
    fn update_to_event_text_delta_plain_string() {
        // Fallback: content is a plain string
        let p = make_update(SessionUpdate::AgentMessageChunk {
            content: json!("hello"),
        });
        let events = update_to_event(&p);
        assert_eq!(events.len(), 1);
        assert!(matches!(&events[0], AgentEvent::Text { text, is_delta: true } if text == "hello"));
    }

    #[test]
    fn update_to_event_text_delta_empty_returns_no_events() {
        let p = make_update(SessionUpdate::AgentMessageChunk {
            content: json!(null),
        });
        let events = update_to_event(&p);
        assert!(events.is_empty());
    }

    #[test]
    fn update_to_event_thinking_plain_string() {
        let p = make_update(SessionUpdate::AgentThoughtChunk {
            content: json!("thinking..."),
        });
        let events = update_to_event(&p);
        assert_eq!(events.len(), 1);
        assert!(matches!(&events[0], AgentEvent::Thinking { text } if text == "thinking..."));
    }

    #[test]
    fn update_to_event_thinking_thought_field() {
        // Some ACP agents: thought wrapped in {"thought": "..."}
        let p = make_update(SessionUpdate::AgentThoughtChunk {
            content: json!({"thought": "deep thought"}),
        });
        let events = update_to_event(&p);
        assert_eq!(events.len(), 1);
        assert!(matches!(&events[0], AgentEvent::Thinking { text } if text == "deep thought"));
    }

    #[test]
    fn update_to_event_thinking_grok_verbatim_text_field_not_thought_field() {
        // `turn-grok.jsonl` -- the REAL shape: same content object as
        // `agent_message_chunk`, `{"type": "text", "text": "..."}`. Before
        // this fix, the `{"thought": "..."}`-only lookup missed this
        // entirely and every real Grok thought chunk rendered as empty
        // text.
        let raw = r#"{"sessionId":"01a05e6a-aa4d-7a13-9e9c-2077aa244389","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"The"}}}"#;
        let params: SessionUpdateParams = serde_json::from_str(raw).unwrap();
        let events = update_to_event(&params);
        assert_eq!(events.len(), 1);
        assert!(matches!(&events[0], AgentEvent::Thinking { text } if text == "The"));
    }

    #[test]
    fn update_to_event_thinking_kimi_verbatim_text_field_not_thought_field() {
        // `turn-kimi.jsonl` -- same real shape as Grok's, confirming it is
        // not a Grok-only quirk.
        let raw = r#"{"sessionId":"session_ff1eb29e-0ba7-40aa-b654-bbf327c39463","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"Reply"}}}"#;
        let params: SessionUpdateParams = serde_json::from_str(raw).unwrap();
        let events = update_to_event(&params);
        assert_eq!(events.len(), 1);
        assert!(matches!(&events[0], AgentEvent::Thinking { text } if text == "Reply"));
    }

    #[test]
    fn update_to_event_user_message_chunk_grok_verbatim() {
        // `turn-grok.jsonl` -- the user's own prompt, echoed back as the
        // first `session/update` of the turn. Same content shape as
        // `agent_message_chunk`; the Grok-only `_meta` sidecar
        // (`modelId`, `promptIndex`) is dropped -- this variant has no
        // named or `extra` slot for it, and nothing in this build needs
        // it.
        let raw = r#"{"sessionId":"01a05e6a-aa4d-7a13-9e9c-2077aa244389","update":{"sessionUpdate":"user_message_chunk","content":{"type":"text","text":"Reply with the single word: ok"},"_meta":{"modelId":"grok-4.6","promptIndex":0}}}"#;
        let params: SessionUpdateParams = serde_json::from_str(raw).unwrap();
        let events = update_to_event(&params);
        assert_eq!(events.len(), 1);
        assert!(matches!(
            &events[0],
            AgentEvent::UserMessage { text, is_delta: true } if text == "Reply with the single word: ok"
        ));
    }

    #[test]
    fn update_to_event_agent_message_chunk_claude_verbatim_single_object() {
        // `turn-claude.jsonl` -- single content-block object, NOT an
        // array, contradicting this variant's earlier "Claude ACP sends
        // an array" doc note.
        let raw = r#"{"sessionId":"2a82e7d7-ffa6-4ebf-a424-1bd783ec3457","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"ok"},"messageId":"msg_011CedGLEtEZqvzLu9npuaJo"}}"#;
        let params: SessionUpdateParams = serde_json::from_str(raw).unwrap();
        let events = update_to_event(&params);
        assert_eq!(events.len(), 1);
        assert!(matches!(&events[0], AgentEvent::Text { text, is_delta: true } if text == "ok"));
    }

    #[test]
    fn update_to_event_tool_start() {
        let p = make_update(SessionUpdate::ToolCall {
            tool_call_id: "t1".to_string(),
            title: "bash".to_string(),
            kind: "bash".to_string(),
            status: "pending".to_string(),
            raw_input: json!({"cmd": "ls"}),
            locations: vec![],
        });
        let events = update_to_event(&p);
        assert_eq!(events.len(), 1);
        assert!(
            matches!(&events[0], AgentEvent::ToolStart { id, name, .. } if id == "t1" && name == "bash")
        );
    }

    #[test]
    fn update_to_event_tool_result() {
        let p = make_update(SessionUpdate::ToolCallUpdate {
            tool_call_id: "t1".to_string(),
            status: "done".to_string(),
            content: vec![json!("ok")],
            meta: None,
        });
        let events = update_to_event(&p);
        assert_eq!(events.len(), 1);
        assert!(
            matches!(&events[0], AgentEvent::ToolResult { id, output, is_error, non_execution_kind, .. }
                if id == "t1" && output == "ok" && !is_error && non_execution_kind.is_none())
        );
    }

    #[test]
    fn update_to_event_tool_result_failed_status_is_error() {
        // ACP's own status vocabulary is `pending | in_progress | completed
        // | failed` -- a `"done"`/`"error"`-shaped guess never matches a
        // real provider's `"failed"`. No `_meta` on this update -- a plain
        // execution failure, not a block.
        let p = make_update(SessionUpdate::ToolCallUpdate {
            tool_call_id: "t1".to_string(),
            status: "failed".to_string(),
            content: vec![json!("boom")],
            meta: None,
        });
        let events = update_to_event(&p);
        assert_eq!(events.len(), 1);
        assert!(
            matches!(&events[0], AgentEvent::ToolResult { is_error, non_execution_kind, .. }
                if *is_error && non_execution_kind.is_none())
        );
    }

    #[test]
    fn update_to_event_tool_result_classifier_permission_rule_sample() {
        // The owner's classifier sample, verbatim
        // (`docs/gate4agent/research/gate4agent-blocked-action-signals-2026-09-02.md`
        // appendix), arriving as a `tool_call_update` with
        // `_meta.nonExecutionKind: "permission-rule"` -- the shape
        // claude-agent-acp uses to report a classifier/permission-rule
        // denial.
        let sample = "Permission for this action was denied by the Claude Code auto mode classifier. Reason: Blocked by classifier. If you have other tasks that don't depend on this action, continue working on those.";
        let p = make_update(SessionUpdate::ToolCallUpdate {
            tool_call_id: "t1".to_string(),
            status: "failed".to_string(),
            content: vec![json!(sample)],
            meta: Some(ToolCallUpdateMeta {
                non_execution_kind: Some("permission-rule".to_owned()),
                comment: None,
                user_comment: None,
                user_comment_snake: None,
            }),
        });
        let events = update_to_event(&p);
        assert_eq!(events.len(), 1);
        match &events[0] {
            AgentEvent::ToolResult { is_error, non_execution_kind, output, .. } => {
                assert!(*is_error);
                assert_eq!(non_execution_kind.as_deref(), Some("permission-rule"));
                assert_eq!(output, sample);
            }
            other => panic!("expected ToolResult, got {other:?}"),
        }
    }

    #[test]
    fn update_to_event_stop_emits_two_events() {
        let p = make_update(SessionUpdate::Stop {
            stop_reason: "end_turn".to_string(),
            input_tokens: 0,
            output_tokens: 0,
            usage: None,
        });
        let events = update_to_event(&p);
        assert_eq!(events.len(), 2);
        assert!(matches!(&events[0], AgentEvent::TurnComplete { .. }));
        assert!(matches!(
            &events[1],
            AgentEvent::SessionEnd { is_error: false, stop_reason: Some(StopReason::EndTurn), .. }
        ));
    }

    #[test]
    fn update_to_event_stop_refusal_is_error() {
        let p = make_update(SessionUpdate::Stop {
            stop_reason: "refusal".to_string(),
            input_tokens: 0,
            output_tokens: 0,
            usage: None,
        });
        let events = update_to_event(&p);
        assert_eq!(events.len(), 2);
        assert!(matches!(
            &events[1],
            AgentEvent::SessionEnd { is_error: true, stop_reason: Some(StopReason::Refusal), .. }
        ));
    }

    #[test]
    fn extract_token_usage_acp_canonical() {
        let v = json!({"inputTokens": 10, "outputTokens": 5});
        assert_eq!(extract_token_usage(&v), (10, 5));
    }

    #[test]
    fn extract_token_usage_nested_camel_case_verified_claude_shape() {
        // Verbatim shape from `turn-claude.jsonl` line 9 (the `session/
        // prompt` response's `usage` object): camelCase, not the
        // snake_case this function's "Claude-nested" case originally
        // guessed and never matched a real payload.
        let v = json!({"usage": {"inputTokens": 2, "outputTokens": 4, "cachedReadTokens": 15320, "cachedWriteTokens": 17081, "totalTokens": 32407}});
        assert_eq!(extract_token_usage(&v), (2, 4));
    }

    #[test]
    fn extract_token_usage_nested_snake_case_unverified_fallback() {
        // No live capture has ever sent this exact shape -- see the
        // function's own doc comment. Kept only as a defensive fallback.
        let v = json!({"usage": {"input_tokens": 10, "output_tokens": 5}});
        assert_eq!(extract_token_usage(&v), (10, 5));
    }

    #[test]
    fn extract_token_usage_stats_nested() {
        let v = json!({"stats": {"input_tokens": 10, "output_tokens": 5}});
        assert_eq!(extract_token_usage(&v), (10, 5));
    }

    #[test]
    fn extract_token_usage_missing() {
        let v = json!({});
        assert_eq!(extract_token_usage(&v), (0, 0));
    }

    // -----------------------------------------------------------------------
    // SessionPromptResult -- `session/prompt` response, all four providers
    // -----------------------------------------------------------------------

    #[test]
    fn session_prompt_result_claude_verbatim_usage() {
        // `turn-claude.jsonl` line 9 -- the id=2 result. `stopReason` plus
        // a camelCase `usage` object; `_meta.quota` duplicates the same
        // numbers in a different shape and is not modeled, only kept via
        // `extra`.
        let raw = r#"{"stopReason":"end_turn","usage":{"inputTokens":2,"outputTokens":4,"cachedReadTokens":15320,"cachedWriteTokens":17081,"totalTokens":32407},"_meta":{"quota":{"token_count":{"totalTokens":32407,"inputTokens":2,"cachedInputTokens":15320,"cachedWriteTokens":17081,"outputTokens":4,"reasoningOutputTokens":0},"model_usage":[{"model":"claude-opus-5[1m]","token_count":{"totalTokens":32407,"inputTokens":2,"cachedInputTokens":15320,"cachedWriteTokens":17081,"outputTokens":4,"reasoningOutputTokens":0}}]}}}"#;
        let result: SessionPromptResult = serde_json::from_str(raw).unwrap();
        assert_eq!(result.stop_reason, Some(StopReason::EndTurn));
        let usage = result.usage.expect("claude sends usage");
        assert_eq!(usage.input_tokens, Some(2));
        assert_eq!(usage.output_tokens, Some(4));
        assert_eq!(usage.cached_read_tokens, Some(15320));
        assert_eq!(usage.cached_write_tokens, Some(17081));
        assert_eq!(usage.total_tokens, Some(32407));
        // `_meta` is present on the wire (Claude's own `quota` sidecar),
        // so it parses to `Some` -- but none of its NAMED token fields
        // are populated by `quota` (those are Grok's field names), only
        // `extra`.
        let meta = result.meta.expect("claude sends _meta.quota");
        assert!(meta.total_tokens.is_none());
        assert!(meta.input_tokens.is_none());
        assert!(meta.extra.contains_key("quota"));
    }

    #[test]
    fn session_prompt_result_grok_verbatim_meta() {
        // `turn-grok.jsonl` -- the id=2 result. No top-level `usage`; the
        // breakdown rides directly on `_meta` instead, alongside a
        // duplicate nested `_meta.usage` this build does not model
        // separately (kept intact via `extra`).
        let raw = r#"{"stopReason":"end_turn","_meta":{"sessionId":"01a05e6a-aa4d-7a13-9e9c-2077aa244389","requestId":"97238a1c-461a-4f9a-ba2f-4acc677b762b","promptId":"97238a1c-461a-4f9a-ba2f-4acc677b762b","totalTokens":19885,"modelId":"grok-4.6","inputTokens":19807,"outputTokens":78,"cachedReadTokens":1408,"reasoningTokens":73,"usage":{"inputTokens":19807,"outputTokens":78,"totalTokens":19885,"cachedReadTokens":1408,"cacheCreationTokens":0,"reasoningTokens":73,"modelCalls":1,"apiDurationMs":3284,"costUsdTicks":64549000,"numTurns":1}}}"#;
        let result: SessionPromptResult = serde_json::from_str(raw).unwrap();
        assert_eq!(result.stop_reason, Some(StopReason::EndTurn));
        assert!(result.usage.is_none());
        let meta = result.meta.expect("grok sends _meta");
        assert_eq!(meta.session_id.as_deref(), Some("01a05e6a-aa4d-7a13-9e9c-2077aa244389"));
        assert_eq!(meta.request_id.as_deref(), Some("97238a1c-461a-4f9a-ba2f-4acc677b762b"));
        assert_eq!(meta.prompt_id.as_deref(), Some("97238a1c-461a-4f9a-ba2f-4acc677b762b"));
        assert_eq!(meta.model_id.as_deref(), Some("grok-4.6"));
        assert_eq!(meta.total_tokens, Some(19885));
        assert_eq!(meta.input_tokens, Some(19807));
        assert_eq!(meta.output_tokens, Some(78));
        assert_eq!(meta.cached_read_tokens, Some(1408));
        assert_eq!(meta.reasoning_tokens, Some(73));
        // The nested per-model breakdown must not be silently dropped.
        assert!(meta.extra.contains_key("usage"));
    }

    #[test]
    fn session_prompt_result_kimi_verbatim_bare_stop_reason() {
        // `turn-kimi.jsonl` -- no `usage`, no `_meta` at all.
        let raw = r#"{"stopReason":"end_turn"}"#;
        let result: SessionPromptResult = serde_json::from_str(raw).unwrap();
        assert_eq!(result.stop_reason, Some(StopReason::EndTurn));
        assert!(result.usage.is_none());
        assert!(result.meta.is_none());
    }

    #[test]
    fn session_prompt_result_codex_verbatim_bare_stop_reason() {
        // `turn-codex.jsonl` -- identical bare shape to Kimi's.
        let raw = r#"{"stopReason":"end_turn"}"#;
        let result: SessionPromptResult = serde_json::from_str(raw).unwrap();
        assert_eq!(result.stop_reason, Some(StopReason::EndTurn));
        assert!(result.usage.is_none());
        assert!(result.meta.is_none());
    }

    #[test]
    fn update_to_event_unknown_returns_empty() {
        let p = make_update(SessionUpdate::Unknown);
        let events = update_to_event(&p);
        assert!(events.is_empty());
    }

    #[test]
    fn session_update_params_round_trip() {
        let original = SessionUpdateParams {
            session_id: "abc".to_string(),
            update: SessionUpdate::AgentMessageChunk {
                content: json!([{"type": "text", "text": "hi"}]),
            },
        };
        let serialized = serde_json::to_string(&original).unwrap();
        let deserialized: SessionUpdateParams = serde_json::from_str(&serialized).unwrap();
        assert_eq!(deserialized.session_id, "abc");
        assert!(matches!(
            deserialized.update,
            SessionUpdate::AgentMessageChunk { .. }
        ));
    }

    #[test]
    fn session_update_params_single_object_content_round_trip() {
        // Simulate an ACP agent whose wire format uses a single object, not an array
        let raw = r#"{"sessionId":"s1","update":{"content":{"text":"hello","type":"text"},"sessionUpdate":"agent_message_chunk"}}"#;
        let params: SessionUpdateParams = serde_json::from_str(raw).unwrap();
        let events = update_to_event(&params);
        assert_eq!(events.len(), 1);
        assert!(matches!(&events[0], AgentEvent::Text { text, is_delta: true } if text == "hello"));
    }

    #[test]
    fn initialize_params_serialize_camel_case() {
        let p = InitializeParams {
            protocol_version: 1,
            client_capabilities: ClientCapabilities {
                fs: FsCapabilities { read_text_file: true, write_text_file: true },
                terminal: true,
            },
            client_info: ClientInfo { name: "gate4agent", title: Some("Gate4Agent"), version: "0.2.0" },
        };
        let s = serde_json::to_string(&p).unwrap();
        assert!(s.contains("protocolVersion"), "must use protocolVersion");
        assert!(s.contains("clientInfo"), "must use clientInfo");
        assert!(s.contains("clientCapabilities"), "must include clientCapabilities");
        // protocolVersion must be an integer, not a quoted string
        assert!(s.contains(r#""protocolVersion":1"#), "protocolVersion must be integer 1");
    }

    #[test]
    fn session_new_params_serialize() {
        let p = SessionNewParams {
            cwd: "/home/user".to_string(),
            mcp_servers: vec![],
            additional_directories: vec![],
        };
        let s = serde_json::to_string(&p).unwrap();
        assert!(s.contains("\"cwd\""), "must use cwd");
        assert!(s.contains("\"mcpServers\""), "must use mcpServers");
        assert!(s.contains("\"additionalDirectories\""), "must use additionalDirectories");
    }

    #[test]
    fn session_new_params_carries_additional_directories() {
        let p = SessionNewParams {
            cwd: "/home/user".to_string(),
            mcp_servers: vec![],
            additional_directories: vec!["/home/user/other-repo".to_string()],
        };
        let s = serde_json::to_string(&p).unwrap();
        let decoded: SessionNewParams = serde_json::from_str(&s).unwrap();
        assert_eq!(decoded.additional_directories, vec!["/home/user/other-repo".to_string()]);
    }

    /// The generic MCP-server-overlay door (gate4agent-arc-mailbox-and-task-
    /// layer Slice A(ii)): when a caller populates `mcp_servers` with one
    /// stdio entry, `session/new` carries it in ACP v1's actual wire shape --
    /// `name`, `command`, `args`, and `env` (an array of `{name,value}`
    /// pairs, never a map), and no `"transport"` discriminator at all. This
    /// is the shape a live capture once showed an ACP adapter silently
    /// dropping: a nameless entry with `env` as a JSON object never matched
    /// the adapter's own `McpServer` union, so `tools/list` never ran. An
    /// empty `mcp_servers` (no overlay prepared) still serializes to
    /// `"mcpServers":[]`, exactly as `session_new_params_serialize` above
    /// already pins.
    #[test]
    fn session_new_params_serializes_mcp_server_stdio_entry() {
        let command = "C:\\example\\example-mcp-server.exe";
        let endpoint = "\\\\.\\pipe\\example-mcp-server-s1";
        let p = SessionNewParams {
            cwd: "/home/user".to_string(),
            mcp_servers: vec![McpServerConfig::stdio(
                "example-mcp-server",
                command,
                vec!["--session-proxy".to_string()],
                vec![
                    ("EXAMPLE_SESSION_ENDPOINT".to_string(), endpoint.to_string()),
                    ("EXAMPLE_SESSION_TOKEN".to_string(), "tok-abc".to_string()),
                ],
            )],
            additional_directories: vec![],
        };
        let s = serde_json::to_string(&p).unwrap();
        assert!(s.contains(r#""mcpServers":[{"#), "must carry the one stdio entry");
        assert!(!s.contains("\"transport\""), "ACP v1 stdio has no discriminator field");
        assert!(s.contains(r#""name":"example-mcp-server""#), "must carry the ACP-visible server name");
        assert!(s.contains(&format!("\"command\":{command:?}")));
        assert!(s.contains(r#""args":["--session-proxy"]"#));
        // env is an array of {name,value} pairs, never a map -- this is
        // exactly the shape a bare `contains("EXAMPLE_SESSION_ENDPOINT")`
        // check (the old assertion) could not have caught, because it
        // passes whether env is an object or an array.
        assert!(s.contains(&format!(
            r#""env":[{{"name":"EXAMPLE_SESSION_ENDPOINT","value":{endpoint:?}}},{{"name":"EXAMPLE_SESSION_TOKEN","value":"tok-abc"}}]"#
        )));

        let empty = SessionNewParams {
            cwd: "/home/user".to_string(),
            mcp_servers: vec![],
            additional_directories: vec![],
        };
        let empty_s = serde_json::to_string(&empty).unwrap();
        assert!(empty_s.contains(r#""mcpServers":[]"#), "no overlay means an empty array, not absence");
    }

    #[test]
    fn session_prompt_params_wraps_content_blocks() {
        let p = SessionPromptParams {
            session_id: "s1".to_string(),
            prompt: vec![ContentBlock::Text { text: "hello".to_string() }],
        };
        let s = serde_json::to_string(&p).unwrap();
        assert!(s.contains("\"prompt\""), "must have prompt field");
        assert!(s.contains("\"type\":\"text\""), "content block must have type=text");
        assert!(s.contains("\"text\":\"hello\""), "must have text content");
    }

    #[test]
    fn session_load_params_serialize() {
        let p = SessionLoadParams { session_id: "prior-session-123".to_string() };
        let s = serde_json::to_string(&p).unwrap();
        assert!(s.contains("\"sessionId\""), "must use sessionId");
        assert!(s.contains("prior-session-123"), "must contain the session id value");

        // Round-trip
        let p2: SessionLoadParams = serde_json::from_str(&s).unwrap();
        assert_eq!(p2.session_id, "prior-session-123");
    }

    #[test]
    fn session_load_result_deserialize_with_session_id() {
        let raw = r#"{"sessionId":"new-session-456"}"#;
        let r: SessionLoadResult = serde_json::from_str(raw).unwrap();
        assert_eq!(r.session_id, "new-session-456");
    }

    #[test]
    fn session_load_result_deserialize_without_session_id() {
        // Agent may omit sessionId — should default to empty string
        let raw = r#"{}"#;
        let r: SessionLoadResult = serde_json::from_str(raw).unwrap();
        assert!(r.session_id.is_empty());
    }

    #[test]
    fn mcp_server_config_stdio_serialize() {
        // ACP v1's stdio `McpServer` carries no discriminator at all --
        // `name`, `command`, `args`, `env` land directly on the object.
        let cfg = McpServerConfig::stdio(
            "my-server",
            "my-mcp-server",
            vec!["--port".to_string(), "8080".to_string()],
            std::iter::empty(),
        );
        let s = serde_json::to_string(&cfg).unwrap();
        assert!(!s.contains("\"transport\""), "ACP v1 stdio has no discriminator field");
        assert!(s.contains(r#""name":"my-server""#), "must carry the ACP-visible name");
        assert!(s.contains(r#""command":"my-mcp-server""#), "must contain command");
        assert!(s.contains(r#""env":[]"#), "env is an array even when empty, never a map");
    }

    #[test]
    fn mcp_server_config_sse_serialize() {
        // ACP v1's SSE `McpServer` is the variant that DOES carry a
        // discriminator -- `"type":"sse"` -- plus `name`.
        let cfg = McpServerConfig::sse("my-sse-server", "https://example.com/mcp", std::iter::empty());
        let s = serde_json::to_string(&cfg).unwrap();
        assert!(s.contains(r#""type":"sse""#), "must tag as sse");
        assert!(s.contains(r#""name":"my-sse-server""#), "must carry the ACP-visible name");
        assert!(s.contains("https://example.com/mcp"), "must contain url");
        assert!(s.contains(r#""headers":[]"#), "headers is an array even when empty, never a map");
    }

    #[test]
    fn mcp_server_config_roundtrip() {
        let original = McpServerConfig::stdio(
            "fs-server",
            "npx",
            vec!["-y".to_string(), "@modelcontextprotocol/server-filesystem".to_string()],
            vec![("HOME".to_string(), "/home/user".to_string())],
        );
        let json = serde_json::to_string(&original).unwrap();
        let decoded: McpServerConfig = serde_json::from_str(&json).unwrap();
        match decoded {
            McpServerConfig::Stdio { name, command, args, env } => {
                assert_eq!(name, "fs-server");
                assert_eq!(command, "npx");
                assert_eq!(args, vec!["-y", "@modelcontextprotocol/server-filesystem"]);
                assert_eq!(env.len(), 1);
                assert_eq!(env[0].name, "HOME");
                assert_eq!(env[0].value, "/home/user");
            }
            McpServerConfig::Sse { .. } => panic!("expected Stdio variant"),
        }
    }

    // -----------------------------------------------------------------------
    // session/request_permission — protocol-accurate shape
    // -----------------------------------------------------------------------

    #[test]
    fn permission_request_params_parses_the_real_wire_shape() {
        let raw = r#"{
            "sessionId": "s1",
            "toolCall": {
                "toolCallId": "tc1",
                "title": "Edit config.toml",
                "kind": "edit",
                "locations": [{"path": "/repo/config.toml", "line": 12}]
            },
            "options": [
                {"optionId": "allow-once", "name": "Allow once", "kind": "allow_once"},
                {"optionId": "reject-once", "name": "Reject once", "kind": "reject_once"}
            ]
        }"#;
        let params: PermissionRequestParams = serde_json::from_str(raw).unwrap();
        assert_eq!(params.session_id, "s1");
        assert_eq!(params.tool_call.tool_call_id, "tc1");
        assert_eq!(params.tool_call.kind, ToolKind::Edit);
        assert_eq!(params.tool_call.locations.len(), 1);
        assert_eq!(params.tool_call.locations[0].path, "/repo/config.toml");
        assert_eq!(params.tool_call.locations[0].line, Some(12));
        assert_eq!(params.options.len(), 2);
        assert_eq!(params.options[0].kind, PermissionOptionKind::AllowOnce);
        assert_eq!(params.options[1].kind, PermissionOptionKind::RejectOnce);
    }

    #[test]
    fn permission_request_params_survives_an_agent_missing_reject_always() {
        // Some agents only ever offer allow_once/allow_always/reject_once —
        // no reject_always. The parser must not require all four kinds.
        let raw = r#"{
            "sessionId": "s1",
            "toolCall": {"toolCallId": "tc1", "kind": "execute"},
            "options": [
                {"optionId": "a1", "name": "Allow once", "kind": "allow_once"},
                {"optionId": "a2", "name": "Allow always", "kind": "allow_always"},
                {"optionId": "r1", "name": "Reject once", "kind": "reject_once"}
            ]
        }"#;
        let params: PermissionRequestParams = serde_json::from_str(raw).unwrap();
        assert_eq!(params.options.len(), 3);
        assert!(params
            .options
            .iter()
            .all(|option| option.kind != PermissionOptionKind::RejectAlways));
    }

    #[test]
    fn permission_request_params_tolerates_a_missing_tool_call_and_options() {
        // Defensive parsing: an agent that sends only sessionId still parses,
        // it just carries no usable tool-call detail or options.
        let raw = r#"{"sessionId": "s1"}"#;
        let params: PermissionRequestParams = serde_json::from_str(raw).unwrap();
        assert_eq!(params.tool_call.kind, ToolKind::Other);
        assert!(params.options.is_empty());
    }

    #[test]
    fn permission_request_params_tolerates_an_unknown_option_kind() {
        // Regression: before `PermissionOptionKind::Unknown` existed, one
        // option in the list whose `kind` string was not one of the four
        // known ones failed the WHOLE `PermissionRequestParams` to
        // deserialize, hiding every option the agent DID offer.
        let raw = r#"{
            "sessionId": "s1",
            "toolCall": {"toolCallId": "tc1", "kind": "execute"},
            "options": [
                {"optionId": "always_allow", "name": "Always allow", "kind": "allow_forever"},
                {"optionId": "reject-once", "name": "Reject once", "kind": "reject_once"}
            ]
        }"#;
        let params: PermissionRequestParams = serde_json::from_str(raw).unwrap();
        assert_eq!(params.options.len(), 2);
        assert_eq!(params.options[0].kind, PermissionOptionKind::Unknown);
        assert_eq!(params.options[1].kind, PermissionOptionKind::RejectOnce);
    }

    #[test]
    fn tool_kind_unknown_string_falls_back_to_other() {
        let raw = r#"{"toolCallId": "tc1", "kind": "not-a-real-kind"}"#;
        let tool_call: PermissionToolCall = serde_json::from_str(raw).unwrap();
        assert_eq!(tool_call.kind, ToolKind::Other);
    }

    #[test]
    fn tool_kind_serializes_the_ten_canonical_wire_values() {
        let cases = [
            (ToolKind::Read, "\"read\""),
            (ToolKind::Edit, "\"edit\""),
            (ToolKind::Delete, "\"delete\""),
            (ToolKind::Move, "\"move\""),
            (ToolKind::Search, "\"search\""),
            (ToolKind::Execute, "\"execute\""),
            (ToolKind::Think, "\"think\""),
            (ToolKind::Fetch, "\"fetch\""),
            (ToolKind::SwitchMode, "\"switch_mode\""),
            (ToolKind::Other, "\"other\""),
        ];
        for (kind, expected) in cases {
            assert_eq!(serde_json::to_string(&kind).unwrap(), expected);
        }
    }

    #[test]
    fn tool_kind_switch_mode_round_trips() {
        let raw = r#"{"toolCallId": "tc1", "kind": "switch_mode"}"#;
        let tool_call: PermissionToolCall = serde_json::from_str(raw).unwrap();
        assert_eq!(tool_call.kind, ToolKind::SwitchMode);
        assert!(!tool_call.kind.is_read_only());
    }

    #[test]
    fn permission_outcome_selected_serializes_with_option_id() {
        let outcome = PermissionOutcome::Selected { option_id: "allow-once".to_owned() };
        let s = serde_json::to_string(&outcome).unwrap();
        assert!(s.contains(r#""outcome":"selected""#));
        assert!(s.contains(r#""optionId":"allow-once""#));
    }

    #[test]
    fn permission_outcome_cancelled_serializes_without_an_option_id() {
        let outcome = PermissionOutcome::Cancelled;
        let s = serde_json::to_string(&outcome).unwrap();
        assert_eq!(s, r#"{"outcome":"cancelled"}"#);
    }

    // -----------------------------------------------------------------------
    // terminal/* — protocol-accurate shapes
    // -----------------------------------------------------------------------

    #[test]
    fn terminal_create_params_parses_command_args_and_env_array() {
        let raw = r#"{
            "sessionId": "s1",
            "command": "pytest",
            "args": ["-x"],
            "env": [{"name": "CI", "value": "1"}],
            "cwd": "/repo",
            "outputByteLimit": 4096
        }"#;
        let params: TerminalCreateParams = serde_json::from_str(raw).unwrap();
        assert_eq!(params.command, "pytest");
        assert_eq!(params.args, vec!["-x"]);
        assert_eq!(params.env.len(), 1);
        assert_eq!(params.env[0].name, "CI");
        assert_eq!(params.env[0].value, "1");
        assert_eq!(params.cwd.as_deref(), Some("/repo"));
        assert_eq!(params.output_byte_limit, Some(4096));
    }

    #[test]
    fn terminal_id_params_round_trip() {
        let params = TerminalIdParams {
            session_id: "s1".to_owned(),
            terminal_id: "term-1".to_owned(),
        };
        let s = serde_json::to_string(&params).unwrap();
        assert!(s.contains("\"terminalId\":\"term-1\""));
        let decoded: TerminalIdParams = serde_json::from_str(&s).unwrap();
        assert_eq!(decoded.terminal_id, "term-1");
    }

    #[test]
    fn fs_write_params_parses_content() {
        let raw = r#"{"sessionId": "s1", "path": "/tmp/x.txt", "content": "hello"}"#;
        let params: FsWriteParams = serde_json::from_str(raw).unwrap();
        assert_eq!(params.path, "/tmp/x.txt");
        assert_eq!(params.content, "hello");
    }

    // -----------------------------------------------------------------------
    // session/update — the six kinds this file previously left unparsed
    // -----------------------------------------------------------------------

    #[test]
    fn session_update_user_message_chunk_parses_and_emits_event() {
        let raw = r#"{"sessionId":"s1","update":{"sessionUpdate":"user_message_chunk","content":{"type":"text","text":"hi from the user"}}}"#;
        let params: SessionUpdateParams = serde_json::from_str(raw).unwrap();
        assert!(matches!(params.update, SessionUpdate::UserMessageChunk { .. }));
        let events = update_to_event(&params);
        assert_eq!(events.len(), 1);
        assert!(matches!(
            &events[0],
            AgentEvent::UserMessage { text, is_delta: true } if text == "hi from the user"
        ));
    }

    #[test]
    fn session_update_plan_parses_full_snapshot() {
        let raw = r#"{"sessionId":"s1","update":{
            "sessionUpdate":"plan",
            "entries":[
                {"content":"read the file","priority":"high","status":"completed"},
                {"content":"write the fix","priority":"medium","status":"in_progress"},
                {"content":"run the tests","priority":"low","status":"pending"}
            ]
        }}"#;
        let params: SessionUpdateParams = serde_json::from_str(raw).unwrap();
        let SessionUpdate::Plan { entries } = &params.update else {
            panic!("expected Plan variant");
        };
        assert_eq!(entries.len(), 3);
        assert_eq!(entries[0].priority, PlanEntryPriority::High);
        assert_eq!(entries[0].status, PlanEntryStatus::Completed);
        assert_eq!(entries[1].status, PlanEntryStatus::InProgress);

        let events = update_to_event(&params);
        assert_eq!(events.len(), 1);
        let AgentEvent::Plan { steps } = &events[0] else {
            panic!("expected AgentEvent::Plan");
        };
        assert_eq!(steps.len(), 3);
        assert_eq!(steps[0].content, "read the file");
        assert_eq!(steps[0].priority, PlanStepPriority::High);
        assert_eq!(steps[2].status, PlanStepStatus::Pending);
    }

    #[test]
    fn session_update_available_commands_update_parses() {
        let raw = r#"{"sessionId":"s1","update":{
            "sessionUpdate":"available_commands_update",
            "availableCommands":[
                {"name":"review","description":"Review the diff","input":{"hint":"<file>"}},
                {"name":"explain","description":"Explain the code"}
            ]
        }}"#;
        let params: SessionUpdateParams = serde_json::from_str(raw).unwrap();
        let SessionUpdate::AvailableCommandsUpdate { available_commands } = &params.update else {
            panic!("expected AvailableCommandsUpdate variant");
        };
        assert_eq!(available_commands.len(), 2);
        assert_eq!(available_commands[0].name, "review");
        assert_eq!(
            available_commands[0].input.as_ref().and_then(|i| i.hint.clone()),
            Some("<file>".to_owned())
        );
        assert!(available_commands[1].input.is_none());

        let events = update_to_event(&params);
        let AgentEvent::AvailableCommandsUpdate { commands } = &events[0] else {
            panic!("expected AgentEvent::AvailableCommandsUpdate");
        };
        assert_eq!(commands.len(), 2);
        assert_eq!(commands[0].input_hint.as_deref(), Some("<file>"));
        assert_eq!(commands[1].input_hint, None);
    }

    #[test]
    fn session_update_current_mode_update_parses() {
        let raw = r#"{"sessionId":"s1","update":{"sessionUpdate":"current_mode_update","currentModeId":"architect"}}"#;
        let params: SessionUpdateParams = serde_json::from_str(raw).unwrap();
        assert!(matches!(
            &params.update,
            SessionUpdate::CurrentModeUpdate { current_mode_id } if current_mode_id == "architect"
        ));
        let events = update_to_event(&params);
        assert!(matches!(
            &events[0],
            AgentEvent::ModeChanged { mode_id } if mode_id == "architect"
        ));
    }

    #[test]
    fn session_update_session_info_update_grok_verbatim() {
        // `turn-grok.jsonl` -- bare title, nothing else. (The wire message
        // is wrapped in the usual `{"jsonrpc", "method": "session/update",
        // "params": {...}}` envelope; `params` is what
        // `SessionUpdateParams` deserializes.)
        let raw = r#"{"sessionId":"01a05e6a-aa4d-7a13-9e9c-2077aa244389","update":{"sessionUpdate":"session_info_update","title":"Reply with single word ok"}}"#;
        let params: SessionUpdateParams = serde_json::from_str(raw).unwrap();
        assert!(matches!(
            &params.update,
            SessionUpdate::SessionInfoUpdate { title: Some(t), .. } if t == "Reply with single word ok"
        ));
    }

    #[test]
    fn session_update_session_info_update_claude_verbatim_carries_updated_at_in_extra() {
        // `turn-claude.jsonl` -- title plus `updatedAt`, which this build
        // does not model as a named field (see the variant's doc comment)
        // and must therefore keep in `extra` rather than drop.
        let raw = r#"{"sessionId":"2a82e7d7-ffa6-4ebf-a424-1bd783ec3457","update":{"sessionUpdate":"session_info_update","title":"Reply with 'ok'","updatedAt":"2026-09-01T19:23:20.355Z"}}"#;
        let params: SessionUpdateParams = serde_json::from_str(raw).unwrap();
        let SessionUpdate::SessionInfoUpdate { title, extra } = &params.update else {
            panic!("expected SessionInfoUpdate variant");
        };
        assert_eq!(title.as_deref(), Some("Reply with 'ok'"));
        assert_eq!(
            extra.get("updatedAt").and_then(Value::as_str),
            Some("2026-09-01T19:23:20.355Z")
        );
    }

    #[test]
    fn session_update_session_info_update_kimi_verbatim() {
        // `turn-kimi.jsonl` -- bare title, same shape as Grok's.
        let raw = r#"{"sessionId":"session_ff1eb29e-0ba7-40aa-b654-bbf327c39463","update":{"sessionUpdate":"session_info_update","title":"Reply with the single word: ok"}}"#;
        let params: SessionUpdateParams = serde_json::from_str(raw).unwrap();
        assert!(matches!(
            &params.update,
            SessionUpdate::SessionInfoUpdate { title: Some(t), .. } if t == "Reply with the single word: ok"
        ));
    }

    #[test]
    fn session_update_session_info_update_codex_verbatim_has_no_title_at_all() {
        // `turn-codex.jsonl` -- the one provider that sends this update
        // WITHOUT a title, only a `_meta.codex.threadStatus` sidecar.
        // Parsing must survive it: `title` defaults to `None` and the
        // sidecar lands in `extra`.
        let raw = r#"{"sessionId":"01a05e70-55a1-7010-9c10-79ae25c4f531","update":{"sessionUpdate":"session_info_update","_meta":{"codex":{"threadStatus":{"type":"active","activeFlags":[]}}}}}"#;
        let params: SessionUpdateParams = serde_json::from_str(raw).unwrap();
        let SessionUpdate::SessionInfoUpdate { title, extra } = &params.update else {
            panic!("expected SessionInfoUpdate variant");
        };
        assert!(title.is_none());
        assert!(extra.contains_key("_meta"));
        let events = update_to_event(&params);
        assert!(matches!(&events[0], AgentEvent::SessionInfoUpdate { title: None }));
    }

    #[test]
    fn session_update_usage_update_claude_verbatim_bare() {
        // `turn-claude.jsonl` line 5 -- the first of three `usage_update`s
        // in the turn, no `_meta`, no `cost`. `used`/`size` are the real
        // wire keys; this file previously guessed camelCase
        // `usedTokens`/`contextWindow`, which never matched.
        let raw = r#"{"sessionId":"2a82e7d7-ffa6-4ebf-a424-1bd783ec3457","update":{"sessionUpdate":"usage_update","used":32407,"size":1000000}}"#;
        let params: SessionUpdateParams = serde_json::from_str(raw).unwrap();
        let SessionUpdate::UsageUpdate { used_tokens, context_window, cost, .. } = &params.update
        else {
            panic!("expected UsageUpdate variant");
        };
        assert_eq!(*used_tokens, Some(32407));
        assert_eq!(*context_window, Some(1_000_000));
        assert!(cost.is_none());
    }

    #[test]
    fn session_update_usage_update_claude_verbatim_final_carries_cost() {
        // `turn-claude.jsonl` line 8 -- the LAST `usage_update` of the
        // turn, right before the `session/prompt` response: same
        // `used`/`size`, now with `cost` attached.
        let raw = r#"{"sessionId":"2a82e7d7-ffa6-4ebf-a424-1bd783ec3457","update":{"sessionUpdate":"usage_update","used":32407,"size":1000000,"cost":{"amount":0.17858,"currency":"USD"},"_meta":{"_claude/origin":{"kind":"human"}}}}"#;
        let params: SessionUpdateParams = serde_json::from_str(raw).unwrap();
        let SessionUpdate::UsageUpdate { used_tokens, context_window, cost, .. } = &params.update
        else {
            panic!("expected UsageUpdate variant");
        };
        assert_eq!(*used_tokens, Some(32407));
        assert_eq!(*context_window, Some(1_000_000));
        assert_eq!(cost.as_ref().and_then(|c| c.amount), Some(0.17858));
        assert_eq!(cost.as_ref().and_then(|c| c.currency.clone()), Some("USD".to_owned()));

        let events = update_to_event(&params);
        assert!(matches!(
            &events[0],
            AgentEvent::UsageUpdate {
                used_tokens: Some(32407),
                context_window: Some(1_000_000),
                cost_amount: Some(amount),
                cost_currency: Some(currency),
            } if (*amount - 0.17858).abs() < f64::EPSILON && currency == "USD"
        ));
    }

    #[test]
    fn session_update_usage_update_kimi_verbatim() {
        // `turn-kimi.jsonl` -- same `used`/`size` shape, no `cost`, no
        // `_meta` at all.
        let raw = r#"{"sessionId":"session_ff1eb29e-0ba7-40aa-b654-bbf327c39463","update":{"sessionUpdate":"usage_update","used":23382,"size":1048576}}"#;
        let params: SessionUpdateParams = serde_json::from_str(raw).unwrap();
        let events = update_to_event(&params);
        assert!(matches!(
            &events[0],
            AgentEvent::UsageUpdate {
                used_tokens: Some(23382),
                context_window: Some(1_048_576),
                cost_amount: None,
                cost_currency: None,
            }
        ));
    }

    #[test]
    fn session_update_config_option_update_parses_select_and_boolean() {
        // Per-option field names (`type`, `currentValue`, choice `name`)
        // match the live wire shape verified on `session/new`'s
        // `configOptions` (claude-agent-acp 0.71.0, codex-acp 1.8.0, Kimi
        // Code CLI 0.39.1 -- `acp-claude.jsonl`, `acp-codex.jsonl`,
        // `acp-kimi.jsonl`); the outer `config_option_update` notification
        // wrapper itself is not exercised by any live capture (none of
        // them runs a full prompt turn).
        let raw = r#"{"sessionId":"s1","update":{
            "sessionUpdate":"config_option_update",
            "configOptions":[
                {
                    "id":"model",
                    "name":"Model",
                    "description":"Which model to use",
                    "category":"generation",
                    "type":"select",
                    "currentValue":"opus",
                    "options":[
                        {"value":"opus","name":"Opus"},
                        {"value":"sonnet","name":"Sonnet"}
                    ]
                },
                {
                    "id":"extended-thinking",
                    "name":"Extended thinking",
                    "type":"boolean",
                    "currentValue":true
                }
            ]
        }}"#;
        let params: SessionUpdateParams = serde_json::from_str(raw).unwrap();
        let SessionUpdate::ConfigOptionUpdate { config_options } = &params.update else {
            panic!("expected ConfigOptionUpdate variant");
        };
        assert_eq!(config_options.len(), 2);
        assert_eq!(config_options[0].kind, ConfigOptionKind::Select);
        assert_eq!(config_options[0].options.len(), 2);
        assert_eq!(config_options[1].kind, ConfigOptionKind::Boolean);
        assert_eq!(config_options[1].value, Value::Bool(true));

        let events = update_to_event(&params);
        let AgentEvent::ConfigOptionsUpdate { options } = &events[0] else {
            panic!("expected AgentEvent::ConfigOptionsUpdate");
        };
        assert_eq!(options.len(), 2);
        assert_eq!(options[0].choices.len(), 2);
        assert_eq!(options[0].choices[0].label.as_deref(), Some("Opus"));
    }

    #[test]
    fn session_update_config_option_kind_unknown_string_falls_back() {
        let raw = r#"{"id":"x","name":"X","type":"not-a-real-kind","currentValue":null}"#;
        let option: SessionConfigOption = serde_json::from_str(raw).unwrap();
        assert_eq!(option.kind, ConfigOptionKind::Unknown);
    }


    #[test]
    fn session_config_option_accepts_acp_v2_config_id_alias() {
        let raw = r#"{"configId":"model","name":"Model","type":"select","currentValue":"grok-4.6"}"#;
        let option: SessionConfigOption = serde_json::from_str(raw).unwrap();
        assert_eq!(option.id, "model");
        assert_eq!(option.name, "Model");
        assert_eq!(option.value, Value::String("grok-4.6".to_owned()));
    }

        #[test]
    fn session_config_option_reads_the_live_wire_key_names() {
        // Verbatim shape of one `configOptions` entry from `session/new`'s
        // result on claude-agent-acp 0.71.0 (`acp-claude.jsonl`) -- the
        // discriminator is `"type"`, not `"kind"`, and the current
        // selection is `"currentValue"`, not `"value"`. Before this fix
        // both fields silently defaulted (`kind` -> `Unknown`, `value` ->
        // `Value::Null`) on every real agent response.
        let raw = r#"{
            "id": "mode",
            "name": "Mode",
            "description": "Session permission mode",
            "category": "mode",
            "type": "select",
            "currentValue": "auto",
            "options": [
                {"value": "default", "name": "Manual", "description": "Always ask before making changes"},
                {"value": "auto", "name": "Auto", "description": "Claude handles permission decisions"}
            ]
        }"#;
        let option: SessionConfigOption = serde_json::from_str(raw).unwrap();
        assert_eq!(option.kind, ConfigOptionKind::Select);
        assert_eq!(option.value, Value::String("auto".to_owned()));
        assert_eq!(option.options.len(), 2);
        assert_eq!(option.options[1].label.as_deref(), Some("Auto"));
    }

    #[test]
    fn session_update_unrecognized_future_kind_falls_back_to_unknown_and_events_are_empty() {
        // A `sessionUpdate` tag this build has never heard of must not
        // break parsing -- it must land in the `Unknown` variant, and
        // `update_to_event` must return no events for it (the reader loop
        // then passes it through as a raw `RpcNotification` rather than
        // dropping it -- see `reader::acp_reader_loop`).
        let raw = r#"{"sessionId":"s1","update":{"sessionUpdate":"totally_new_kind_from_the_future","someField":42}}"#;
        let params: SessionUpdateParams = serde_json::from_str(raw).unwrap();
        assert!(matches!(params.update, SessionUpdate::Unknown));
        assert!(update_to_event(&params).is_empty());
    }

    // -----------------------------------------------------------------------
    // session/new & session/load handshake result — modes, commands, config
    // -----------------------------------------------------------------------

    #[test]
    fn session_load_result_parses_modes_commands_and_config_options() {
        let raw = r#"{
            "sessionId":"s1",
            "modes":{
                "currentModeId":"code",
                "availableModes":[
                    {"id":"code","name":"Code"},
                    {"id":"architect","name":"Architect","description":"Plan before editing"}
                ]
            },
            "availableCommands":[
                {"name":"review","description":"Review the diff"}
            ],
            "configOptions":[
                {"id":"model","name":"Model","type":"select","currentValue":"opus"}
            ]
        }"#;
        let result: SessionLoadResult = serde_json::from_str(raw).unwrap();
        assert_eq!(result.session_id, "s1");
        assert_eq!(result.modes.current_mode_id.as_deref(), Some("code"));
        assert_eq!(result.modes.available_modes.len(), 2);
        assert_eq!(result.modes.available_modes[1].id, "architect");
        assert_eq!(result.available_commands.len(), 1);
        assert_eq!(result.config_options.len(), 1);
        assert_eq!(result.config_options[0].id, "model");
        assert_eq!(result.config_options[0].kind, ConfigOptionKind::Select);
        assert_eq!(result.config_options[0].value, Value::String("opus".to_owned()));
        assert!(result.models.available_models.is_empty());
    }

    #[test]
    fn session_load_result_defaults_when_agent_predates_modes_and_commands() {
        let raw = r#"{"sessionId":"s1"}"#;
        let result: SessionLoadResult = serde_json::from_str(raw).unwrap();
        assert!(result.modes.current_mode_id.is_none());
        assert!(result.modes.available_modes.is_empty());
        assert!(result.available_commands.is_empty());
        assert!(result.config_options.is_empty());
        assert!(result.models.current_model_id.is_none());
        assert!(result.models.available_models.is_empty());
    }

    #[test]
    fn session_load_result_parses_the_live_codex_models_field() {
        // Trimmed to two entries from codex-acp 1.8.0's real `session/new`
        // result (`acp-codex.jsonl`) -- Codex's model catalog entries
        // carry no `_meta` at all.
        let raw = r#"{
            "sessionId":"01a05e3a-f474-7c53-9e8e-68b60a606d39",
            "models":{
                "availableModels":[
                    {"modelId":"gpt-5.6-sol[low]","name":"GPT-5.6-Sol (low)","description":"Fast responses with lighter reasoning"},
                    {"modelId":"gpt-5.4-mini[xhigh]","name":"GPT-5.4-Mini (xhigh)","description":"Extra high reasoning depth for complex problems"}
                ],
                "currentModelId":"gpt-5.6-sol[ultra]"
            }
        }"#;
        let result: SessionLoadResult = serde_json::from_str(raw).unwrap();
        assert_eq!(result.models.current_model_id.as_deref(), Some("gpt-5.6-sol[ultra]"));
        assert_eq!(result.models.available_models.len(), 2);
        assert_eq!(result.models.available_models[0].model_id, "gpt-5.6-sol[low]");
        assert!(result.models.available_models[0].meta.is_none());
    }

    #[test]
    fn session_load_result_parses_the_live_grok_models_field_with_reasoning_efforts() {
        // Verbatim from Grok CLI 1.0.13's real `session/new` result
        // (`acp-grok.jsonl`), trimmed to one model's `_meta` block.
        let raw = r#"{
            "sessionId":"01a05e41-1437-7231-9625-5fb30b8a02cd",
            "models":{
                "currentModelId":"grok-4.6",
                "availableModels":[
                    {
                        "modelId":"grok-4.6",
                        "name":"Grok 4.6",
                        "description":"SpaceXAI's latest frontier model",
                        "_meta":{
                            "totalContextTokens":500000,
                            "agentType":"grok-build-plan",
                            "supportsReasoningEffort":true,
                            "reasoningEffort":"high",
                            "reasoningEfforts":[
                                {"id":"xhigh","value":"xhigh","label":"Extra High Effort","description":"Highest effort and reasoning level","default":false},
                                {"id":"high","value":"high","label":"High Effort","description":"Higher implementation quality with extensive reasoning","default":true}
                            ]
                        }
                    }
                ]
            }
        }"#;
        let result: SessionLoadResult = serde_json::from_str(raw).unwrap();
        assert_eq!(result.models.current_model_id.as_deref(), Some("grok-4.6"));
        let model = &result.models.available_models[0];
        assert_eq!(model.model_id, "grok-4.6");
        let meta = model.meta.as_ref().expect("grok models carry _meta");
        assert_eq!(meta.total_context_tokens, Some(500_000));
        assert_eq!(meta.reasoning_efforts.len(), 2);
        assert_eq!(meta.reasoning_efforts[1].id, "high");
        assert!(meta.reasoning_efforts[1].default);
    }

    #[test]
    fn session_state_from_handshake_seeds_modes_commands_and_config_options() {
        let raw = r#"{
            "sessionId":"s1",
            "modes":{"currentModeId":"code","availableModes":[{"id":"code","name":"Code"}]},
            "availableCommands":[{"name":"review","description":"Review the diff"}],
            "configOptions":[{"id":"model","name":"Model","type":"select","currentValue":"opus"}],
            "models":{"currentModelId":"grok-4.6","availableModels":[{"modelId":"grok-4.6","name":"Grok 4.6"}]}
        }"#;
        let result: SessionLoadResult = serde_json::from_str(raw).unwrap();
        let state = SessionState::from_handshake(&result);
        assert_eq!(state.modes.current_mode_id.as_deref(), Some("code"));
        assert_eq!(state.available_commands.len(), 1);
        assert_eq!(state.config_options.len(), 1);
        assert_eq!(state.models.current_model_id.as_deref(), Some("grok-4.6"));
        assert_eq!(state.models.available_models.len(), 1);
        assert!(state.title.is_none());
        assert!(state.usage.is_none());
    }

    // -----------------------------------------------------------------------
    // apply_session_update — SessionState kept current by *_update
    // -----------------------------------------------------------------------

    #[test]
    fn apply_session_update_sets_current_mode_id() {
        let mut state = SessionState::default();
        apply_session_update(
            &mut state,
            &SessionUpdate::CurrentModeUpdate { current_mode_id: "architect".to_owned() },
        );
        assert_eq!(state.modes.current_mode_id.as_deref(), Some("architect"));
    }

    #[test]
    fn apply_session_update_replaces_available_commands() {
        let mut state = SessionState::default();
        state.available_commands.push(AvailableCommand {
            name: "stale".to_owned(),
            description: String::new(),
            input: None,
            extra: HashMap::new(),
        });
        let fresh = vec![AvailableCommand {
            name: "review".to_owned(),
            description: "Review the diff".to_owned(),
            input: None,
            extra: HashMap::new(),
        }];
        apply_session_update(
            &mut state,
            &SessionUpdate::AvailableCommandsUpdate { available_commands: fresh.clone() },
        );
        assert_eq!(state.available_commands.len(), 1);
        assert_eq!(state.available_commands[0].name, "review");
    }

    #[test]
    fn apply_session_update_replaces_config_options_wholesale() {
        let mut state = SessionState::default();
        let options = vec![SessionConfigOption {
            id: "model".to_owned(),
            name: "Model".to_owned(),
            kind: ConfigOptionKind::Select,
            value: Value::String("opus".to_owned()),
            ..Default::default()
        }];
        apply_session_update(
            &mut state,
            &SessionUpdate::ConfigOptionUpdate { config_options: options },
        );
        assert_eq!(state.config_options.len(), 1);
        assert_eq!(state.config_options[0].id, "model");
    }

    #[test]
    fn apply_session_update_sets_title_only_when_present() {
        let mut state = SessionState::default();
        apply_session_update(
            &mut state,
            &SessionUpdate::SessionInfoUpdate { title: None, extra: HashMap::new() },
        );
        assert!(state.title.is_none());

        apply_session_update(
            &mut state,
            &SessionUpdate::SessionInfoUpdate {
                title: Some("New title".to_owned()),
                extra: HashMap::new(),
            },
        );
        assert_eq!(state.title.as_deref(), Some("New title"));
    }

    #[test]
    fn apply_session_update_sets_usage() {
        let mut state = SessionState::default();
        apply_session_update(
            &mut state,
            &SessionUpdate::UsageUpdate {
                used_tokens: Some(500),
                context_window: Some(200_000),
                cost: Some(UsageCost {
                    amount: Some(1.5),
                    currency: Some("USD".to_owned()),
                    extra: HashMap::new(),
                }),
                extra: HashMap::new(),
            },
        );
        let usage = state.usage.expect("usage must be set");
        assert_eq!(usage.used_tokens, Some(500));
        assert_eq!(usage.context_window, Some(200_000));
        assert_eq!(usage.cost_amount, Some(1.5));
        assert_eq!(usage.cost_currency.as_deref(), Some("USD"));
    }

    #[test]
    fn apply_session_update_ignores_stream_only_updates() {
        let mut state = SessionState::default();
        let before = state.clone();
        apply_session_update(&mut state, &SessionUpdate::Plan { entries: vec![] });
        apply_session_update(
            &mut state,
            &SessionUpdate::Stop {
                stop_reason: "end_turn".to_owned(),
                input_tokens: 0,
                output_tokens: 0,
                usage: None,
            },
        );
        assert_eq!(before.modes.current_mode_id, state.modes.current_mode_id);
        assert!(state.title.is_none());
        assert!(state.usage.is_none());
    }

    // -----------------------------------------------------------------------
    // session/set_mode & session/set_config_option — new outbound methods
    // -----------------------------------------------------------------------

    #[test]
    fn session_set_mode_params_serialize() {
        let params = SessionSetModeParams {
            session_id: "s1".to_owned(),
            mode_id: "architect".to_owned(),
        };
        let s = serde_json::to_string(&params).unwrap();
        assert!(s.contains("\"sessionId\":\"s1\""));
        assert!(s.contains("\"modeId\":\"architect\""));
    }

    #[test]
    fn session_set_config_option_params_serialize() {
        let params = SessionSetConfigOptionParams {
            session_id: "s1".to_owned(),
            option_id: "model".to_owned(),
            value: Value::String("sonnet".to_owned()),
        };
        let s = serde_json::to_string(&params).unwrap();
        assert!(s.contains("\"sessionId\":\"s1\""));
        assert!(s.contains("\"optionId\":\"model\""));
        assert!(s.contains("\"value\":\"sonnet\""));
    }

    // -----------------------------------------------------------------------
    // sessionCapabilities — verified live against the initialize response
    // -----------------------------------------------------------------------

    #[test]
    fn session_capabilities_parses_the_live_claude_and_codex_shape() {
        // Verbatim `agentCapabilities.sessionCapabilities` from
        // claude-agent-acp 0.71.0 and codex-acp 1.8.0 (`acp-claude.jsonl`,
        // `acp-codex.jsonl`): all seven keys present, including `subagents`.
        let raw = r#"{
            "additionalDirectories": {},
            "close": {},
            "delete": {},
            "fork": {},
            "list": {},
            "resume": {},
            "subagents": {}
        }"#;
        let caps: SessionCapabilities = serde_json::from_str(raw).unwrap();
        assert!(caps.list.is_some());
        assert!(caps.resume.is_some());
        assert!(caps.close.is_some());
        assert!(caps.delete.is_some());
        assert!(caps.fork.is_some());
        assert!(caps.additional_directories.is_some());
        assert!(caps.subagents.is_some());
    }

    #[test]
    fn session_capabilities_parses_the_live_kimi_shape_without_subagents() {
        // Verbatim from Kimi Code CLI 0.39.1 (`acp-kimi.jsonl`): six keys,
        // no `subagents`.
        let raw = r#"{
            "list": {},
            "resume": {},
            "close": {},
            "delete": {},
            "fork": {},
            "additionalDirectories": {}
        }"#;
        let caps: SessionCapabilities = serde_json::from_str(raw).unwrap();
        assert!(caps.fork.is_some());
        assert!(caps.subagents.is_none());
    }

    #[test]
    fn session_capabilities_parses_the_live_grok_shape_with_only_three_keys() {
        // Verbatim from Grok CLI 1.0.13 (`acp-grok.jsonl`): only
        // `list`/`resume`/`close` -- no `delete`, `fork`,
        // `additionalDirectories`, or `subagents`.
        let raw = r#"{"list": {}, "resume": {}, "close": {}}"#;
        let caps: SessionCapabilities = serde_json::from_str(raw).unwrap();
        assert!(caps.list.is_some());
        assert!(caps.resume.is_some());
        assert!(caps.close.is_some());
        assert!(caps.delete.is_none());
        assert!(caps.fork.is_none());
        assert!(caps.additional_directories.is_none());
        assert!(caps.subagents.is_none());
    }

    #[test]
    fn agent_capability_flags_parses_session_capabilities_nested_under_the_live_key() {
        let raw = r#"{
            "loadSession": true,
            "sessionCapabilities": {"list": {}, "resume": {}, "close": {}, "subagents": {}}
        }"#;
        let flags: AgentCapabilityFlags = serde_json::from_str(raw).unwrap();
        assert!(flags.load_session);
        assert!(flags.session_capabilities.list.is_some());
        assert!(flags.session_capabilities.subagents.is_some());
    }

    // -----------------------------------------------------------------------
    // session/list, session/close, session/delete, session/fork — outbound,
    // verified by direct live invocation on claude-agent-acp 0.71.0 and
    // Grok CLI 1.0.13 (`session/delete` was NOT exercised and stays
    // UNVERIFIED, unchanged from the earlier guess).
    // -----------------------------------------------------------------------

    #[test]
    fn session_list_params_serialize_with_no_filter_matches_the_call_that_was_actually_made() {
        // Verified: an empty object is accepted by both providers.
        let s = serde_json::to_string(&SessionListParams::default()).unwrap();
        assert_eq!(s, "{}");
    }

    #[test]
    fn session_list_params_serialize_with_a_cwd_filter_matches_the_call_that_was_actually_made() {
        // Verified: Grok accepted `{"cwd": "<path>"}` and answered
        // identically to the filterless call.
        let params = SessionListParams { cwd: Some("/repo".to_owned()) };
        let s = serde_json::to_string(&params).unwrap();
        assert_eq!(s, r#"{"cwd":"/repo"}"#);
    }

    #[test]
    fn session_list_result_parses_the_live_claude_session_summary_shape() {
        // Claude's `session/list` entry: sessionId, cwd, title, updatedAt
        // -- no `_meta`. `updatedAt` uses milliseconds + `Z`.
        let raw = r#"{"sessions":[{
            "sessionId": "5932f0f1-b2c0-4651-8041-1e7d64be1d64",
            "cwd": "/repo",
            "title": "Fix the parser",
            "updatedAt": "2026-09-01T19:02:19.365Z"
        }]}"#;
        let result: SessionListResult = serde_json::from_str(raw).unwrap();
        assert_eq!(result.sessions.len(), 1);
        let entry = &result.sessions[0];
        assert_eq!(entry.session_id, "5932f0f1-b2c0-4651-8041-1e7d64be1d64");
        assert_eq!(entry.cwd.as_deref(), Some("/repo"));
        assert_eq!(entry.title.as_deref(), Some("Fix the parser"));
        assert_eq!(entry.updated_at.as_deref(), Some("2026-09-01T19:02:19.365Z"));
        assert!(entry.meta.is_none());
    }

    #[test]
    fn session_list_result_parses_the_live_grok_session_summary_shape_with_meta_facets() {
        // Grok's `session/list` entry: sessionId, cwd, updatedAt, _meta
        // (`x.ai/session`: kind + facets branch/cwd/gitRoot/repo) -- no
        // `title`. `updatedAt` uses six-digit microseconds + `+00:00`.
        // Sub-values of `kind`/`facets` were reported by key set, not
        // literal values, so this fixture uses illustrative content for
        // those; the key names and outer shape are as reported.
        let raw = r#"{"sessions":[{
            "sessionId": "01a05e41-1437-7231-9625-5fb30b8a02cd",
            "cwd": "C:\\repo\\gate4agent",
            "updatedAt": "2026-09-01T19:00:20.154340+00:00",
            "_meta": {
                "x.ai/session": {
                    "kind": "build",
                    "facets": {
                        "branch": "main",
                        "cwd": "C:\\repo\\gate4agent",
                        "gitRoot": "C:/repo/gate4agent",
                        "repo": "gate4agent"
                    }
                }
            }
        }]}"#;
        let result: SessionListResult = serde_json::from_str(raw).unwrap();
        let entry = &result.sessions[0];
        assert_eq!(entry.session_id, "01a05e41-1437-7231-9625-5fb30b8a02cd");
        assert_eq!(entry.updated_at.as_deref(), Some("2026-09-01T19:00:20.154340+00:00"));
        assert!(entry.title.is_none());
        let meta = entry.meta.as_ref().expect("grok entries carry _meta");
        assert_eq!(meta["x.ai/session"]["kind"], "build");
        assert_eq!(meta["x.ai/session"]["facets"]["repo"], "gate4agent");
    }

    #[test]
    fn session_close_params_serialize() {
        // Verified: identical `{"sessionId": "<id>"}` shape on both
        // claude-agent-acp 0.71.0 and Grok CLI 1.0.13.
        let params = SessionCloseParams { session_id: "s1".to_owned() };
        let s = serde_json::to_string(&params).unwrap();
        assert_eq!(s, r#"{"sessionId":"s1"}"#);
    }

    #[test]
    fn session_close_result_parses_the_live_claude_empty_response() {
        // Verbatim: Claude's `session/close` response is `{}`.
        let result: SessionCloseResult = serde_json::from_str("{}").unwrap();
        assert!(result.meta.is_none());
    }

    #[test]
    fn session_close_result_parses_the_live_grok_close_outcome_response() {
        // Verbatim: Grok's `session/close` response.
        let raw = r#"{"_meta": {"x.ai/closeOutcome": "closed"}}"#;
        let result: SessionCloseResult = serde_json::from_str(raw).unwrap();
        assert_eq!(result.meta.unwrap()["x.ai/closeOutcome"], "closed");
    }

    #[test]
    fn session_delete_params_serialize() {
        // UNVERIFIED -- not exercised by any live invocation, unchanged
        // from the earlier `{sessionId}`-request guess.
        let params = SessionDeleteParams { session_id: "s1".to_owned() };
        let s = serde_json::to_string(&params).unwrap();
        assert_eq!(s, r#"{"sessionId":"s1"}"#);
    }

    #[test]
    fn session_fork_params_serialize_carries_both_session_id_and_the_required_cwd() {
        // Verified: calling with only `sessionId` (this file's earlier
        // guess) was rejected live by claude-agent-acp 0.71.0 with:
        //   {"code": -32602, "message": "Invalid params",
        //    "data": {"_errors": [],
        //             "cwd": {"_errors": ["Invalid input: expected string, received undefined"]}}}
        // `cwd` is a required field on `SessionForkParams` -- the type
        // system itself now makes the earlier bug (a call missing `cwd`)
        // impossible to construct.
        let params = SessionForkParams { session_id: "s1".to_owned(), cwd: "/repo".to_owned() };
        let s = serde_json::to_string(&params).unwrap();
        assert_eq!(s, r#"{"sessionId":"s1","cwd":"/repo"}"#);
    }

    // -----------------------------------------------------------------------
    // Grok vendor `_x.ai/*` extensions — parsed from verbatim capture JSON
    // -----------------------------------------------------------------------

    #[test]
    fn parse_vendor_notification_models_update_updates_state_and_emits_event() {
        // Verbatim `_x.ai/models/update` params from Grok CLI 1.0.13
        // (`acp-grok.jsonl`), trimmed to one model.
        let raw = serde_json::from_str::<Value>(
            r#"{
                "currentModelId": "grok-4.6",
                "availableModels": [
                    {
                        "modelId": "grok-4.6",
                        "name": "Grok 4.6",
                        "description": "SpaceXAI's latest frontier model",
                        "_meta": {
                            "totalContextTokens": 500000,
                            "supportsReasoningEffort": true,
                            "reasoningEffort": "high",
                            "reasoningEfforts": [
                                {"id": "high", "value": "high", "label": "High Effort", "description": "Higher implementation quality with extensive reasoning", "default": true}
                            ]
                        }
                    }
                ]
            }"#,
        )
        .unwrap();
        let mut state = SessionState::default();
        let event = parse_vendor_notification(&mut state, "_x.ai/models/update", &raw)
            .expect("must parse the live models/update shape");
        assert_eq!(state.models.current_model_id.as_deref(), Some("grok-4.6"));
        assert_eq!(state.models.available_models.len(), 1);
        match event {
            AgentEvent::ModelsUpdate { current_model_id, available_models } => {
                assert_eq!(current_model_id.as_deref(), Some("grok-4.6"));
                assert_eq!(available_models.len(), 1);
                assert_eq!(available_models[0].model_id, "grok-4.6");
                assert_eq!(available_models[0].context_tokens, Some(500_000));
                assert_eq!(available_models[0].reasoning_efforts.len(), 1);
                assert_eq!(available_models[0].reasoning_efforts[0].id, "high");
            }
            other => panic!("expected AgentEvent::ModelsUpdate, got {other:?}"),
        }
    }

    #[test]
    fn parse_vendor_notification_settings_update_pulls_permission_fields() {
        // Trimmed from Grok CLI 1.0.13's real `_x.ai/settings/update`
        // (`acp-grok.jsonl`) -- the live capture itself has both fields
        // `null`; exercised here with concrete values to prove the
        // extraction path, since `raw` still carries the full payload
        // either way.
        let raw = json!({
            "show_resolved_model": false,
            "permission_mode": "auto",
            "auto_permission_mode_enabled": true,
            "subscription_tier_display": "SuperGrok Plus"
        });
        let mut state = SessionState::default();
        let event = parse_vendor_notification(&mut state, "_x.ai/settings/update", &raw)
            .expect("must parse settings/update");
        match event {
            AgentEvent::SettingsUpdate { permission_mode, auto_permission_mode_enabled, raw: echoed } => {
                assert_eq!(permission_mode.as_deref(), Some("auto"));
                assert_eq!(auto_permission_mode_enabled, Some(true));
                assert_eq!(echoed, raw, "raw must carry the full payload verbatim");
            }
            other => panic!("expected AgentEvent::SettingsUpdate, got {other:?}"),
        }
    }

    #[test]
    fn parse_vendor_notification_settings_update_tolerates_null_permission_fields() {
        // Verbatim from `acp-grok.jsonl`: both fields are actually `null`
        // on the wire in this capture.
        let raw = json!({"permission_mode": null, "auto_permission_mode_enabled": null});
        let mut state = SessionState::default();
        let event = parse_vendor_notification(&mut state, "_x.ai/settings/update", &raw).unwrap();
        assert!(matches!(
            event,
            AgentEvent::SettingsUpdate { permission_mode: None, auto_permission_mode_enabled: None, .. }
        ));
    }

    #[test]
    fn parse_vendor_notification_session_notification_hook_execution() {
        // Verbatim `_x.ai/session_notification` params from Grok CLI
        // 1.0.13 (`acp-grok.jsonl`), including the mangled-encoding error
        // text from a failed hook exactly as captured.
        let raw = serde_json::from_str::<Value>(
            r#"{
                "sessionId": "01a05e41-1437-7231-9625-5fb30b8a02cd",
                "update": {
                    "sessionUpdate": "hook_execution",
                    "event_name": "session_start",
                    "runs": [
                        {"name": "global/gate4agent-status:session_start[0].hooks[0]", "status": {"status": "success", "elapsed_ms": 539}},
                        {"name": "global/settings:session_start[0].hooks[0]", "status": {"status": "failed", "error": "exit code 1", "elapsed_ms": 701}},
                        {"name": "global/settings:session_start[1].hooks[0]", "status": {"status": "success", "elapsed_ms": 548}}
                    ]
                }
            }"#,
        )
        .unwrap();
        let mut state = SessionState::default();
        let event = parse_vendor_notification(&mut state, "_x.ai/session_notification", &raw)
            .expect("must parse hook_execution");
        match event {
            AgentEvent::HookExecutionUpdate { event_name, runs } => {
                assert_eq!(event_name, "session_start");
                assert_eq!(runs.len(), 3);
                assert_eq!(runs[0].status, "success");
                assert_eq!(runs[0].elapsed_ms, Some(539));
                assert_eq!(runs[1].status, "failed");
                assert_eq!(runs[1].error.as_deref(), Some("exit code 1"));
            }
            other => panic!("expected AgentEvent::HookExecutionUpdate, got {other:?}"),
        }
    }

    #[test]
    fn parse_vendor_notification_session_notification_model_changed() {
        // Verbatim from Grok CLI 1.0.13 (`acp-grok.jsonl`).
        let raw = json!({
            "sessionId": "01a05e41-1437-7231-9625-5fb30b8a02cd",
            "update": {"sessionUpdate": "model_changed", "model_id": "grok-4.6", "reasoning_effort": "high"}
        });
        let mut state = SessionState::default();
        let event = parse_vendor_notification(&mut state, "_x.ai/session_notification", &raw)
            .expect("must parse model_changed");
        match event {
            AgentEvent::ProviderModelChanged { model_id, reasoning_effort } => {
                assert_eq!(model_id, "grok-4.6");
                assert_eq!(reasoning_effort.as_deref(), Some("high"));
            }
            other => panic!("expected AgentEvent::ProviderModelChanged, got {other:?}"),
        }
    }

    #[test]
    fn parse_vendor_notification_mcp_servers_updated() {
        // Verbatim from Grok CLI 1.0.13 (`acp-grok.jsonl`).
        let raw = json!({
            "mcpServers": [
                {"name": "Puppeteer", "source": "local", "type": "stdio", "command": "npx", "args": ["-y", "@modelcontextprotocol/server-puppeteer"]}
            ]
        });
        let mut state = SessionState::default();
        let event = parse_vendor_notification(&mut state, "_x.ai/mcp/servers_updated", &raw)
            .expect("must parse mcp/servers_updated");
        match event {
            AgentEvent::McpServersUpdate { servers } => {
                assert_eq!(servers.len(), 1);
                assert_eq!(servers[0].name, "Puppeteer");
                assert_eq!(servers[0].transport, "stdio");
            }
            other => panic!("expected AgentEvent::McpServersUpdate, got {other:?}"),
        }
    }

    #[test]
    fn parse_vendor_notification_mcp_init_progress() {
        // Verbatim from Grok CLI 1.0.13 (`acp-grok.jsonl`).
        let raw = json!({"total": 1, "connected": 0, "sessionId": "01a05e41-1437-7231-9625-5fb30b8a02cd"});
        let mut state = SessionState::default();
        let event = parse_vendor_notification(&mut state, "_x.ai/mcp/init_progress", &raw).unwrap();
        assert!(matches!(event, AgentEvent::McpInitProgress { total: 1, connected: 0 }));
    }

    #[test]
    fn parse_vendor_notification_mcp_initialized() {
        // Verbatim from Grok CLI 1.0.13 (`acp-grok.jsonl`).
        let raw = json!({
            "sessionId": "01a05e41-1437-7231-9625-5fb30b8a02cd",
            "mcpToolCount": 7,
            "elapsedMs": 3887
        });
        let mut state = SessionState::default();
        let event = parse_vendor_notification(&mut state, "_x.ai/mcp_initialized", &raw).unwrap();
        assert!(matches!(
            event,
            AgentEvent::McpInitialized { tool_count: 7, elapsed_ms: 3887 }
        ));
    }

    #[test]
    fn parse_vendor_notification_announcements_update() {
        // Verbatim from Grok CLI 1.0.13 (`acp-grok.jsonl`).
        let raw = json!({
            "gen": 1788287666i64,
            "announcements": [
                {"id": "team", "message": "Select 'Grok 4.6' under /model.", "severity": "info", "title": "Grok 4.6 is here!", "cta": null, "updated_at": null, "expires_at": null, "dismissible": null, "persistent": null}
            ]
        });
        let mut state = SessionState::default();
        let event = parse_vendor_notification(&mut state, "_x.ai/announcements/update", &raw)
            .expect("must parse announcements/update");
        match event {
            AgentEvent::AnnouncementsUpdate { announcements } => {
                assert_eq!(announcements.len(), 1);
                assert_eq!(announcements[0].id, "team");
                assert_eq!(announcements[0].title.as_deref(), Some("Grok 4.6 is here!"));
                assert_eq!(announcements[0].severity.as_deref(), Some("info"));
            }
            other => panic!("expected AgentEvent::AnnouncementsUpdate, got {other:?}"),
        }
    }

    #[test]
    fn parse_vendor_notification_unknown_x_ai_method_returns_none() {
        // An `_x.ai/*` method this build has never seen must not break
        // parsing -- the reader loop falls back to the generic
        // `RpcNotification` passthrough for it.
        let mut state = SessionState::default();
        let event = parse_vendor_notification(&mut state, "_x.ai/some_future_method", &json!({}));
        assert!(event.is_none());
    }

    #[test]
    fn parse_vendor_notification_unrelated_namespace_returns_none() {
        // A notification method entirely outside `_x.ai/` -- e.g. another
        // vendor's own future extension -- must likewise fall through.
        let mut state = SessionState::default();
        let event = parse_vendor_notification(&mut state, "_some.other.vendor/thing", &json!({}));
        assert!(event.is_none());
    }

    #[test]
    fn parse_vendor_notification_malformed_x_ai_payload_returns_none() {
        // A recognized `_x.ai/*` method with a payload that fails to
        // parse against its known shape must fall through to the generic
        // passthrough rather than panicking or fabricating an event.
        let mut state = SessionState::default();
        let event = parse_vendor_notification(&mut state, "_x.ai/mcp_initialized", &json!("not an object"));
        assert!(event.is_none());
    }

    // -----------------------------------------------------------------------
    // available_commands_update — `_meta` sidecar data is preserved
    // -----------------------------------------------------------------------

    #[test]
    fn available_command_keeps_meta_sidecar_data_in_extra() {
        // Trimmed from codex-acp 1.8.0's real `available_commands_update`
        // (`acp-codex.jsonl`) -- the `/plan` command's `_meta.
        // commandAction` wiring.
        let raw = r#"{
            "name": "plan",
            "description": "Turn plan mode on.",
            "input": null,
            "_meta": {"commandAction": {"kind": "setConfigOption", "configId": "collaboration_mode", "value": "plan"}}
        }"#;
        let command: AvailableCommand = serde_json::from_str(raw).unwrap();
        assert_eq!(command.name, "plan");
        assert!(command.input.is_none());
        assert!(command.extra.contains_key("_meta"));
    }
}