gate4agent-types 0.4.0

Pure data contracts for gate4agent backends and shells
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
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
use crate::{
    AdapterBinding, AdapterFamily, AgentId, CapabilityModelSummary, CapabilityProbeFailure,
    CapabilityProbeRequest, CapabilitySnapshot, HistoryCandidateSummary, HistoryOperation,
    HistoryQuery, HistorySessionRecord, HistorySnapshot, InputAction, InputPrepareError,
    PreparedInput, PreparedInputKind, ResumeAuthorityTarget, ResumeLaunchRequest,
    ResumeSessionSummary, ResumeSnapshot, ResumeTarget, SessionOptionSelection,
};
use serde::{Deserialize, Deserializer, Serialize};
use thiserror::Error;

pub const CONTROL_SESSIONS_MAX: usize = 512;
pub const CONTROL_INSTANCE_IDENTITIES_CAPACITY: u32 = 4_096;
pub const CONTROL_INSTANCE_IDENTITIES_MAX: usize = CONTROL_INSTANCE_IDENTITIES_CAPACITY as usize;
pub const TERMINAL_ROWS_MAX: u16 = 1_000;
pub const TERMINAL_COLUMNS_MAX: u16 = 1_000;
pub const WORKING_DIRECTORY_MAX_BYTES: usize = 32_768;
pub const PROVIDER_INGRESS_EVENTS_MAX: usize = 32;
pub const PROVIDER_EVENT_TEXT_MAX_BYTES: usize = 262_144;
pub const PROVIDER_EVENT_ID_MAX_BYTES: usize = 512;
pub const PROVIDER_EVENT_TOOLS_MAX: usize = 256;
pub const PROVIDER_INTERACTIONS_MAX: usize = 64;
pub const PROVIDER_INTERACTION_RESPONSE_MAX_BYTES: usize = 32_768;
pub const PROVIDER_INTERACTION_FAILURE_MAX_BYTES: usize = 4_096;
/// Bound on `ProviderEvent::InteractionRequested::options` -- same
/// rationale as `OPERATOR_GATE_OPTIONS_MAX`: an ACP `session/request_
/// permission` call offers a subset of exactly four `PermissionOptionKind`
/// values, so this gives headroom over that domain maximum without letting
/// a garbled or hostile agent inflate the wire payload.
pub const PROVIDER_INTERACTION_OPTIONS_MAX: usize = 8;
pub const PROVIDER_SUBAGENTS_MAX: usize = 64;
pub const PROVIDER_SESSION_LOCATOR_MAX_BYTES: usize = 32_768;
pub const PROVIDER_PLAN_STEPS_MAX: usize = 256;
pub const PROVIDER_AVAILABLE_COMMANDS_MAX: usize = 256;
pub const PROVIDER_CONFIG_OPTIONS_MAX: usize = 256;
pub const PROVIDER_CONFIG_OPTION_CHOICES_MAX: usize = 256;
pub const PROVIDER_MODE_CATALOG_MAX: usize = 256;

#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
#[serde(transparent)]
pub struct AgentInstanceId(pub u64);

#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
#[serde(transparent)]
pub struct CommandId(pub u64);

#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
#[serde(transparent)]
pub struct OperationId(pub u64);

#[derive(
    Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize, Deserialize,
)]
#[serde(transparent)]
pub struct SessionGeneration(pub u64);

/// How much autonomy a freshly spawned provider CLI process is granted at
/// launch, independent of which transport (PTY, inline/pipe, ACP) execs it --
/// these are process launch arguments, the same axis regardless of transport.
///
/// The mapping from a level to actual CLI flags is per-provider, verified
/// against vendor documentation (and, for `grok`/`kimi`, against a third-party
/// harness's observed behavior), and lives in `gate4agent_catalog` -- the
/// crate that owns launch policy -- not here; this type only names the
/// levels. Where a provider has no verified intermediate flag (`grok` and
/// `kimi` do not have one for `Moderate` or `ReadOnly` as of this writing),
/// the catalog's mapping falls back to `Unmanaged` behavior (no injected
/// flag) rather than fabricating one -- see
/// `gate4agent_catalog::approval_level_args`.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum ApprovalLevel {
    /// No restriction: the provider CLI is launched with whatever flag
    /// grants it full autonomy (Claude `--permission-mode bypassPermissions`,
    /// Codex `--dangerously-bypass-approvals-and-sandbox`, Grok
    /// `--permission-mode bypassPermissions`, Kimi `--yolo`). Default --
    /// restricting is opt-in, not asking a human is the norm.
    #[default]
    FullAuto,
    /// The provider's own middle ground, when one is verified (Claude
    /// `--permission-mode acceptEdits`, Codex `--sandbox workspace-write
    /// --ask-for-approval on-request`). A provider with no verified
    /// intermediate flag falls back to `Unmanaged` -- never a fabricated
    /// flag.
    Moderate,
    /// Read-only: no writes, no command execution (Claude
    /// `--permission-mode default`, Codex `--sandbox read-only
    /// --ask-for-approval never`). A provider with no verified read-only
    /// flag falls back to `Unmanaged`.
    ReadOnly,
    /// Impose nothing: launch with no approval-related flag at all and let
    /// the provider CLI use whatever it is configured with on its own.
    Unmanaged,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct StartRequest {
    pub working_directory: String,
    pub terminal_size: TerminalSize,
    #[serde(default)]
    pub initial_prompt: Option<String>,
    #[serde(default)]
    pub session_options: Option<SessionOptionSelection>,
    /// Approval-level axis for this spawn; defaults to
    /// `ApprovalLevel::FullAuto` when the caller does not set it, matching
    /// `ApprovalLevel`'s own default. `#[serde(default)]` so a peer that
    /// predates this field decodes it as the same default rather than
    /// failing to deserialize.
    #[serde(default)]
    pub approval_level: ApprovalLevel,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
pub struct ProviderRuntimePolicy {
    pub raw_pty_lifecycle: bool,
    pub semantic_readiness: bool,
    pub structured_prompt: bool,
    pub provider_session_identity: bool,
    pub semantic_resume: bool,
    /// Whether this session's provider-event ingestion may come from a
    /// declared hook adapter -- a native hooks contract the provider CLI
    /// itself calls over the authenticated loopback ingress route, with the
    /// node's own adapter normalizing the payload before it ever reaches the
    /// engine.
    ///
    /// This is deliberately NOT `semantic_readiness`, and granting one must
    /// never imply the other. `semantic_readiness` (and the `structured_
    /// prompt`/`provider_session_identity`/`semantic_resume` capabilities
    /// chained off it) authorize INFERRING provider semantics by parsing PTY
    /// terminal text -- that inference is only sound for a CLI version this
    /// build has a verified vendor terminal contract for (see
    /// `gate4agent-runtime-native`'s `VERIFIED_PROFILES`). A hook event is
    /// not an inference: the CLI is asserting it directly over a route this
    /// node authenticated, and the node's hook adapter -- not a terminal
    /// screen scanner -- turns it into a `ProviderEvent`. None of the
    /// terminal-behaviour verification a vendor contract encodes is
    /// relevant to that trust story, so `hook_semantics` is derived purely
    /// from "does the catalog declare a hook adapter for this provider" and
    /// never from a vendor version probe. Conflating the two would let a
    /// provider that merely declares a hook adapter silently unlock
    /// PTY-parsing semantics it was never verified for, or -- the bug this
    /// field fixes -- let a verified-semantic gate silently swallow every
    /// hook event a provider with no verified profile at all (grok, codex,
    /// kimi) sends over a route that is otherwise working end to end.
    pub hook_semantics: bool,
}

impl ProviderRuntimePolicy {
    pub fn new(
        raw_pty_lifecycle: bool,
        semantic_readiness: bool,
        structured_prompt: bool,
        provider_session_identity: bool,
        semantic_resume: bool,
        hook_semantics: bool,
    ) -> Result<Self, ProviderRuntimePolicyError> {
        let policy = Self {
            raw_pty_lifecycle,
            semantic_readiness,
            structured_prompt,
            provider_session_identity,
            semantic_resume,
            hook_semantics,
        };
        policy.validate()?;
        Ok(policy)
    }

    pub const fn raw_pty() -> Self {
        Self {
            raw_pty_lifecycle: true,
            semantic_readiness: false,
            structured_prompt: false,
            provider_session_identity: false,
            semantic_resume: false,
            hook_semantics: false,
        }
    }

    /// The all-false policy: no capability admitted at all. This is the
    /// correct shape for a transport that has no PTY and whose catalog entry
    /// declares no contract this build can grant a semantic capability from
    /// -- e.g. a Pipe-transport provider with no declared Pipe contract.
    /// Unlike `raw_pty()`, this does NOT claim a PTY lifecycle exists.
    pub const fn none() -> Self {
        Self {
            raw_pty_lifecycle: false,
            semantic_readiness: false,
            structured_prompt: false,
            provider_session_identity: false,
            semantic_resume: false,
            hook_semantics: false,
        }
    }

    /// Only `semantic_resume` and `hook_semantics` require the raw PTY
    /// lifecycle. `semantic_readiness`, `structured_prompt`, and
    /// `provider_session_identity` do NOT, on their own -- an ACP transport
    /// has no PTY at all, yet `session/prompt` and `session/update` are
    /// MANDATORY surface of the ACP protocol itself, and `session/new` MUST
    /// return a `sessionId` under that same specification, none of it an
    /// inference this build makes by parsing PTY terminal text the way it
    /// does for a verified PTY vendor contract. `provider_session_identity`
    /// in particular is not a bare protocol formality here: both shipped ACP
    /// adapters map that mandatory `sessionId` to the provider's own durable
    /// session id (claude-agent-acp's is the Claude Code session id and
    /// on-disk transcript filename; codex-acp's is the Codex thread id), and
    /// the ACP spawn path publishes it as a `SessionId`-keyed
    /// `ProviderEvent::SessionIdentityObserved`, which is what carries a
    /// newly-created record from `IdentityPending` to `Live`. An agent whose
    /// adapter never emits that event -- because it returns no `sessionId`,
    /// violating the ACP contract this grant relies on -- correctly stays
    /// `IdentityPending` rather than being treated as identity-less; that is
    /// the refusal-by-name this policy is meant to produce for such an
    /// agent, not a defect in the grant. Granting `semantic_readiness`/
    /// `structured_prompt`/`provider_session_identity` with
    /// `raw_pty_lifecycle: false` is therefore a legitimate policy shape (see
    /// `gate4agent_node::provider_runtime::policy_for_transport`'s
    /// `TransportKind::Acp` arm), not a defect this validation should catch.
    ///
    /// `semantic_resume`/`hook_semantics` keep the old, stricter rule: today
    /// nothing derives either of the two for a transport other than a
    /// verified PTY vendor contract -- ACP's spec gives no resume guarantee
    /// analogous to `session/new`'s `sessionId`, and the engine separately
    /// refuses ACP resume outright -- so granting one without
    /// `raw_pty_lifecycle` remains a construction defect rather than a
    /// legitimate non-PTY policy shape.
    pub fn validate(self) -> Result<(), ProviderRuntimePolicyError> {
        if (self.semantic_resume || self.hook_semantics) && !self.raw_pty_lifecycle {
            return Err(ProviderRuntimePolicyError::SemanticCapabilityRequiresRawPty);
        }
        if self.structured_prompt && !self.semantic_readiness {
            return Err(ProviderRuntimePolicyError::StructuredPromptRequiresReadiness);
        }
        if self.semantic_resume && !self.provider_session_identity {
            return Err(ProviderRuntimePolicyError::ResumeRequiresSessionIdentity);
        }
        Ok(())
    }

    pub const fn admits(self, capability: ProviderRuntimeCapability) -> bool {
        match capability {
            ProviderRuntimeCapability::RawPtyLifecycle => self.raw_pty_lifecycle,
            ProviderRuntimeCapability::SemanticReadiness => self.semantic_readiness,
            ProviderRuntimeCapability::StructuredPrompt => self.structured_prompt,
            ProviderRuntimeCapability::ProviderSessionIdentity => {
                self.provider_session_identity
            }
            ProviderRuntimeCapability::SemanticResume => self.semantic_resume,
            ProviderRuntimeCapability::HookSemantics => self.hook_semantics,
        }
    }
}

impl<'de> Deserialize<'de> for ProviderRuntimePolicy {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        #[derive(Deserialize)]
        struct WirePolicy {
            raw_pty_lifecycle: bool,
            semantic_readiness: bool,
            structured_prompt: bool,
            provider_session_identity: bool,
            semantic_resume: bool,
            hook_semantics: bool,
        }

        let wire = WirePolicy::deserialize(deserializer)?;
        Self::new(
            wire.raw_pty_lifecycle,
            wire.semantic_readiness,
            wire.structured_prompt,
            wire.provider_session_identity,
            wire.semantic_resume,
            wire.hook_semantics,
        )
        .map_err(serde::de::Error::custom)
    }
}

#[derive(Clone, Copy, Debug, Eq, Error, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum ProviderRuntimePolicyError {
    #[error("semantic resume and hook semantics require the raw PTY lifecycle")]
    SemanticCapabilityRequiresRawPty,
    #[error("structured prompts require semantic readiness")]
    StructuredPromptRequiresReadiness,
    #[error("semantic resume requires provider session identity")]
    ResumeRequiresSessionIdentity,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum ProviderRuntimeCapability {
    RawPtyLifecycle,
    SemanticReadiness,
    StructuredPrompt,
    ProviderSessionIdentity,
    SemanticResume,
    /// Admits provider-event ingestion sourced from a declared hook adapter.
    /// Independent of `SemanticReadiness` -- see `ProviderRuntimePolicy::
    /// hook_semantics` for why the two must never stand in for each other.
    HookSemantics,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct TerminalSize {
    pub rows: u16,
    pub columns: u16,
}

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum TerminalMouseProtocolEncoding {
    #[default]
    Default,
    Utf8,
    Sgr,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct TerminalFrame {
    pub sequence: u64,
    pub size: TerminalSize,
    pub cursor_row: u16,
    pub cursor_column: u16,
    pub contents: String,
    pub formatted: Vec<u8>,
    #[serde(default)]
    pub scrollback_formatted: Vec<Vec<u8>>,
    #[serde(default)]
    pub alternate_screen: bool,
    #[serde(default)]
    pub mouse_protocol_enabled: bool,
    #[serde(default)]
    pub mouse_protocol_encoding: TerminalMouseProtocolEncoding,
    /// Unix-epoch milliseconds when this frame's screen state was
    /// materialized -- the one instant `PtyEventPublisher::snapshot` turns
    /// live terminal state into a frame. Every hop after that (the shell's
    /// `ObservationEnvelope`, the c2 relay, the harness's terminal ring
    /// buffer, the operator wire) carries this value through unchanged; none
    /// of them may recompute, refresh, or zero it, because the whole point
    /// of the field is to let something 200ms downstream in a ring buffer
    /// still answer "how stale am I". `#[serde(default)]` so a peer that
    /// predates this field decodes it as 0 -- "age unknown" -- instead of a
    /// fabricated timestamp. Diffing this value across two hosts also mixes
    /// in their clock skew, not just transit time, so a consumer comparing
    /// it against wall-clock time must say so rather than presenting the
    /// gap as pure network/queue latency.
    #[serde(default)]
    pub produced_at_unix_ms: u64,
    /// The screen classification at the instant THIS frame's screen was
    /// materialized -- stamped once at the node from the same snapshot that
    /// produced `contents`/`formatted`, and carried through every hop
    /// unchanged like `produced_at_unix_ms`; no hop may recompute it against
    /// its own (possibly staler) copy of the screen. `#[serde(default)]` so a
    /// peer that predates this field decodes it as `Unknown` -- "not
    /// classified" -- rather than a fabricated `Ready`; defaulting to
    /// `Unknown` and not `Ready` is the entire point of that default.
    #[serde(default)]
    pub screen_state: PtyScreenState,
    /// Whether bracketed-paste mode was enabled on the PTY at the instant
    /// THIS frame's screen was materialized, read straight off the same
    /// `vt100::Screen` snapshot that produced `contents`/`formatted` --
    /// `Some(true)` means the terminal application has turned the mode on
    /// (a paste is delivered to it as one bracketed block instead of
    /// keystrokes), `Some(false)` means it explicitly has not, and `None`
    /// means this frame predates the field or the value was never sampled.
    /// `None` is not a claim that the mode is off; a caller that needs to
    /// know must treat `None` the same as `PtyScreenState::Unknown` --
    /// absence of information, not a fabricated default.
    /// `skip_serializing_if` is load-bearing the same way it is on
    /// `HarnessRuntimeTerminalFrameV1::screen_state`: the key must be
    /// ABSENT from the JSON, not `null`, so a peer that predates this field
    /// decodes it as `None` rather than a fabricated `Some(false)`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bracketed_paste: Option<bool>,
}

pub const FOREGROUND_PROCESS_NAME_MAX_BYTES: usize = 512;
pub const PTY_SCREEN_GATE_NAME_MAX_BYTES: usize = 128;
/// Bound on `OperatorGateState::options` -- large enough for any list a real
/// prompt has ever been observed to render (2-4 choices), small enough that
/// a garbled or hostile screen capture cannot inflate the wire payload.
pub const OPERATOR_GATE_OPTIONS_MAX: usize = 8;
/// Per-`OperatorGateOption::text` byte bound, same scale as
/// `PTY_SCREEN_GATE_NAME_MAX_BYTES` -- an option label is a single short
/// line off the screen, never a paragraph.
pub const OPERATOR_GATE_OPTION_TEXT_MAX_BYTES: usize = 128;
/// Bound on `OperatorGateSubject::Directory`'s `path`, matching the scale of
/// other path-shaped fields carried on this wire (see `WORKING_DIRECTORY_MAX_BYTES`
/// for the same order of magnitude on a full working-directory string).
pub const OPERATOR_GATE_PATH_MAX_BYTES: usize = 32_768;

/// What TYPE of blocking question `OperatorGateState` is showing, classified
/// from the screen's own top-level phrasing (see `startup_operator_gate` in
/// `gate4agent-shell-native`, the only producer). Distinct kinds exist so a
/// consumer can react differently to "an update is running" versus "type an
/// answer" without parsing `OperatorGateSubject`/`options` first.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum OperatorGateKind {
    /// Trust the current project directory before the CLI will read or run
    /// anything in it.
    WorkspaceTrust,
    /// Trust a specific set of shell hooks the CLI discovered inside an
    /// already-trusted directory. Kept distinct from `WorkspaceTrust`: that
    /// gate is about the directory as a whole, this one is about hooks the
    /// CLI found inside it -- an operator reading `kind` should be able to
    /// tell which question is being asked.
    HookTrust,
    /// Sign in, or choose how to sign in / which credential to use.
    Authentication,
    /// The CLI (or a wrapper script fronting it) is installing or updating
    /// itself and wants a relaunch, regardless of which mechanism drives the
    /// update -- an in-app updater or an external package manager.
    VendorUpdate,
    /// A first-run welcome/setup screen unrelated to trust or auth (IDE
    /// integration notice, "press enter to continue" splash, and similar).
    Onboarding,
    /// Choosing a terminal color/text style during first-run setup.
    TerminalAppearance,
    /// A stored configuration format needs to be migrated/confirmed before
    /// the CLI continues.
    ConfigurationMigration,
}

impl OperatorGateKind {
    /// Short operator-facing label, one per variant, stable in wording with
    /// what this module classified as a bare string before `OperatorGateState`
    /// existed -- existing log lines and error messages that quote this text
    /// keep reading the same.
    pub fn label(&self) -> &'static str {
        match self {
            Self::WorkspaceTrust => "workspace trust",
            Self::HookTrust => "hook trust review",
            Self::Authentication => "authentication",
            Self::VendorUpdate => "vendor update",
            Self::Onboarding => "onboarding",
            Self::TerminalAppearance => "terminal appearance setup",
            Self::ConfigurationMigration => "configuration migration",
        }
    }
}

/// WHAT entity `OperatorGateState` is gating access to -- narrower than
/// `kind` (which says what TYPE of question this is): two `WorkspaceTrust`
/// gates always share `subject: Directory`, but the `path` detail (when a
/// matcher can read one off the screen) distinguishes which directory.
/// `Unknown` is the honest reading for a `kind` whose screen text does not
/// name a concrete subject from this list (a vendor updater or onboarding
/// splash is not "about" a directory, a hook set, or an account) -- it is
/// never upgraded into a guess.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "kebab-case")]
pub enum OperatorGateSubject {
    /// A project/workspace directory. `path` is the directory the screen
    /// names, when a matcher can read one off the text; `None` means the
    /// screen's phrasing did not carry one, not that there is no directory.
    Directory { path: Option<String> },
    /// A set of shell hooks discovered inside an already-trusted directory.
    /// `count` is the number reported on screen, when readable; `None` means
    /// unreadable, never zero.
    Hooks { count: Option<u32> },
    /// MCP servers configured for the project.
    McpServers,
    /// The signed-in account/identity.
    Account,
    /// An API key/credential value.
    ApiKey,
    /// Terminal color/text-style appearance.
    Appearance,
    /// No concrete subject from this list applies to the matched `kind`.
    Unknown,
}

/// HOW `OperatorGateState` is controlled -- what a caller resolving it
/// (typically a human, occasionally a scripted answer) needs to send.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum OperatorGateInput {
    /// Choices are numbered (`1.`, `2.`, ...); confirmed with Enter after
    /// selecting a number.
    NumberedList,
    /// Choices are an unnumbered list navigated with arrow keys and a
    /// cursor glyph; confirmed with Enter.
    ArrowList,
    /// A single acknowledgement -- nothing to choose between, just Enter.
    PressEnter,
    /// Free text (a pasted code, a typed value) rather than a choice from a
    /// list.
    TextEntry,
    /// The screen's input mechanism was not recognized.
    Unknown,
}

/// What choosing a given `OperatorGateOption` does, inferred from the verb
/// in its own on-screen text (see `classify_operator_gate_option_semantics`
/// in `gate4agent-shell-native`) -- never from its position or number, since
/// neither is stable across CLIs or screen wraps.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum OperatorGateOptionSemantics {
    /// Grants what the gate is asking for (trust, continue, proceed).
    Accept,
    /// Refuses what the gate is asking for (don't trust, continue without
    /// trusting) while still moving past the prompt.
    Decline,
    /// Opens a closer look before deciding (review the hooks/diff) rather
    /// than accepting or declining outright.
    Inspect,
    /// Leaves the CLI entirely rather than answering the prompt.
    Exit,
    /// The option's own text used none of the recognized verbs.
    Unknown,
}

/// One choice as rendered on screen inside an `OperatorGateState`.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct OperatorGateOption {
    /// The option's label exactly as it appears on screen (list-marker and
    /// leading whitespace stripped, nothing else altered) -- never
    /// paraphrased, so an operator reading it sees the same words the CLI
    /// rendered.
    pub text: String,
    pub semantics: OperatorGateOptionSemantics,
    /// Whether the screen's own cursor/highlight currently sits on this
    /// option. `false` means either it is not selected or selection is not
    /// visible on this screen shape -- there is no third state, because a
    /// consumer deciding "which option is highlighted right now" only ever
    /// needs to know if THIS one is.
    pub selected: bool,
}

impl OperatorGateOption {
    fn is_valid(&self) -> bool {
        !self.text.trim().is_empty()
            && self.text.len() <= OPERATOR_GATE_OPTION_TEXT_MAX_BYTES
            && !self.text.chars().any(char::is_control)
    }
}

/// The full classification of a screen recognized as an `OperatorGate`,
/// replacing what used to be a bare label string. `kind` is always known (a
/// matcher only returns this type once it has matched a specific gate
/// phrase); `subject`, `input`, and `options` degrade independently to
/// `Unknown`/empty when the screen's specific shape was not recognized --
/// never invented from `kind` alone.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct OperatorGateState {
    pub kind: OperatorGateKind,
    pub subject: OperatorGateSubject,
    pub input: OperatorGateInput,
    /// Recognized on-screen choices, in on-screen order. Empty means no
    /// option list was recognized -- NOT that the screen has no choices;
    /// see `OperatorGateInput::Unknown` for the paired "input mechanism
    /// unrecognized either" case.
    pub options: Vec<OperatorGateOption>,
}

impl OperatorGateState {
    /// The gate with nothing known past `kind` -- `subject: Unknown`,
    /// `input: Unknown`, no options. This is the honest shape for a matched
    /// `kind` whose screen a parser has not (yet) learned to read past the
    /// phrase that identified it; never upgrade an unread screen into a
    /// guessed subject or option list.
    pub fn new(kind: OperatorGateKind) -> Self {
        Self {
            kind,
            subject: OperatorGateSubject::Unknown,
            input: OperatorGateInput::Unknown,
            options: Vec::new(),
        }
    }

    /// Builder-style: attach a recognized subject.
    pub fn with_subject(mut self, subject: OperatorGateSubject) -> Self {
        self.subject = subject;
        self
    }

    /// Builder-style: attach a recognized input mechanism and its options
    /// together, since one is meaningless without the other (an `Unknown`
    /// input never carries options, and options never accompany an
    /// unrecognized input mechanism).
    pub fn with_options(mut self, input: OperatorGateInput, options: Vec<OperatorGateOption>) -> Self {
        self.input = input;
        self.options = options;
        self
    }

    /// Bounds check matching `PtyScreenState::is_valid`'s own rationale --
    /// every string this type carries travels over the wire into an
    /// operator UI and must be non-empty (where required), control-character
    /// free, and within its per-field byte cap before anything downstream
    /// trusts it.
    pub fn is_valid(&self) -> bool {
        let subject_valid = match &self.subject {
            OperatorGateSubject::Directory { path: Some(path) } => {
                !path.trim().is_empty()
                    && path.len() <= OPERATOR_GATE_PATH_MAX_BYTES
                    && !path.chars().any(char::is_control)
            }
            OperatorGateSubject::Directory { path: None }
            | OperatorGateSubject::Hooks { .. }
            | OperatorGateSubject::McpServers
            | OperatorGateSubject::Account
            | OperatorGateSubject::ApiKey
            | OperatorGateSubject::Appearance
            | OperatorGateSubject::Unknown => true,
        };
        subject_valid
            && self.options.len() <= OPERATOR_GATE_OPTIONS_MAX
            && self.options.iter().all(OperatorGateOption::is_valid)
    }
}

impl std::fmt::Display for OperatorGateState {
    /// Renders as `kind.label()` alone -- the same text this whole type
    /// replaced used to carry as its only payload -- so an existing
    /// `format!("...{gate}...")` call site keeps reading the same message
    /// after this type lands under it.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.kind.label())
    }
}

impl OperatorGateState {
    /// Longer operator-facing rendering than `Display`: the kind label,
    /// plus a compact list of recognized options (currently-selected one
    /// prefixed `*`) when `options` is non-empty. `Display` stays kind-only
    /// on purpose (see its own doc comment) -- this is for a surface that
    /// can afford, and wants, the fuller picture once one was parsed.
    pub fn describe(&self) -> String {
        if self.options.is_empty() {
            return self.kind.label().to_owned();
        }
        let options = self
            .options
            .iter()
            .map(|option| {
                if option.selected {
                    format!("*{}", option.text)
                } else {
                    option.text.clone()
                }
            })
            .collect::<Vec<_>>()
            .join(", ");
        format!("{} [{options}]", self.kind.label())
    }
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "kebab-case")]
pub enum ForegroundProcessKind {
    Agent { agent_id: AgentId },
    Shell,
    Other,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct ForegroundProcess {
    pub root_process_id: u32,
    pub process_id: u32,
    pub process_name: String,
    pub kind: ForegroundProcessKind,
}

impl ForegroundProcess {
    pub fn is_valid_for(&self, session_agent_id: &AgentId) -> bool {
        self.root_process_id > 0
            && self.process_id > 0
            && !self.process_name.trim().is_empty()
            && self.process_name.len() <= FOREGROUND_PROCESS_NAME_MAX_BYTES
            && !self.process_name.chars().any(char::is_control)
            && match &self.kind {
                ForegroundProcessKind::Agent { agent_id } => agent_id == session_agent_id,
                ForegroundProcessKind::Shell | ForegroundProcessKind::Other => true,
            }
    }
}

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum ForegroundAuthority {
    #[default]
    Unknown,
    Confirmed,
    Stale,
}

#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
pub struct ForegroundSnapshot {
    pub authority: ForegroundAuthority,
    pub process: Option<ForegroundProcess>,
    pub stale_reason: Option<String>,
}

/// Whether the screen currently painted at a PTY looks like the agent's own
/// composer, as classified by the node from the same terminal text a human
/// would read. This is a screen-content judgement, never a process-liveness
/// one -- `SessionStatus` already answers "is something running", and a
/// consumer must not fold the two into a single "is it running" question:
/// a process can be `Running` while its screen sits on an unrelated
/// installer prompt, and that combination is exactly the case this type
/// exists to distinguish.
#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "kebab-case")]
pub enum PtyScreenState {
    /// No observation has been made for this generation yet, or the most
    /// recent observation attempt failed. A caller deciding whether to write
    /// to the PTY blindly must treat this exactly like `NotAgent` -- there is
    /// no "probably fine" reading of "unclassified". Never optimistic.
    #[default]
    Unknown,
    /// The PTY's foreground process is neither the agent's own binary nor a
    /// tolerated wrapper that spawns it. `observed_process` records what was
    /// actually seen there, so an operator reading this gets "an update is
    /// installing" rather than a bare timeout with no explanation.
    NotAgent { observed_process: String },
    /// The foreground process matches, but the screen itself is showing a
    /// recognized blocking pattern -- workspace trust, authentication,
    /// a vendor update, first-run onboarding. This is the state that wants a
    /// human specifically, because resolving it means typing into the pane
    /// rather than dispatching another agent turn. `gate` is a structured
    /// `OperatorGateState`, not a bare label -- what TYPE of gate
    /// (`kind`), what it is gating (`subject`), how it is answered
    /// (`input`), and which choices were read off the screen (`options`),
    /// so a consumer can close the gate or ask an operator a real question
    /// instead of only ever surfacing a tag.
    OperatorGate { gate: OperatorGateState },
    /// The foreground process matches, but the screen shows the agent came
    /// up wrong or fell over -- a crash/stack trace, an expired or rejected
    /// login, a fatal startup error. Kept distinct from `OperatorGate` on
    /// purpose: a gate is a screen a human resolves BY typing into it, while
    /// nothing typed into this screen fixes it. Collapsing the two would
    /// lose exactly the diagnosis an operator needs -- "waiting for you"
    /// versus "broken". For write-gating it behaves like every other
    /// non-`Ready` state (refused); the split buys a correct label, not
    /// different gating. `reason` is a short classifier label, the same
    /// shape `OperatorGate::gate` used to carry before it became a
    /// structured type, never raw terminal text -- nothing in this enum
    /// carries screen contents. Where a provider has a
    /// `pty_sidecar` adapter bound, structured signals (rate limits arriving
    /// as a `ProviderEvent`) remain the authority for those specific
    /// conditions; this variant is the text-derived fallback, and the only
    /// signal at all for providers that emit no structured events.
    Failing { reason: String },
    /// The foreground process matches AND no known gate or failure pattern
    /// is showing. This is explicitly NOT a claim that the agent is idle,
    /// waiting for input, or will do anything useful with a write -- it only
    /// means the screen is not known to be showing something else. Reading
    /// `Ready` as "safe to act on" beyond that is the over-read this type
    /// exists to prevent. Note the asymmetry with the other four variants:
    /// each of them fires from a single signal (process mismatch, or a
    /// recognized gate/failure pattern alone), while `Ready` requires both
    /// the process and text signals to agree -- a screen the text matcher
    /// does not recognize never reaches `Ready` on that basis alone.
    Ready,
}

impl PtyScreenState {
    /// True unless this screen was READ as an obstacle. Refuses on the three
    /// states that carry a finding -- a gate the operator must answer, a
    /// foreign process, a failure -- and admits `Ready` and `Unknown` alike.
    ///
    /// `Unknown` admits deliberately. It does not mean "an obstacle we might
    /// have missed", it means the matcher recognized nothing, and refusing on
    /// it makes ignorance indistinguishable from a finding. Every provider
    /// reaches `Ready` within a frame or two of spawn on process identity
    /// alone, long before anything is on screen, so `Unknown` is mostly just
    /// the moment before that -- and the screen is no longer where this
    /// system decides what a session is doing. ACP carries that as protocol
    /// state and never consults this predicate at all; a PTY is an operator's
    /// surface first and a control channel second.
    ///
    /// What stays refused is what was actually read: writing a task into a
    /// trust prompt or a login screen puts the text nowhere and leaves Enter
    /// to pick a menu item blind. That is a finding, and findings still
    /// count. Answering such a screen is not blocked and never was -- key
    /// injection does not come through here.
    pub fn admits_blind_write(&self) -> bool {
        !matches!(
            self,
            Self::OperatorGate { .. } | Self::NotAgent { .. } | Self::Failing { .. }
        )
    }

    /// Bounds check matching `ForegroundProcess::is_valid_for`: the carried
    /// strings must be non-empty, control-character free, and within the
    /// per-field byte caps, since both travel over the wire into an operator
    /// UI and a raw process/gate label is not something to trust unbounded.
    pub fn is_valid(&self) -> bool {
        match self {
            Self::Unknown | Self::Ready => true,
            Self::NotAgent { observed_process } => {
                !observed_process.trim().is_empty()
                    && observed_process.len() <= FOREGROUND_PROCESS_NAME_MAX_BYTES
                    && !observed_process.chars().any(char::is_control)
            }
            Self::OperatorGate { gate } => gate.is_valid(),
            Self::Failing { reason } => {
                !reason.trim().is_empty()
                    && reason.len() <= PTY_SCREEN_GATE_NAME_MAX_BYTES
                    && !reason.chars().any(char::is_control)
            }
        }
    }
}

impl TerminalSize {
    pub fn is_valid(self) -> bool {
        (1..=TERMINAL_ROWS_MAX).contains(&self.rows)
            && (1..=TERMINAL_COLUMNS_MAX).contains(&self.columns)
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum TransportKind {
    Pty,
    Pipe,
    Acp,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct CommandEnvelope {
    pub id: CommandId,
    pub command: ControlCommand,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "kebab-case")]
pub enum ControlCommand {
    Register {
        instance_id: AgentInstanceId,
        agent_id: AgentId,
        transport: TransportKind,
    },
    Start {
        instance_id: AgentInstanceId,
        runtime_policy: ProviderRuntimePolicy,
        request: StartRequest,
    },
    Stop {
        instance_id: AgentInstanceId,
        force: bool,
    },
    SendInput {
        instance_id: AgentInstanceId,
        action: InputAction,
    },
    Resize {
        instance_id: AgentInstanceId,
        size: TerminalSize,
    },
    RefreshForeground {
        instance_id: AgentInstanceId,
    },
    ProbeCapabilities {
        instance_id: AgentInstanceId,
        request: CapabilityProbeRequest,
    },
    DiscoverHistory {
        instance_id: AgentInstanceId,
        query: HistoryQuery,
    },
    LoadHistory {
        instance_id: AgentInstanceId,
        candidate_id: String,
    },
    Resume {
        instance_id: AgentInstanceId,
        target: ResumeTarget,
        runtime_policy: ProviderRuntimePolicy,
        request: ResumeLaunchRequest,
    },
    ResolveInteraction {
        instance_id: AgentInstanceId,
        generation: SessionGeneration,
        interaction_id: ProviderInteractionId,
        response: ProviderInteractionResponse,
    },
    /// Switch the session's ACP `session/set_mode` mode. ACP-transport only;
    /// `gate4agent-engine`'s `set_session_mode` refuses any other transport.
    SetSessionMode {
        instance_id: AgentInstanceId,
        mode_id: String,
    },
    /// Set one ACP `session/set_config_option` value (model, reasoning
    /// effort, ...) -- the mechanism that supersedes session modes.
    /// `value_json` is pre-serialized JSON text, same convention as
    /// [`ProviderConfigOption::value_json`]: this crate does not depend on
    /// `serde_json`, so parsing it into a value is the shell executor's job.
    SetSessionConfigOption {
        instance_id: AgentInstanceId,
        option_id: String,
        value_json: String,
    },
    /// Switch the session's active model via a provider vendor extension
    /// (there is no `session/set_model` in the ACP spec proper). Wired end
    /// to end on the wire and through this command regardless of whether
    /// the current build shell can honor it for a given provider -- see
    /// `gate4agent-shell-native`'s `SetSessionModel` effect arm for what it
    /// actually does today.
    SetSessionModel {
        instance_id: AgentInstanceId,
        model_id: String,
    },
    IngestProvider {
        instance_id: AgentInstanceId,
        generation: SessionGeneration,
        source: ProviderSource,
        source_sequence: u64,
        events: Vec<ProviderEvent>,
    },
    Remove {
        instance_id: AgentInstanceId,
    },
}

impl ControlCommand {
    pub fn instance_id(&self) -> AgentInstanceId {
        match self {
            Self::Register { instance_id, .. }
            | Self::Start { instance_id, .. }
            | Self::Stop { instance_id, .. }
            | Self::SendInput { instance_id, .. }
            | Self::Resize { instance_id, .. }
            | Self::RefreshForeground { instance_id }
            | Self::ProbeCapabilities { instance_id, .. }
            | Self::DiscoverHistory { instance_id, .. }
            | Self::LoadHistory { instance_id, .. }
            | Self::Resume { instance_id, .. }
            | Self::ResolveInteraction { instance_id, .. }
            | Self::SetSessionMode { instance_id, .. }
            | Self::SetSessionConfigOption { instance_id, .. }
            | Self::SetSessionModel { instance_id, .. }
            | Self::IngestProvider { instance_id, .. }
            | Self::Remove { instance_id } => *instance_id,
        }
    }
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct EffectEnvelope {
    pub operation_id: OperationId,
    pub instance_id: AgentInstanceId,
    pub generation: SessionGeneration,
    pub effect: ControlEffect,
}

/// Route proof an effect executor must obtain immediately before a PTY write.
///
/// This is carried by the effect rather than inferred by a product shell so
/// local, hosted, and future browser-facing executors enforce the same rule.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "kebab-case")]
pub enum ForegroundRequirement {
    /// Explicit terminal text and controls are direct user terminal input.
    Any,
    /// Semantic input must target the session's configured agent.
    Agent { agent_id: AgentId },
    /// Intentional shell syntax may be written only while a shell owns the PTY.
    Shell,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "kebab-case")]
pub enum ControlEffect {
    Spawn {
        agent_id: AgentId,
        transport: TransportKind,
        runtime_policy: ProviderRuntimePolicy,
        request: StartRequest,
    },
    Stop {
        force: bool,
    },
    WriteInput {
        input: PreparedInput,
        required_foreground: ForegroundRequirement,
    },
    SubmitPrompt {
        prompt: String,
    },
    Interrupt,
    Resize {
        size: TerminalSize,
    },
    ObserveForeground,
    ProbeCapabilities {
        agent_id: AgentId,
        request: CapabilityProbeRequest,
    },
    DiscoverHistory {
        agent_id: AgentId,
        query: HistoryQuery,
    },
    LoadHistory {
        agent_id: AgentId,
        candidate_id: String,
    },
    AuthorizeResume {
        agent_id: AgentId,
        target: ResumeAuthorityTarget,
        request: ResumeLaunchRequest,
    },
    SpawnResume {
        agent_id: AgentId,
        transport: TransportKind,
        provider_session: ProviderSessionIdentity,
        runtime_policy: ProviderRuntimePolicy,
        request: ResumeLaunchRequest,
    },
    ResolveInteraction {
        target: ProviderInteractionTarget,
        response: ProviderInteractionResponse,
    },
    SetSessionMode {
        mode_id: String,
    },
    SetSessionConfigOption {
        option_id: String,
        value_json: String,
    },
    SetSessionModel {
        model_id: String,
    },
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct ObservationEnvelope {
    pub operation_id: Option<OperationId>,
    pub instance_id: AgentInstanceId,
    pub generation: SessionGeneration,
    pub observation: ControlObservation,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "kebab-case")]
pub enum ControlObservation {
    Spawned {
        process_id: Option<u32>,
    },
    SpawnFailed {
        message: String,
    },
    ProcessExited {
        exit_code: Option<i32>,
        final_terminal: Option<TerminalFrame>,
    },
    StopCompleted {
        forced: bool,
        exit_code: Option<i32>,
        final_terminal: Option<TerminalFrame>,
    },
    StopFailed {
        message: String,
    },
    InputCompleted,
    InputFailed {
        message: String,
    },
    ResizeCompleted {
        size: TerminalSize,
    },
    ResizeFailed {
        message: String,
    },
    ForegroundObserved {
        process: ForegroundProcess,
    },
    ForegroundFailed {
        message: String,
    },
    CapabilitiesProbed {
        session_option_models: Vec<CapabilityModelSummary>,
    },
    CapabilityProbeFailed {
        failure: CapabilityProbeFailure,
    },
    HistoryDiscovered {
        candidates: Vec<HistoryCandidateSummary>,
    },
    HistoryLoaded {
        session: HistorySessionRecord,
    },
    HistoryFailed {
        message: String,
    },
    ResumeAuthorized {
        provider_session: ProviderSessionIdentity,
    },
    ResumeDenied {
        reason: String,
    },
    ResumeFailed {
        message: String,
    },
    InteractionResolutionCompleted {
        interaction_id: ProviderInteractionId,
    },
    InteractionResolutionFailed {
        interaction_id: ProviderInteractionId,
        message: String,
    },
    /// `ControlEffect::SetSessionMode` succeeded; `mode_id` echoes back the
    /// mode the shell executor actually confirmed with the agent (Resize's
    /// `ResizeCompleted { size }` is the same convention).
    SessionModeSet {
        mode_id: String,
    },
    SessionModeSetFailed {
        message: String,
    },
    SessionConfigOptionSet {
        option_id: String,
    },
    SessionConfigOptionSetFailed {
        message: String,
    },
    SessionModelSet {
        model_id: String,
    },
    SessionModelSetFailed {
        message: String,
    },
    TerminalFrame {
        frame: TerminalFrame,
    },
    TerminalStale {
        message: String,
    },
    /// The node's merged `PtyScreenState` classification changed. Emitted
    /// only on an actual change, never per frame and never per foreground
    /// probe -- the node compares against its own last-published value
    /// before sending this, so a subscriber never has to de-duplicate.
    /// This is node-internal (shell -> engine), the same lane as
    /// `TerminalFrame`/`TerminalStale`, not a wire type: neither the node
    /// nor the c2 protocol carries `ControlObservation` across a process
    /// boundary, so this variant needs no version gate.
    ScreenState {
        state: PtyScreenState,
    },
    ProviderEvent {
        source: ProviderSource,
        sequence: u64,
        event: ProviderEvent,
    },
    ProviderGap {
        source: ProviderSource,
        source_sequence: u64,
        missed: u64,
    },
}

impl ControlObservation {
    pub fn requires_operation_id(&self) -> bool {
        !matches!(
            self,
            Self::ProcessExited { .. }
                | Self::TerminalFrame { .. }
                | Self::TerminalStale { .. }
                | Self::ScreenState { .. }
                | Self::ProviderEvent { .. }
                | Self::ProviderGap { .. }
        )
    }
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "kebab-case")]
pub enum SessionStatus {
    Registered,
    Starting,
    Running,
    Stopping,
    Exited { exit_code: Option<i32> },
    Failed { message: String },
}

impl SessionStatus {
    /// Whether a `Remove` command for a session in this status will be
    /// accepted rather than rejected as an invalid transition.
    ///
    /// It lives here, on the status itself, because two crates need the
    /// same answer and neither may depend on the other: `gate4agent-engine`
    /// enforces it in `Gate4AgentEngine::remove`, and `gate4agent-node`
    /// consults it in `wait_until_removed` BEFORE re-dispatching, because a
    /// rejected command is not free -- it publishes a `ControlEventKind::
    /// CommandRejected` to every subscriber and writes a WARN line. Ungated,
    /// one ordinary teardown produced 241 rejections in 1.6 seconds: the
    /// entire `Stopping` window at one known-doomed dispatch per 2ms tick.
    ///
    /// Exhaustive on purpose -- a status added to this enum without a
    /// decision here fails to compile rather than silently joining one set.
    pub fn allows_remove(&self) -> bool {
        match self {
            Self::Starting | Self::Running | Self::Stopping => false,
            Self::Registered | Self::Exited { .. } | Self::Failed { .. } => true,
        }
    }
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct SessionSnapshot {
    pub instance_id: AgentInstanceId,
    pub agent_id: AgentId,
    pub transport: TransportKind,
    pub generation: SessionGeneration,
    pub status: SessionStatus,
    pub pending_operation: Option<OperationId>,
    pub pending_input: Option<PreparedInputKind>,
    pub process_id: Option<u32>,
    pub terminal_size: Option<TerminalSize>,
    pub terminal_frame: Option<TerminalFrame>,
    pub terminal_stale: Option<String>,
    pub session_options: Option<SessionOptionSelection>,
    pub capabilities: CapabilitySnapshot,
    pub history: HistorySnapshot,
    pub resume: ResumeSnapshot,
    pub foreground: ForegroundSnapshot,
    pub provider: ProviderSnapshot,
    /// The session's CURRENT screen classification, as opposed to
    /// `terminal_frame`'s per-frame stamp -- both are read off one value
    /// computed at the node, but this one is what a consumer reads when it
    /// wants the state now without subscribing to terminal frames, which is
    /// what makes gating a dispatch possible for a caller holding only the
    /// session inventory.
    #[serde(default)]
    pub screen_state: PtyScreenState,
}

#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
pub struct TokenUsage {
    pub input_tokens: u64,
    pub output_tokens: u64,
    pub cache_read_tokens: u64,
    pub cache_write_tokens: u64,
    pub reasoning_tokens: u64,
    pub context_window: Option<u64>,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct ContextWindowUsage {
    pub uncached_input_tokens: u64,
    pub cache_read_tokens: u64,
    pub cache_write_tokens: u64,
    pub output_tokens: u64,
    pub unattributed_tokens: u64,
    pub used_tokens: u64,
    pub capacity_tokens: u64,
}

impl ContextWindowUsage {
    pub fn validate(&self) -> Result<(), ProviderEventValidationError> {
        if self.capacity_tokens == 0 {
            return Err(ProviderEventValidationError::ZeroContextWindowCapacity);
        }
        let segment_sum = self
            .uncached_input_tokens
            .checked_add(self.cache_read_tokens)
            .and_then(|sum| sum.checked_add(self.cache_write_tokens))
            .and_then(|sum| sum.checked_add(self.output_tokens))
            .and_then(|sum| sum.checked_add(self.unattributed_tokens))
            .ok_or(ProviderEventValidationError::ContextWindowSegmentsOverflow)?;
        if segment_sum != self.used_tokens {
            return Err(ProviderEventValidationError::ContextWindowSegmentsMismatch {
                segment_sum,
                used_tokens: self.used_tokens,
            });
        }
        Ok(())
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum ProviderInteractionKind {
    Approval,
    Question,
}

/// Which class of budget a `ProviderEvent::RateLimited` observation
/// concerns. This is the wire-typed counterpart of `gate4agent`'s own
/// (source-of-truth) `RateLimitType` -- kept as its own type here, rather
/// than imported, because this crate's contract forbids depending on
/// `gate4agent` (see this crate's `CLAUDE.md`); the conversion from the
/// detector's enum lives in the shell that already depends on both.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum ProviderRateLimitKind {
    /// Session/hourly limit (codex: the rolling 5h window).
    Session,
    /// Daily limit.
    Daily,
    /// Weekly limit.
    Weekly,
    /// Limit type could not be determined from the matched text.
    Unknown,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum ProviderInteractionOutcome {
    Approved,
    Answered,
    Denied,
    Interrupted,
    TurnEnded,
    Superseded,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum ProviderInteractionResponseKind {
    ApproveOnce,
    Deny,
    Answer,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "kebab-case")]
pub enum ProviderInteractionResponse {
    ApproveOnce,
    Deny,
    Answer { text: String },
}

impl ProviderInteractionResponse {
    pub fn kind(&self) -> ProviderInteractionResponseKind {
        match self {
            Self::ApproveOnce => ProviderInteractionResponseKind::ApproveOnce,
            Self::Deny => ProviderInteractionResponseKind::Deny,
            Self::Answer { .. } => ProviderInteractionResponseKind::Answer,
        }
    }

    pub fn outcome(&self) -> ProviderInteractionOutcome {
        match self {
            Self::ApproveOnce => ProviderInteractionOutcome::Approved,
            Self::Deny => ProviderInteractionOutcome::Denied,
            Self::Answer { .. } => ProviderInteractionOutcome::Answered,
        }
    }

    pub fn validate_for(
        &self,
        interaction_kind: ProviderInteractionKind,
    ) -> Result<(), ProviderInteractionResponseError> {
        match (interaction_kind, self) {
            (ProviderInteractionKind::Approval, Self::ApproveOnce)
            | (ProviderInteractionKind::Approval, Self::Deny)
            | (ProviderInteractionKind::Question, Self::Deny) => Ok(()),
            (ProviderInteractionKind::Question, Self::Answer { text }) => {
                if text.trim().is_empty() {
                    return Err(ProviderInteractionResponseError::EmptyAnswer);
                }
                let has_unsafe_control = text.chars().any(|character| {
                    character.is_control() && !matches!(character, '\n' | '\r' | '\t')
                });
                if text.len() > PROVIDER_INTERACTION_RESPONSE_MAX_BYTES || has_unsafe_control {
                    return Err(ProviderInteractionResponseError::InvalidAnswer {
                        max: PROVIDER_INTERACTION_RESPONSE_MAX_BYTES,
                    });
                }
                Ok(())
            }
            (ProviderInteractionKind::Approval, Self::Answer { .. }) => {
                Err(ProviderInteractionResponseError::AnswerRequiresQuestion)
            }
            (ProviderInteractionKind::Question, Self::ApproveOnce) => {
                Err(ProviderInteractionResponseError::ApprovalRequiresApproval)
            }
        }
    }
}

#[derive(Clone, Debug, Eq, Error, PartialEq)]
pub enum ProviderInteractionResponseError {
    #[error("interaction answer is required")]
    EmptyAnswer,
    #[error("interaction answer contains controls or exceeds {max} bytes")]
    InvalidAnswer { max: usize },
    #[error("an answer response requires a question interaction")]
    AnswerRequiresQuestion,
    #[error("an approve-once response requires an approval interaction")]
    ApprovalRequiresApproval,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum ProviderSessionKey {
    SessionId,
    ConversationId,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct ProviderSessionIdentity {
    pub key: ProviderSessionKey,
    pub id: String,
    pub transcript_path: Option<String>,
}

impl ProviderSessionIdentity {
    pub fn validate(&self) -> Result<(), ProviderEventValidationError> {
        validate_required("provider session id", &self.id, PROVIDER_EVENT_ID_MAX_BYTES)?;
        if self.id.starts_with('-') {
            return Err(ProviderEventValidationError::InvalidField {
                field: "provider session id",
                max: PROVIDER_EVENT_ID_MAX_BYTES,
            });
        }
        if let Some(path) = &self.transcript_path {
            validate_required(
                "provider transcript path",
                path,
                PROVIDER_SESSION_LOCATOR_MAX_BYTES,
            )?;
        }
        Ok(())
    }
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct ProviderSubagent {
    pub source: ProviderSource,
    pub provider_agent_id: String,
    pub agent_type: Option<String>,
    pub description: Option<String>,
}

/// Priority of a single [`ProviderPlanStep`], carried on
/// `ProviderEvent::Plan`.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum ProviderPlanPriority {
    High,
    Medium,
    Low,
}

/// Status of a single [`ProviderPlanStep`], carried on
/// `ProviderEvent::Plan`.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum ProviderPlanStatus {
    Pending,
    InProgress,
    Completed,
}

/// One step of the agent's execution plan (ACP transport's `plan`
/// update). `ProviderEvent::Plan` always carries the FULL plan snapshot,
/// never a delta.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct ProviderPlanStep {
    pub content: String,
    pub priority: ProviderPlanPriority,
    pub status: ProviderPlanStatus,
}

/// A single slash-style command the agent advertises (ACP transport's
/// `available_commands_update`).
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct ProviderAvailableCommand {
    pub name: String,
    pub description: String,
    pub input_hint: Option<String>,
}

/// One mode the agent advertised as selectable, read from ACP's
/// `session/new` handshake result (`AcpSession::available_modes()`) and
/// carried on [`ProviderEvent::ModeChanged`] alongside the id that changed.
/// Mirrors `gate4agent-node-protocol`'s `AgentStreamNamedIdV1`
/// field-for-field; this crate does not depend on that one (see this
/// crate's own `CLAUDE.md`), so the shape is repeated rather than shared.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct ProviderModeInfo {
    pub id: String,
    pub name: String,
    pub description: Option<String>,
}

/// The kind of a [`ProviderConfigOption`] -- `select` (choose one of
/// `choices`) or `boolean` (toggle the option's current value). `Unknown`
/// is the fallback for a kind string this build does not recognize.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum ProviderConfigOptionKind {
    Select,
    Boolean,
    Unknown,
}

/// One selectable value of a `select`-kind [`ProviderConfigOption`].
/// `value_json` is the choice's value pre-serialized to JSON text (this
/// crate is a pure data contract and does not depend on `serde_json`; see
/// `ProviderConfigOption::value_json` for the same convention applied to
/// the option's own current value).
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct ProviderConfigChoice {
    pub value_json: String,
    pub label: Option<String>,
}

/// One session configuration setting -- the mechanism ACP uses to change
/// model, reasoning effort, and similar settings, superseding session
/// modes. `ProviderEvent::ConfigOptionsUpdated` always carries the FULL
/// current set, never a delta.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct ProviderConfigOption {
    pub id: String,
    pub name: String,
    pub description: Option<String>,
    pub category: Option<String>,
    pub kind: ProviderConfigOptionKind,
    pub value_json: String,
    pub choices: Vec<ProviderConfigChoice>,
}

/// WHO decided a host request the agent sent to the ACP host -- see
/// [`ProviderEvent::HostRequestObserved`]. Mirrors `gate4agent`'s own
/// `HostDecisionAuthority` one-for-one; this crate cannot depend on
/// `gate4agent` (see this crate's `CLAUDE.md`), so the value is converted at
/// the boundary that already depends on both (`gate4agent-shell-native`).
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum HostDecisionAuthority {
    /// The dangerous-command gate forced this outcome ahead of `HostPolicy`
    /// -- `terminal/create` and `execute`-kind `session/request_permission`
    /// only. Always a denial.
    Gate,
    /// `HostPolicy` (`Yolo`/`Auto`/`ReadOnly`/`Deny`) decided the request
    /// the instant it arrived -- the default path for every request that
    /// is neither gate-blocked nor deferred.
    Policy,
    /// An operator answered a `session/request_permission` call that had
    /// been left `HostRequestDecision::Deferred`.
    Operator,
    /// A `session/request_permission` call left `HostRequestDecision::
    /// Deferred` reached its deadline with no operator answer, so
    /// `HostPolicy` -- the SAME policy that would have answered it
    /// immediately had deferral never been enabled -- decided it instead.
    /// Deliberately its own variant rather than `Policy`: folding it in
    /// would erase the fact that an operator was asked first and nobody
    /// answered in time. Equally deliberately not `Operator`: no human
    /// made this choice.
    DeadlinePolicy,
}

/// A typed answer to "what happened to this host request" -- see
/// [`ProviderEvent::HostRequestObserved`]. Mirrors `gate4agent`'s own
/// `HostRequestDecision` one-for-one; see [`HostDecisionAuthority`]'s doc
/// comment for why this crate keeps its own copy rather than importing it.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "kebab-case")]
pub enum HostRequestDecision {
    /// The request was allowed. `by` is who made that call.
    Granted { by: HostDecisionAuthority },
    /// The request was refused. `by` is who made that call.
    Denied { by: HostDecisionAuthority },
    /// The request has arrived and been recorded, but nothing has decided
    /// it yet. A later `ProviderEvent::HostRequestObserved` reports the
    /// eventual `Granted`/`Denied` outcome once one exists.
    Deferred,
}

/// Whether a `Granted` host request's underlying operation actually ran
/// without an I/O or execution problem -- see [`ProviderEvent::
/// HostRequestObserved`]. Mirrors `gate4agent`'s own `HostRequestOutcome`
/// one-for-one; see [`HostDecisionAuthority`]'s doc comment for why this
/// crate keeps its own copy rather than importing it.
///
/// Only meaningful paired with `HostRequestDecision::Granted`: a `Denied` or
/// `Deferred` request never attempted its underlying operation, so it is
/// always `Executed` there for lack of anything to have failed running.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "kebab-case")]
pub enum HostRequestOutcome {
    /// No execution problem -- either the request ran cleanly, or (for
    /// `Denied`/`Deferred`) no execution was ever attempted to fail.
    Executed,
    /// The request was authorized but failed while running it. `error` is
    /// the bounded underlying I/O/execution failure text (e.g. an OS error
    /// from a spawn call) -- never a policy/gate refusal message, which
    /// stays on `HostRequestObserved::reason` instead, exactly as it did
    /// before this variant existed.
    Failed { error: String },
}

impl Default for HostRequestOutcome {
    /// Backs `ProviderEvent::HostRequestObserved::outcome`'s
    /// `#[serde(default)]` -- mirrors `gate4agent_observation_protocol`'s
    /// own `HostRequestOutcomeV1::default`, the same field added at the
    /// same commit; see that type's doc comment for why a record from
    /// before this field existed always means `Executed`.
    fn default() -> Self {
        Self::Executed
    }
}

/// One option the agent offered on a `session/request_permission`-style
/// interaction, carried on `ProviderEvent::InteractionRequested::options`
/// exactly as the agent gave it -- see ACP's `PermissionOption` in
/// `src/acp/protocol.rs` (`option_id`, `name`, `kind`). This crate cannot
/// depend on `gate4agent` (see this crate's own `CLAUDE.md`), so the shape
/// is repeated here rather than shared, the same precedent
/// `ProviderRateLimitKind` already sets for a wire-typed mirror of a
/// `gate4agent`-side enum.
///
/// `kind` is carried as the ACP wire's own snake_case string (`allow_once`,
/// `allow_always`, `reject_once`, `reject_always`) rather than re-typed
/// into an enum here: nothing in this crate interprets `kind`, an operator
/// surface only ever displays it, and `gate4agent-node-protocol`'s
/// `AgentStreamInteractionOptionV1::kind` -- the wire shape this eventually
/// becomes -- is the same plain `String`, so a round trip through an enum
/// here would buy no safety, only an extra conversion.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct ProviderInteractionOption {
    pub option_id: String,
    pub name: String,
    pub kind: String,
}

/// Why an ACP turn stopped -- mirrors `gate4agent`'s own `StopReason`
/// (`src/core/types.rs`) one-for-one; this crate cannot depend on
/// `gate4agent` (see this crate's own `CLAUDE.md`), the same reason every
/// other wire-typed mirror here exists (`ProviderRateLimitKind`,
/// `ProviderInteractionOption`, ...). `ProviderError` is synthesized
/// locally by `gate4agent`'s ACP session when `session/prompt` itself
/// answers with a JSON-RPC error instead of a normal response -- see that
/// type's own doc comment for the live Codex fixture this shape was
/// measured against.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "kebab-case")]
pub enum ProviderStopReason {
    EndTurn,
    MaxTokens,
    MaxTurnRequests,
    Refusal,
    Cancelled,
    Other { value: String },
    ProviderError {
        code: i32,
        message: String,
        vendor_code: Option<String>,
    },
}

impl ProviderStopReason {
    fn validate_ingress(&self) -> Result<(), ProviderEventValidationError> {
        match self {
            Self::EndTurn | Self::MaxTokens | Self::MaxTurnRequests | Self::Refusal | Self::Cancelled => {
                Ok(())
            }
            Self::Other { value } => validate_text("stop reason", value, PROVIDER_EVENT_ID_MAX_BYTES),
            Self::ProviderError { message, vendor_code, .. } => {
                validate_text("provider error message", message, PROVIDER_EVENT_TEXT_MAX_BYTES)?;
                if let Some(code) = vendor_code {
                    validate_text("provider error vendor code", code, PROVIDER_EVENT_ID_MAX_BYTES)?;
                }
                Ok(())
            }
        }
    }
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "kebab-case")]
pub enum ProviderEvent {
    SessionStarted {
        session_id: String,
        model: String,
        tools: Vec<String>,
    },
    SessionIdentityObserved {
        identity: ProviderSessionIdentity,
    },
    TurnStarted {
        prompt: Option<String>,
    },
    WorkingObserved,
    Text {
        text: String,
        is_delta: bool,
    },
    Thinking {
        text: String,
    },
    ToolStarted {
        id: String,
        name: String,
        input_json: String,
        agent_id: Option<String>,
    },
    ToolCompleted {
        id: String,
        output: String,
        is_error: bool,
        duration_ms: Option<u64>,
        agent_id: Option<String>,
        /// ACP `tool_call_update._meta.nonExecutionKind` -- Claude's own
        /// vocabulary for WHY the tool never actually ran:
        /// `"user-rejected"`, `"permission-rule"`, `"interrupted"`,
        /// `"cancelled"`. `None` for a provider that sends no such field,
        /// or a call that genuinely ran and either succeeded or failed for
        /// real. `#[serde(default)]` reads a durable record written
        /// before this field existed as `None` -- honest, since that
        /// record could not have carried it either way.
        #[serde(default)]
        non_execution_kind: Option<String>,
    },
    TurnCompleted {
        usage: TokenUsage,
        is_cumulative: bool,
    },
    ContextWindowUsage {
        usage: ContextWindowUsage,
    },
    TurnInterrupted,
    SessionEnded {
        result: String,
        cost_usd: Option<String>,
        is_error: bool,
        /// Why the turn stopped, when the transport is ACP and one exists
        /// -- mirrors `gate4agent`'s own `StopReason` (`src/core/
        /// types.rs`) one-for-one; this crate cannot depend on
        /// `gate4agent` (see this crate's own `CLAUDE.md`), the same
        /// reason every other wire-typed mirror here exists. `None` for a
        /// non-ACP transport, and for a durable record written before
        /// this field existed (`#[serde(default)]`).
        #[serde(default)]
        stop_reason: Option<ProviderStopReason>,
    },
    Error {
        message: String,
    },
    Ready,
    InteractionRequested {
        request_id: Option<String>,
        interaction_kind: ProviderInteractionKind,
        tool_name: String,
        /// The ACP `PermissionToolCall.title` -- the human sentence
        /// describing this particular call (e.g. "Edit files"), when the
        /// source carries one. `None` means this source never carries a
        /// title at all (a PTY- or hook-sourced interaction has no such
        /// field to read -- see `gate4agent-shell-native`'s construction
        /// sites), never that a title was dropped after arriving.
        title: Option<String>,
        prompt: String,
        /// The concrete options the agent is willing to accept a decision
        /// from, in the agent's own order -- an ACP `PermissionOption`
        /// list verbatim (see `ProviderInteractionOption`). Empty means
        /// this source has no option list to offer at all (PTY- and
        /// hook-sourced interactions), never that the agent offered zero
        /// and one was dropped.
        options: Vec<ProviderInteractionOption>,
        agent_id: Option<String>,
    },
    InteractionResolved {
        request_id: String,
        outcome: ProviderInteractionOutcome,
    },
    SubagentStarted {
        agent_id: String,
        agent_type: Option<String>,
        description: Option<String>,
    },
    SubagentStopped {
        agent_id: String,
    },
    RateLimited {
        limit_type: ProviderRateLimitKind,
        resets_at: Option<String>,
        usage_percent: Option<String>,
        raw_message: String,
    },
    /// The agent sent a JSON-RPC request to the ACP host -- `session/
    /// request_permission`, `fs/read_text_file`, `fs/write_text_file`,
    /// `terminal/create`, `terminal/output`, `terminal/wait_for_exit`,
    /// `terminal/kill`, `terminal/release`. `decision` is read off the
    /// host's own answer, not re-derived here -- see the source
    /// (`gate4agent`'s `AgentEvent::RpcIncomingRequest::decision`) for
    /// exactly how. A `session/request_permission` call the host chose to
    /// defer to an operator arrives here TWICE under different `method`/
    /// `params_json` snapshots but the SAME logical request: once as
    /// `HostRequestDecision::Deferred` when it is recorded, then again as
    /// `Granted`/`Denied` once `HostPolicy` (`Yolo`/`Auto`/`ReadOnly`/`Deny`)
    /// or an operator decides it -- see `HostRequestDecision` and
    /// `HostDecisionAuthority` for what each of the four ways a request can
    /// end up decided actually means. This event does not change what the
    /// host does; it exists purely so an operator sees the request AND the
    /// decision instead of the request silently disappearing into a
    /// refusal nobody downstream ever hears about.
    HostRequestObserved {
        method: String,
        params_json: String,
        decision: HostRequestDecision,
        /// Whether an authorized (`Granted`) request actually ran cleanly
        /// or failed doing so -- see [`HostRequestOutcome`]'s own doc
        /// comment for why this is a separate field from `decision` rather
        /// than a third flavor of `Denied`. Always `Executed` for `Denied`/
        /// `Deferred` (nothing ran to fail). `#[serde(default)]` reads a
        /// record from before this field existed as `Executed` -- see
        /// `HostRequestOutcome::default`.
        #[serde(default)]
        outcome: HostRequestOutcome,
        /// The refusal text behind a `Denied` decision, when this session
        /// actually computed one -- the dangerous-command gate's own
        /// "blocked by dangerous-command gate: rule=…, argument=…", or
        /// `HostPolicy`'s fixed "denied by host policy" sentence. `None` for
        /// every `Granted`/`Deferred` decision (there is nothing to explain),
        /// and for a `Denied` decision this session's host handler did not
        /// attach text to -- never a placeholder standing in for a reason
        /// nobody computed. Bounded and verbatim, the same
        /// `PROVIDER_EVENT_TEXT_MAX_BYTES` bound `ToolCompleted::output`
        /// uses -- never summarised or rewritten at the point this is
        /// minted (`gate4agent-shell-native`'s `provider_event`).
        reason: Option<String>,
    },
    /// A JSON-RPC notification the reader received but could not classify
    /// into any other `ProviderEvent` -- most commonly a `session/update`
    /// whose `update` shape none of the known kinds matched, but also any
    /// other notification method this build has no mapping for. This is a
    /// raw protocol echo, NOT a normal operational event: nothing here has
    /// been validated against a known shape, so a consumer must treat
    /// `payload_json` as opaque vendor JSON, not a fact to act on.
    UnrecognizedNotification {
        method: String,
        payload_json: String,
    },
    /// Echo of a user message, replayed when resuming a loaded session
    /// (ACP transport's `user_message_chunk`).
    UserMessage {
        text: String,
        is_delta: bool,
    },
    /// The agent's full execution plan, replacing any plan reported
    /// before it (ACP transport's `plan`).
    Plan {
        steps: Vec<ProviderPlanStep>,
    },
    /// The agent's slash-command catalog changed (ACP transport's
    /// `available_commands_update`).
    AvailableCommandsUpdated {
        commands: Vec<ProviderAvailableCommand>,
    },
    /// The session's active mode changed (ACP transport's
    /// `current_mode_update`). `available` is the mode catalogue the agent
    /// returned at `session/new` (`AcpSession::available_modes()`), read
    /// back at the moment this event is minted -- `current_mode_update`
    /// itself carries only the new id, never the catalogue. ACP orders
    /// `session/new` strictly before any `session/update`, and the
    /// catalogue never changes after handshake, so by the time a
    /// `ModeChanged` can exist the same session object's catalogue is
    /// already the real one: an empty `available` here always means the
    /// agent announced zero modes, never "not read yet".
    ModeChanged {
        mode_id: String,
        available: Vec<ProviderModeInfo>,
    },
    /// Session metadata changed; only the fields that actually changed
    /// are populated (ACP transport's `session_info_update`).
    SessionInfoUpdated {
        title: Option<String>,
    },
    /// Context-window consumption and, when reported, turn cost (ACP
    /// transport's `usage_update`). `cost_amount` is a decimal string, not
    /// `f64`, for the same reason `SessionEnded::cost_usd` is -- so this
    /// type can keep deriving `Eq`.
    UsageUpdated {
        used_tokens: Option<u64>,
        context_window: Option<u64>,
        cost_amount: Option<String>,
        cost_currency: Option<String>,
    },
    /// The full current set of session configuration options (ACP
    /// transport's `config_option_update`).
    ConfigOptionsUpdated {
        options: Vec<ProviderConfigOption>,
    },
}

impl ProviderEvent {
    pub fn validate_ingress(&self) -> Result<(), ProviderEventValidationError> {
        match self {
            Self::SessionStarted {
                session_id,
                model,
                tools,
            } => {
                validate_required("session_id", session_id, PROVIDER_EVENT_ID_MAX_BYTES)?;
                validate_identifier("model", model, PROVIDER_EVENT_ID_MAX_BYTES)?;
                if tools.len() > PROVIDER_EVENT_TOOLS_MAX {
                    return Err(ProviderEventValidationError::TooManyTools {
                        count: tools.len(),
                        max: PROVIDER_EVENT_TOOLS_MAX,
                    });
                }
                for tool in tools {
                    validate_required("tool", tool, PROVIDER_EVENT_ID_MAX_BYTES)?;
                }
            }
            Self::SessionIdentityObserved { identity } => {
                identity.validate()?;
            }
            Self::TurnStarted { prompt } => {
                if let Some(prompt) = prompt {
                    validate_text("prompt", prompt, PROVIDER_EVENT_TEXT_MAX_BYTES)?;
                }
            }
            Self::Text { text, .. } | Self::Thinking { text } => {
                validate_text("text", text, PROVIDER_EVENT_TEXT_MAX_BYTES)?;
            }
            Self::ToolStarted {
                id,
                name,
                input_json,
                agent_id,
            } => {
                validate_required("tool id", id, PROVIDER_EVENT_ID_MAX_BYTES)?;
                validate_required("tool name", name, PROVIDER_EVENT_ID_MAX_BYTES)?;
                validate_text("tool input", input_json, PROVIDER_EVENT_TEXT_MAX_BYTES)?;
                validate_optional_agent_id(agent_id)?;
            }
            Self::ToolCompleted {
                id,
                output,
                agent_id,
                non_execution_kind,
                ..
            } => {
                validate_required("tool id", id, PROVIDER_EVENT_ID_MAX_BYTES)?;
                validate_text("tool output", output, PROVIDER_EVENT_TEXT_MAX_BYTES)?;
                validate_optional_agent_id(agent_id)?;
                if let Some(kind) = non_execution_kind {
                    validate_text("tool non-execution kind", kind, PROVIDER_EVENT_ID_MAX_BYTES)?;
                }
            }
            Self::SessionEnded {
                result,
                cost_usd,
                stop_reason,
                ..
            } => {
                validate_text("session result", result, PROVIDER_EVENT_TEXT_MAX_BYTES)?;
                if let Some(cost) = cost_usd {
                    validate_identifier("cost", cost, PROVIDER_EVENT_ID_MAX_BYTES)?;
                }
                if let Some(stop_reason) = stop_reason {
                    stop_reason.validate_ingress()?;
                }
            }
            Self::Error { message } => {
                validate_required_text("error", message, PROVIDER_EVENT_TEXT_MAX_BYTES)?;
            }
            Self::InteractionRequested {
                request_id,
                interaction_kind,
                tool_name,
                title,
                prompt,
                options,
                agent_id,
            } => {
                if let Some(request_id) = request_id {
                    validate_required(
                        "interaction request id",
                        request_id,
                        PROVIDER_EVENT_ID_MAX_BYTES,
                    )?;
                }
                validate_required("interaction tool", tool_name, PROVIDER_EVENT_ID_MAX_BYTES)?;
                if let Some(title) = title {
                    validate_text("interaction title", title, PROVIDER_EVENT_TEXT_MAX_BYTES)?;
                }
                if *interaction_kind == ProviderInteractionKind::Question {
                    validate_required_text(
                        "interaction prompt",
                        prompt,
                        PROVIDER_EVENT_TEXT_MAX_BYTES,
                    )?;
                } else {
                    validate_text("interaction prompt", prompt, PROVIDER_EVENT_TEXT_MAX_BYTES)?;
                }
                if options.len() > PROVIDER_INTERACTION_OPTIONS_MAX {
                    return Err(ProviderEventValidationError::TooManyInteractionOptions {
                        count: options.len(),
                        max: PROVIDER_INTERACTION_OPTIONS_MAX,
                    });
                }
                for option in options {
                    validate_required(
                        "interaction option id",
                        &option.option_id,
                        PROVIDER_EVENT_ID_MAX_BYTES,
                    )?;
                    validate_required(
                        "interaction option name",
                        &option.name,
                        PROVIDER_EVENT_ID_MAX_BYTES,
                    )?;
                    validate_required(
                        "interaction option kind",
                        &option.kind,
                        PROVIDER_EVENT_ID_MAX_BYTES,
                    )?;
                }
                validate_optional_agent_id(agent_id)?;
            }
            Self::InteractionResolved {
                request_id,
                outcome,
            } => {
                validate_required(
                    "interaction request id",
                    request_id,
                    PROVIDER_EVENT_ID_MAX_BYTES,
                )?;
                if !matches!(
                    outcome,
                    ProviderInteractionOutcome::Approved | ProviderInteractionOutcome::Denied
                ) {
                    return Err(
                        ProviderEventValidationError::InvalidInteractionResolutionOutcome {
                            outcome: *outcome,
                        },
                    );
                }
            }
            Self::SubagentStarted {
                agent_id,
                agent_type,
                description,
            } => {
                validate_required("subagent id", agent_id, PROVIDER_EVENT_ID_MAX_BYTES)?;
                if let Some(agent_type) = agent_type {
                    validate_identifier("subagent type", agent_type, PROVIDER_EVENT_ID_MAX_BYTES)?;
                }
                if let Some(description) = description {
                    validate_text(
                        "subagent description",
                        description,
                        PROVIDER_EVENT_TEXT_MAX_BYTES,
                    )?;
                }
            }
            Self::SubagentStopped { agent_id } => {
                validate_required("subagent id", agent_id, PROVIDER_EVENT_ID_MAX_BYTES)?;
            }
            Self::RateLimited {
                limit_type: _,
                resets_at,
                usage_percent,
                raw_message,
            } => {
                // `limit_type` is a typed enum now (`ProviderRateLimitKind`),
                // not a String -- it has no shape to validate here.
                for (field, value) in [
                    ("reset time", resets_at.as_deref()),
                    ("usage percent", usage_percent.as_deref()),
                ] {
                    if let Some(value) = value {
                        validate_identifier(field, value, PROVIDER_EVENT_ID_MAX_BYTES)?;
                    }
                }
                validate_text(
                    "rate limit message",
                    raw_message,
                    PROVIDER_EVENT_TEXT_MAX_BYTES,
                )?;
            }
            Self::HostRequestObserved {
                method,
                params_json,
                reason,
                outcome,
                ..
            } => {
                validate_required("host request method", method, PROVIDER_EVENT_ID_MAX_BYTES)?;
                validate_text(
                    "host request params",
                    params_json,
                    PROVIDER_EVENT_TEXT_MAX_BYTES,
                )?;
                if let Some(reason) = reason {
                    validate_text("host request reason", reason, PROVIDER_EVENT_TEXT_MAX_BYTES)?;
                }
                if let HostRequestOutcome::Failed { error } = outcome {
                    validate_text(
                        "host request outcome error",
                        error,
                        PROVIDER_EVENT_TEXT_MAX_BYTES,
                    )?;
                }
            }
            Self::UnrecognizedNotification {
                method,
                payload_json,
            } => {
                validate_required(
                    "unrecognized notification method",
                    method,
                    PROVIDER_EVENT_ID_MAX_BYTES,
                )?;
                validate_text(
                    "unrecognized notification payload",
                    payload_json,
                    PROVIDER_EVENT_TEXT_MAX_BYTES,
                )?;
            }
            Self::UserMessage { text, .. } => {
                validate_text("text", text, PROVIDER_EVENT_TEXT_MAX_BYTES)?;
            }
            Self::Plan { steps } => {
                if steps.len() > PROVIDER_PLAN_STEPS_MAX {
                    return Err(ProviderEventValidationError::TooManyPlanSteps {
                        count: steps.len(),
                        max: PROVIDER_PLAN_STEPS_MAX,
                    });
                }
                for step in steps {
                    validate_required_text(
                        "plan step content",
                        &step.content,
                        PROVIDER_EVENT_TEXT_MAX_BYTES,
                    )?;
                }
            }
            Self::AvailableCommandsUpdated { commands } => {
                if commands.len() > PROVIDER_AVAILABLE_COMMANDS_MAX {
                    return Err(ProviderEventValidationError::TooManyAvailableCommands {
                        count: commands.len(),
                        max: PROVIDER_AVAILABLE_COMMANDS_MAX,
                    });
                }
                for command in commands {
                    validate_required("command name", &command.name, PROVIDER_EVENT_ID_MAX_BYTES)?;
                    validate_text(
                        "command description",
                        &command.description,
                        PROVIDER_EVENT_TEXT_MAX_BYTES,
                    )?;
                    if let Some(hint) = &command.input_hint {
                        validate_text("command input hint", hint, PROVIDER_EVENT_TEXT_MAX_BYTES)?;
                    }
                }
            }
            Self::ModeChanged { mode_id, available } => {
                validate_required("mode id", mode_id, PROVIDER_EVENT_ID_MAX_BYTES)?;
                if available.len() > PROVIDER_MODE_CATALOG_MAX {
                    return Err(ProviderEventValidationError::TooManyModes {
                        count: available.len(),
                        max: PROVIDER_MODE_CATALOG_MAX,
                    });
                }
                for mode in available {
                    validate_required("available mode id", &mode.id, PROVIDER_EVENT_ID_MAX_BYTES)?;
                    validate_required(
                        "available mode name",
                        &mode.name,
                        PROVIDER_EVENT_ID_MAX_BYTES,
                    )?;
                    if let Some(description) = &mode.description {
                        validate_text(
                            "available mode description",
                            description,
                            PROVIDER_EVENT_TEXT_MAX_BYTES,
                        )?;
                    }
                }
            }
            Self::SessionInfoUpdated { title } => {
                if let Some(title) = title {
                    validate_text("session title", title, PROVIDER_EVENT_TEXT_MAX_BYTES)?;
                }
            }
            Self::UsageUpdated {
                cost_amount,
                cost_currency,
                ..
            } => {
                if let Some(amount) = cost_amount {
                    validate_identifier("usage cost amount", amount, PROVIDER_EVENT_ID_MAX_BYTES)?;
                }
                if let Some(currency) = cost_currency {
                    validate_identifier(
                        "usage cost currency",
                        currency,
                        PROVIDER_EVENT_ID_MAX_BYTES,
                    )?;
                }
            }
            Self::ConfigOptionsUpdated { options } => {
                if options.len() > PROVIDER_CONFIG_OPTIONS_MAX {
                    return Err(ProviderEventValidationError::TooManyConfigOptions {
                        count: options.len(),
                        max: PROVIDER_CONFIG_OPTIONS_MAX,
                    });
                }
                for option in options {
                    validate_required("config option id", &option.id, PROVIDER_EVENT_ID_MAX_BYTES)?;
                    validate_required(
                        "config option name",
                        &option.name,
                        PROVIDER_EVENT_ID_MAX_BYTES,
                    )?;
                    if let Some(description) = &option.description {
                        validate_text(
                            "config option description",
                            description,
                            PROVIDER_EVENT_TEXT_MAX_BYTES,
                        )?;
                    }
                    if let Some(category) = &option.category {
                        validate_identifier(
                            "config option category",
                            category,
                            PROVIDER_EVENT_ID_MAX_BYTES,
                        )?;
                    }
                    validate_text(
                        "config option value",
                        &option.value_json,
                        PROVIDER_EVENT_TEXT_MAX_BYTES,
                    )?;
                    if option.choices.len() > PROVIDER_CONFIG_OPTION_CHOICES_MAX {
                        return Err(ProviderEventValidationError::TooManyConfigOptionChoices {
                            count: option.choices.len(),
                            max: PROVIDER_CONFIG_OPTION_CHOICES_MAX,
                        });
                    }
                    for choice in &option.choices {
                        validate_text(
                            "config option choice value",
                            &choice.value_json,
                            PROVIDER_EVENT_TEXT_MAX_BYTES,
                        )?;
                        if let Some(label) = &choice.label {
                            validate_text(
                                "config option choice label",
                                label,
                                PROVIDER_EVENT_TEXT_MAX_BYTES,
                            )?;
                        }
                    }
                }
            }
            Self::WorkingObserved
            | Self::TurnCompleted { .. }
            | Self::TurnInterrupted
            | Self::Ready => {}
            Self::ContextWindowUsage { usage } => usage.validate()?,
        }
        Ok(())
    }
}

fn validate_required(
    field: &'static str,
    value: &str,
    max: usize,
) -> Result<(), ProviderEventValidationError> {
    if value.trim().is_empty() {
        return Err(ProviderEventValidationError::Empty { field });
    }
    validate_identifier(field, value, max)
}

fn validate_required_text(
    field: &'static str,
    value: &str,
    max: usize,
) -> Result<(), ProviderEventValidationError> {
    if value.trim().is_empty() {
        return Err(ProviderEventValidationError::Empty { field });
    }
    validate_text(field, value, max)
}

fn validate_identifier(
    field: &'static str,
    value: &str,
    max: usize,
) -> Result<(), ProviderEventValidationError> {
    if value.len() > max || value.chars().any(char::is_control) {
        return Err(ProviderEventValidationError::InvalidField { field, max });
    }
    Ok(())
}

fn validate_optional_agent_id(
    agent_id: &Option<String>,
) -> Result<(), ProviderEventValidationError> {
    if let Some(agent_id) = agent_id {
        validate_required("provider agent id", agent_id, PROVIDER_EVENT_ID_MAX_BYTES)?;
    }
    Ok(())
}

fn validate_text(
    field: &'static str,
    value: &str,
    max: usize,
) -> Result<(), ProviderEventValidationError> {
    let has_unsafe_control = value
        .chars()
        .any(|character| character.is_control() && !matches!(character, '\n' | '\r' | '\t'));
    if value.len() > max || has_unsafe_control {
        return Err(ProviderEventValidationError::InvalidField { field, max });
    }
    Ok(())
}

/// Bounds check for the `mode_id`/`option_id`/`model_id` an ACP session
/// control command (`ControlCommand::SetSessionMode`/
/// `SetSessionConfigOption`/`SetSessionModel`) carries -- the same bound as
/// any other provider-scoped id (`PROVIDER_EVENT_ID_MAX_BYTES`), required
/// and free of control characters. Mirrors what
/// `gate4agent-node-protocol`'s wire boundary already enforces
/// (`deserialize_acp_control_id`) before a command ever reaches
/// `gate4agent-engine`; re-checked here because a `ControlCommand` is
/// constructible directly (tests, other embedders), not only through that
/// one wire.
pub fn validate_session_control_id(
    field: &'static str,
    value: &str,
) -> Result<(), ProviderEventValidationError> {
    validate_required(field, value, PROVIDER_EVENT_ID_MAX_BYTES)
}

/// Bounds check for `ControlCommand::SetSessionConfigOption`'s
/// `value_json`: required, bounded the same as any other provider-scoped
/// free text (`PROVIDER_EVENT_TEXT_MAX_BYTES`), free of unsafe control
/// bytes. Mirrors `gate4agent-node-protocol`'s
/// `deserialize_acp_config_value_json` minus the JSON-parseability check --
/// this crate is a pure data contract and does not depend on `serde_json`,
/// so confirming the text actually parses is the shell executor's job
/// (`AcpSession::set_config_option` takes an already-parsed
/// `serde_json::Value`).
pub fn validate_session_config_value_json(
    value: &str,
) -> Result<(), ProviderEventValidationError> {
    validate_required_text(
        "session config option value",
        value,
        PROVIDER_EVENT_TEXT_MAX_BYTES,
    )
}

#[derive(Clone, Debug, Error, Eq, PartialEq)]
pub enum ProviderEventValidationError {
    #[error("provider event field '{field}' is required")]
    Empty { field: &'static str },
    #[error("provider event field '{field}' contains controls or exceeds {max} bytes")]
    InvalidField { field: &'static str, max: usize },
    #[error("provider event tool count {count} exceeds {max}")]
    TooManyTools { count: usize, max: usize },
    #[error("provider interaction resolution outcome {outcome:?} is not exact")]
    InvalidInteractionResolutionOutcome { outcome: ProviderInteractionOutcome },
    #[error("context-window capacity must be non-zero")]
    ZeroContextWindowCapacity,
    #[error("context-window token segments overflow u64")]
    ContextWindowSegmentsOverflow,
    #[error("context-window token segments sum to {segment_sum}, not used_tokens {used_tokens}")]
    ContextWindowSegmentsMismatch { segment_sum: u64, used_tokens: u64 },
    #[error("provider plan step count {count} exceeds {max}")]
    TooManyPlanSteps { count: usize, max: usize },
    #[error("provider available command count {count} exceeds {max}")]
    TooManyAvailableCommands { count: usize, max: usize },
    #[error("provider config option count {count} exceeds {max}")]
    TooManyConfigOptions { count: usize, max: usize },
    #[error("provider config option choice count {count} exceeds {max}")]
    TooManyConfigOptionChoices { count: usize, max: usize },
    #[error("provider mode catalog count {count} exceeds {max}")]
    TooManyModes { count: usize, max: usize },
    #[error("provider interaction option count {count} exceeds {max}")]
    TooManyInteractionOptions { count: usize, max: usize },
}

#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
pub struct ProviderSource {
    pub family: AdapterFamily,
    pub binding: AdapterBinding,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct ProviderSourceCursor {
    pub source: ProviderSource,
    pub sequence: u64,
    pub gap_count: u64,
    pub stale: bool,
}

#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
#[serde(transparent)]
pub struct ProviderInteractionId(pub u64);

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct ProviderInteractionTarget {
    pub interaction_id: ProviderInteractionId,
    pub source: ProviderSource,
    pub provider_request_id: Option<String>,
    pub interaction_kind: ProviderInteractionKind,
    pub tool_name: String,
    pub agent_id: Option<String>,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "kebab-case")]
pub enum ProviderInteractionStatus {
    Pending,
    Resolving {
        operation_id: OperationId,
        response_kind: ProviderInteractionResponseKind,
    },
    Resolved {
        outcome: ProviderInteractionOutcome,
    },
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct ProviderInteraction {
    pub id: ProviderInteractionId,
    pub source: ProviderSource,
    pub provider_request_id: Option<String>,
    pub interaction_kind: ProviderInteractionKind,
    pub tool_name: String,
    pub prompt: String,
    pub agent_id: Option<String>,
    pub resume_lead_activity: Option<ProviderActivity>,
    pub status: ProviderInteractionStatus,
}

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum ProviderActivity {
    #[default]
    Idle,
    Working,
    WaitingForInput,
    Blocked,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct ActiveProviderTool {
    pub id: String,
    pub name: String,
    pub input_json: String,
}

#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
pub struct ProviderSnapshot {
    pub sequence: u64,
    pub session: Option<ProviderSessionIdentity>,
    pub model: Option<String>,
    pub tools: Vec<String>,
    pub completed_turns: u64,
    pub usage: TokenUsage,
    pub lead_activity: ProviderActivity,
    pub activity: ProviderActivity,
    pub current_prompt: Option<String>,
    pub active_tools: Vec<ActiveProviderTool>,
    pub interactions: Vec<ProviderInteraction>,
    pub subagents: Vec<ProviderSubagent>,
    pub sources: Vec<ProviderSourceCursor>,
    pub last_event: Option<ProviderEvent>,
    pub gap_count: u64,
    pub stale: bool,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct ControlSnapshot {
    pub revision: u64,
    pub health: ControlHealth,
    pub sessions: Vec<SessionSnapshot>,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct ControlHealth {
    pub operation_id_exhausted: bool,
    pub event_sequence_exhausted: bool,
    pub revision_exhausted: bool,
    pub provider_sequence_exhausted_sessions: u32,
    pub retained_instance_identities: u32,
    pub retained_instance_identity_capacity: u32,
}

impl Default for ControlHealth {
    fn default() -> Self {
        Self {
            operation_id_exhausted: false,
            event_sequence_exhausted: false,
            revision_exhausted: false,
            provider_sequence_exhausted_sessions: 0,
            retained_instance_identities: 0,
            retained_instance_identity_capacity: CONTROL_INSTANCE_IDENTITIES_CAPACITY,
        }
    }
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct ControlEvent {
    pub sequence: u64,
    pub command_id: Option<CommandId>,
    pub instance_id: AgentInstanceId,
    pub generation: SessionGeneration,
    pub event: ControlEventKind,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "kebab-case")]
pub enum ControlEventKind {
    CommandRejected {
        message: String,
    },
    Registered,
    StartRequested {
        operation_id: OperationId,
    },
    Running {
        process_id: Option<u32>,
    },
    StopRequested {
        operation_id: OperationId,
        force: bool,
    },
    InputRequested {
        operation_id: OperationId,
        input_kind: PreparedInputKind,
    },
    InputCompleted {
        input_kind: PreparedInputKind,
    },
    InputFailed {
        input_kind: PreparedInputKind,
        message: String,
    },
    ResizeRequested {
        operation_id: OperationId,
        size: TerminalSize,
    },
    Resized {
        size: TerminalSize,
    },
    ResizeFailed {
        message: String,
    },
    ForegroundRefreshRequested {
        operation_id: OperationId,
    },
    ForegroundObserved {
        process: ForegroundProcess,
    },
    ForegroundFailed {
        message: String,
    },
    CapabilityProbeRequested {
        operation_id: OperationId,
    },
    CapabilitiesProbed {
        count: usize,
    },
    CapabilityProbeFailed {
        failure: CapabilityProbeFailure,
    },
    HistoryRequested {
        operation_id: OperationId,
        operation: HistoryOperation,
    },
    HistoryDiscovered {
        count: usize,
    },
    HistoryLoaded {
        session_id: String,
    },
    HistoryFailed {
        message: String,
    },
    ResumeRequested {
        operation_id: OperationId,
        target: ResumeTarget,
    },
    ResumeAuthorized {
        session: ResumeSessionSummary,
    },
    Resumed {
        session: ResumeSessionSummary,
        process_id: Option<u32>,
    },
    ResumeDenied {
        reason: String,
    },
    ResumeFailed {
        message: String,
    },
    TerminalStale {
        message: String,
    },
    ProviderEvent {
        sequence: u64,
        source: ProviderSource,
        source_sequence: u64,
        event: ProviderEvent,
    },
    ProviderGap {
        sequence: u64,
        source: ProviderSource,
        source_sequence: u64,
        missed: u64,
    },
    InteractionRequested {
        interaction: ProviderInteraction,
    },
    InteractionResolutionRequested {
        operation_id: OperationId,
        interaction_id: ProviderInteractionId,
        response_kind: ProviderInteractionResponseKind,
    },
    InteractionResolutionFailed {
        interaction_id: ProviderInteractionId,
        message: String,
    },
    InteractionResolved {
        interaction_id: ProviderInteractionId,
        outcome: ProviderInteractionOutcome,
    },
    SessionModeSetRequested {
        operation_id: OperationId,
        mode_id: String,
    },
    SessionModeSet {
        mode_id: String,
    },
    SessionModeSetFailed {
        message: String,
    },
    SessionConfigOptionSetRequested {
        operation_id: OperationId,
        option_id: String,
    },
    SessionConfigOptionSet {
        option_id: String,
    },
    SessionConfigOptionSetFailed {
        message: String,
    },
    SessionModelSetRequested {
        operation_id: OperationId,
        model_id: String,
    },
    SessionModelSet {
        model_id: String,
    },
    SessionModelSetFailed {
        message: String,
    },
    Exited {
        exit_code: Option<i32>,
        forced: bool,
    },
    Failed {
        message: String,
    },
    Removed,
    ObservationIgnored {
        reason: ObservationIgnoredReason,
    },
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum ObservationIgnoredReason {
    UnknownInstance,
    StaleGeneration,
    GenerationExhausted,
    MissingOperation,
    OperationMismatch,
    InvalidState,
    StaleTerminalFrame,
    StaleProviderEvent,
    InvalidForegroundObservation,
    InvalidCapabilityObservation,
    InvalidHistoryObservation,
    InvalidResumeObservation,
    InvalidInteractionObservation,
    ProviderRuntimePolicyDenied {
        capability: ProviderRuntimeCapability,
    },
}

#[derive(Clone, Debug, Eq, Error, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "kebab-case")]
pub enum ControlError {
    #[error("agent instance {instance_id:?} is already registered")]
    DuplicateInstance { instance_id: AgentInstanceId },
    #[error(
        "cannot register agent instance {instance_id:?}: live session capacity {max} is exhausted"
    )]
    SessionCapacityExceeded {
        instance_id: AgentInstanceId,
        max: usize,
    },
    #[error(
        "cannot register agent instance {instance_id:?}: retained identity capacity {max} is exhausted"
    )]
    InstanceIdentityCapacityExceeded {
        instance_id: AgentInstanceId,
        max: usize,
    },
    #[error("agent instance {instance_id:?} is not registered")]
    UnknownInstance { instance_id: AgentInstanceId },
    #[error("agent instance {instance_id:?} exhausted session generation {generation:?}")]
    GenerationExhausted {
        instance_id: AgentInstanceId,
        generation: SessionGeneration,
    },
    #[error("control operation identifiers are exhausted")]
    OperationIdExhausted,
    #[error("control event sequences are exhausted")]
    EventSequenceExhausted,
    #[error("control snapshot revisions are exhausted")]
    RevisionExhausted,
    #[error(
        "agent instance {instance_id:?} generation {generation:?} exhausted provider event sequences"
    )]
    ProviderSequenceExhausted {
        instance_id: AgentInstanceId,
        generation: SessionGeneration,
    },
    #[error(
        "agent instance {instance_id:?} generation {generation:?} exhausted source sequence for {provider_source:?}"
    )]
    ProviderSourceSequenceExhausted {
        instance_id: AgentInstanceId,
        generation: SessionGeneration,
        provider_source: ProviderSource,
    },
    #[error("agent instance {instance_id:?} already has pending operation {operation_id:?}")]
    OperationPending {
        instance_id: AgentInstanceId,
        operation_id: OperationId,
    },
    #[error("agent input was rejected: {error}")]
    InputRejected { error: InputPrepareError },
    #[error("provider runtime policy is invalid: {error}")]
    InvalidProviderRuntimePolicy { error: ProviderRuntimePolicyError },
    #[error("provider runtime capability {capability:?} is not admitted")]
    ProviderRuntimePolicyDenied {
        capability: ProviderRuntimeCapability,
    },
    #[error("terminal size is outside the supported bounded range")]
    InvalidTerminalSize,
    #[error("working directory is empty, too large, or contains a NUL byte")]
    InvalidWorkingDirectory,
    #[error("pipe transport requires a non-empty initial prompt")]
    MissingInitialPrompt,
    #[error("session options are invalid: {message}")]
    InvalidSessionOptions { message: String },
    #[error("capability probe request is invalid: {message}")]
    InvalidCapabilityProbeRequest { message: String },
    #[error("capability probe operation {operation_id:?} is already pending")]
    CapabilityProbeOperationPending { operation_id: OperationId },
    #[error("capability probe already settled for this agent instance")]
    CapabilityProbeSettled,
    #[error("history request is invalid: {message}")]
    InvalidHistoryRequest { message: String },
    #[error("history operation {operation_id:?} is already pending")]
    HistoryOperationPending { operation_id: OperationId },
    #[error("history candidate is not present in the current discovery snapshot")]
    UnknownHistoryCandidate,
    #[error("resume request is invalid: {message}")]
    InvalidResumeRequest { message: String },
    #[error("resume requires a canonical provider session identity")]
    MissingProviderSession,
    #[error("resume history candidate must be the currently loaded candidate")]
    HistoryCandidateNotLoaded,
    #[error("transport {transport:?} does not support {action}")]
    UnsupportedTransportOperation {
        transport: TransportKind,
        action: String,
    },
    #[error("agent instance {instance_id:?} cannot {action} while in state {status:?}")]
    InvalidTransition {
        instance_id: AgentInstanceId,
        action: String,
        status: SessionStatus,
    },
    #[error("provider ingress generation {actual:?} is stale; expected {expected:?}")]
    StaleProviderGeneration {
        expected: SessionGeneration,
        actual: SessionGeneration,
    },
    #[error("provider ingress source sequence must be greater than the current sequence")]
    StaleProviderSequence,
    #[error("provider ingress batch must contain between 1 and {max} events")]
    InvalidProviderBatch { max: usize },
    #[error("invalid provider ingress event: {message}")]
    InvalidProviderEvent { message: String },
    #[error("provider interaction generation {actual:?} is stale; expected {expected:?}")]
    StaleProviderInteractionGeneration {
        expected: SessionGeneration,
        actual: SessionGeneration,
    },
    #[error("provider interaction {interaction_id:?} is unknown")]
    UnknownProviderInteraction {
        interaction_id: ProviderInteractionId,
    },
    #[error("provider interaction {interaction_id:?} is not pending")]
    ProviderInteractionNotPending {
        interaction_id: ProviderInteractionId,
    },
    #[error("provider interaction response is invalid: {message}")]
    InvalidProviderInteractionResponse { message: String },
    #[error("session mode request is invalid: {message}")]
    InvalidSessionModeRequest { message: String },
    #[error("session config option request is invalid: {message}")]
    InvalidSessionConfigOptionRequest { message: String },
    #[error("session model request is invalid: {message}")]
    InvalidSessionModelRequest { message: String },
}

impl Default for ControlSnapshot {
    fn default() -> Self {
        Self {
            revision: 0,
            health: ControlHealth::default(),
            sessions: Vec::new(),
        }
    }
}

#[cfg(test)]
mod tests {

    /// The split `SessionStatus::allows_remove` draws, stated once so the
    /// two crates that consult it (`gate4agent-engine`'s own `remove`
    /// guard, `gate4agent-node`'s `wait_until_removed` re-dispatch gate)
    /// are pinned to the same answer.
    ///
    /// The three live statuses refuse: a session that is starting, running
    /// or stopping still owns a process. The three settled ones allow. The
    /// node's retry loop reads this BEFORE dispatching, because a rejected
    /// `Remove` fans a `CommandRejected` out to every subscriber -- 241 of
    /// them in 1.6 seconds when the loop dispatched blind.
    #[test]
    fn only_a_settled_session_admits_a_remove() {
        use crate::SessionStatus;

        for live in [
            SessionStatus::Starting,
            SessionStatus::Running,
            SessionStatus::Stopping,
        ] {
            assert!(
                !live.allows_remove(),
                "{live:?} still owns a process; a Remove for it is rejected",
            );
        }
        for settled in [
            SessionStatus::Registered,
            SessionStatus::Exited { exit_code: Some(0) },
            SessionStatus::Exited { exit_code: None },
            SessionStatus::Failed { message: "boom".to_owned() },
        ] {
            assert!(
                settled.allows_remove(),
                "{settled:?} is settled; a Remove for it must be accepted",
            );
        }
    }

    use crate::AgentId;
    use super::{
        AgentInstanceId, CapabilitySnapshot, ContextWindowUsage, ForegroundProcess,
        ForegroundProcessKind, ForegroundSnapshot, HistorySnapshot, HostDecisionAuthority,
        HostRequestDecision, HostRequestOutcome, OperatorGateInput,
        OperatorGateKind, OperatorGateOption, OperatorGateOptionSemantics, OperatorGateState,
        OperatorGateSubject, ProviderAvailableCommand, ProviderConfigChoice, ProviderConfigOption,
        ProviderConfigOptionKind, ProviderEvent,
        ProviderEventValidationError,
        ProviderInteractionKind, ProviderInteractionOption, ProviderInteractionOutcome,
        ProviderInteractionResponse,
        ProviderInteractionResponseError, ProviderModeInfo, ProviderPlanPriority,
        ProviderPlanStatus,
        ProviderPlanStep, ProviderRuntimeCapability, ProviderRuntimePolicy,
        ProviderRuntimePolicyError,
        ProviderSessionIdentity, ProviderSessionKey, ProviderSnapshot, PtyScreenState,
        ResumeSnapshot, SessionGeneration, SessionSnapshot, SessionStatus, TerminalFrame,
        TerminalMouseProtocolEncoding, TransportKind,
        FOREGROUND_PROCESS_NAME_MAX_BYTES, OPERATOR_GATE_OPTIONS_MAX,
        OPERATOR_GATE_OPTION_TEXT_MAX_BYTES, OPERATOR_GATE_PATH_MAX_BYTES,
        PROVIDER_AVAILABLE_COMMANDS_MAX,
        PROVIDER_EVENT_ID_MAX_BYTES, PROVIDER_EVENT_TEXT_MAX_BYTES,
        PROVIDER_INTERACTION_OPTIONS_MAX, PROVIDER_INTERACTION_RESPONSE_MAX_BYTES,
        PROVIDER_MODE_CATALOG_MAX,
        PROVIDER_PLAN_STEPS_MAX,
        PTY_SCREEN_GATE_NAME_MAX_BYTES,
    };

    /// Shared fixture: a fully-known gate (every field populated), used by
    /// every test below that needs "some real `OperatorGateState`" without
    /// re-deriving one -- one option accepted, one declined, matching the
    /// shape `parse_operator_gate_options` actually produces for a numbered
    /// list (see `gate4agent-shell-native`'s own tests for the parser
    /// itself; this crate only owns the data shape and its bounds).
    fn sample_gate() -> OperatorGateState {
        OperatorGateState::new(OperatorGateKind::HookTrust)
            .with_subject(OperatorGateSubject::Hooks { count: Some(6) })
            .with_options(
                OperatorGateInput::NumberedList,
                vec![
                    OperatorGateOption {
                        text: "Trust all and continue".to_owned(),
                        semantics: OperatorGateOptionSemantics::Accept,
                        selected: false,
                    },
                    OperatorGateOption {
                        text: "Continue without trusting".to_owned(),
                        semantics: OperatorGateOptionSemantics::Decline,
                        selected: true,
                    },
                ],
            )
    }

    #[test]
    fn context_window_usage_ingress_requires_exact_bounded_segments() {
        let event = |usage| ProviderEvent::ContextWindowUsage { usage };
        let valid = ContextWindowUsage {
            uncached_input_tokens: 70,
            cache_read_tokens: 20,
            cache_write_tokens: 0,
            output_tokens: 10,
            unattributed_tokens: 5,
            used_tokens: 105,
            capacity_tokens: 100,
        };
        assert_eq!(event(valid).validate_ingress(), Ok(()));
        assert_eq!(
            event(ContextWindowUsage { capacity_tokens: 0, ..valid }).validate_ingress(),
            Err(ProviderEventValidationError::ZeroContextWindowCapacity)
        );
        assert_eq!(
            event(ContextWindowUsage { used_tokens: 104, ..valid }).validate_ingress(),
            Err(ProviderEventValidationError::ContextWindowSegmentsMismatch {
                segment_sum: 105,
                used_tokens: 104,
            })
        );
        assert_eq!(
            event(ContextWindowUsage {
                uncached_input_tokens: u64::MAX,
                cache_read_tokens: 1,
                cache_write_tokens: 0,
                output_tokens: 0,
                unattributed_tokens: 0,
                used_tokens: u64::MAX,
                capacity_tokens: 1,
            })
            .validate_ingress(),
            Err(ProviderEventValidationError::ContextWindowSegmentsOverflow)
        );
    }

    #[test]
    fn provider_runtime_policy_enforces_semantic_invariants() {
        let raw = ProviderRuntimePolicy::raw_pty();
        assert!(raw.admits(ProviderRuntimeCapability::RawPtyLifecycle));
        assert!(!raw.admits(ProviderRuntimeCapability::SemanticReadiness));
        assert!(!raw.admits(ProviderRuntimeCapability::HookSemantics));
        assert_eq!(raw.validate(), Ok(()));

        let none = ProviderRuntimePolicy::none();
        assert!(!none.admits(ProviderRuntimeCapability::RawPtyLifecycle));
        assert!(!none.admits(ProviderRuntimeCapability::SemanticReadiness));
        assert_eq!(none.validate(), Ok(()));

        // The ACP shape: `session/prompt`/`session/update` are mandatory ACP
        // protocol surface, and `session/new` returns a `sessionId` under
        // that same specification -- none of it a PTY-terminal-text
        // inference, so this transport grants `semantic_readiness`/
        // `structured_prompt`/`provider_session_identity` with no raw PTY
        // lifecycle at all, and that is now a VALID policy, not the
        // `SemanticCapabilityRequiresRawPty` defect it used to be.
        assert_eq!(
            ProviderRuntimePolicy::new(false, true, true, true, false, false),
            Ok(ProviderRuntimePolicy {
                raw_pty_lifecycle: false,
                semantic_readiness: true,
                structured_prompt: true,
                provider_session_identity: true,
                semantic_resume: false,
                hook_semantics: false,
            }),
        );
        // `structured_prompt` still requires `semantic_readiness`, and that
        // rule holds independent of `raw_pty_lifecycle` -- it is not the rule
        // the ACP shape above loosened.
        assert_eq!(
            ProviderRuntimePolicy::new(false, false, true, false, false, false),
            Err(ProviderRuntimePolicyError::StructuredPromptRequiresReadiness),
        );
        assert_eq!(
            ProviderRuntimePolicy::new(true, false, true, false, false, false),
            Err(ProviderRuntimePolicyError::StructuredPromptRequiresReadiness),
        );
        assert_eq!(
            ProviderRuntimePolicy::new(true, true, true, false, true, false),
            Err(ProviderRuntimePolicyError::ResumeRequiresSessionIdentity),
        );
        assert_eq!(
            ProviderRuntimePolicy::new(false, false, false, false, false, true),
            Err(ProviderRuntimePolicyError::SemanticCapabilityRequiresRawPty),
        );
        // Granting `semantic_readiness`/`structured_prompt`/
        // `provider_session_identity` without a raw PTY lifecycle (the ACP
        // shape) must NOT silently unlock `semantic_resume`/`hook_semantics`
        // -- those two keep the old, stricter rule, even with every other
        // field in the ACP shape already granted.
        assert_eq!(
            ProviderRuntimePolicy::new(false, true, true, true, true, false),
            Err(ProviderRuntimePolicyError::SemanticCapabilityRequiresRawPty),
        );
        assert_eq!(
            ProviderRuntimePolicy::new(false, true, true, true, false, true),
            Err(ProviderRuntimePolicyError::SemanticCapabilityRequiresRawPty),
        );
        assert!(ProviderRuntimePolicy::new(true, true, true, true, true, true).is_ok());
    }

    /// The pair that makes hook ingestion work for a provider like grok: a
    /// hook adapter with no verified vendor terminal contract still admits
    /// its own events, and that admission never leaks into the PTY-parsing
    /// `SemanticReadiness` capability it is deliberately independent from.
    #[test]
    fn hook_semantics_and_semantic_readiness_are_independently_grantable() {
        let hook_only = ProviderRuntimePolicy::new(true, false, false, false, false, true)
            .expect("hook semantics alone requires only the raw PTY lifecycle");
        assert!(hook_only.admits(ProviderRuntimeCapability::HookSemantics));
        assert!(!hook_only.admits(ProviderRuntimeCapability::SemanticReadiness));

        let semantic_only = ProviderRuntimePolicy::new(true, true, false, false, false, false)
            .expect("semantic readiness alone requires only the raw PTY lifecycle");
        assert!(semantic_only.admits(ProviderRuntimeCapability::SemanticReadiness));
        assert!(!semantic_only.admits(ProviderRuntimeCapability::HookSemantics));
    }

    #[test]
    fn provider_runtime_policy_serde_requires_every_field_and_revalidates() {
        let raw = ProviderRuntimePolicy::raw_pty();
        let encoded = serde_json::to_string(&raw).unwrap();
        assert_eq!(
            encoded,
            r#"{"raw_pty_lifecycle":true,"semantic_readiness":false,"structured_prompt":false,"provider_session_identity":false,"semantic_resume":false,"hook_semantics":false}"#,
        );
        assert_eq!(
            serde_json::from_str::<ProviderRuntimePolicy>(&encoded).unwrap(),
            raw,
        );
        assert!(serde_json::from_str::<ProviderRuntimePolicy>(
            r#"{"raw_pty_lifecycle":true,"semantic_readiness":false,"structured_prompt":false,"provider_session_identity":false,"semantic_resume":false}"#,
        )
        .is_err());
        assert!(serde_json::from_str::<ProviderRuntimePolicy>(
            r#"{"raw_pty_lifecycle":true,"semantic_readiness":false,"structured_prompt":true,"provider_session_identity":false,"semantic_resume":false,"hook_semantics":false}"#,
        )
        .is_err());
        assert!(serde_json::from_str::<super::ControlCommand>(
            r#"{"kind":"start","instance_id":1,"request":{"working_directory":"C:\\repo","terminal_size":{"rows":24,"columns":80}}}"#,
        )
        .is_err());
        assert!(serde_json::from_str::<super::ControlEffect>(
            r#"{"kind":"spawn","agent_id":"claude","transport":"pty","request":{"working_directory":"C:\\repo","terminal_size":{"rows":24,"columns":80}}}"#,
        )
        .is_err());
    }

    #[test]
    fn foreground_process_is_bounded_and_agent_bound() {
        let claude = AgentId::new("claude").unwrap();
        let process = ForegroundProcess {
            root_process_id: 1,
            process_id: 2,
            process_name: "claude".to_owned(),
            kind: ForegroundProcessKind::Agent {
                agent_id: claude.clone(),
            },
        };
        assert!(process.is_valid_for(&claude));
        assert!(!process.is_valid_for(&AgentId::new("codex").unwrap()));
        assert!(!ForegroundProcess {
            process_name: "x".repeat(FOREGROUND_PROCESS_NAME_MAX_BYTES + 1),
            ..process
        }
        .is_valid_for(&claude));
    }

    #[test]
    fn terminal_frame_metadata_defaults_for_older_serialized_frames() {
        let frame: TerminalFrame = serde_json::from_str(
            r#"{"sequence":1,"size":{"rows":24,"columns":80},"cursor_row":0,"cursor_column":0,"contents":"ready","formatted":[114]}"#,
        )
        .expect("legacy terminal frame");

        assert!(frame.scrollback_formatted.is_empty());
        assert!(!frame.alternate_screen);
        assert!(!frame.mouse_protocol_enabled);
        assert_eq!(frame.mouse_protocol_encoding, TerminalMouseProtocolEncoding::Default);
        assert_eq!(frame.produced_at_unix_ms, 0);
    }

    #[test]
    fn a_terminal_frame_that_omits_screen_state_decodes_as_unknown_not_ready() {
        let frame: TerminalFrame = serde_json::from_str(
            r#"{"sequence":1,"size":{"rows":24,"columns":80},"cursor_row":0,"cursor_column":0,"contents":"ready","formatted":[114]}"#,
        )
        .expect("legacy terminal frame");

        assert_eq!(frame.screen_state, PtyScreenState::Unknown);
        // A peer that predates this field carries no classification at all --
        // reading that silence as `Ready` would hand a blind writer a green
        // light nobody ever actually gave.
        assert_ne!(frame.screen_state, PtyScreenState::Ready);
    }

    #[test]
    fn a_session_snapshot_that_omits_screen_state_decodes_as_unknown_not_ready() {
        let populated = SessionSnapshot {
            instance_id: AgentInstanceId(1),
            agent_id: AgentId::new("claude").unwrap(),
            transport: TransportKind::Pty,
            generation: SessionGeneration(1),
            status: SessionStatus::Running,
            pending_operation: None,
            pending_input: None,
            process_id: None,
            terminal_size: None,
            terminal_frame: None,
            terminal_stale: None,
            session_options: None,
            capabilities: CapabilitySnapshot::default(),
            history: HistorySnapshot::default(),
            resume: ResumeSnapshot::default(),
            foreground: ForegroundSnapshot::default(),
            provider: ProviderSnapshot::default(),
            screen_state: PtyScreenState::Ready,
        };
        let mut wire = serde_json::to_value(&populated).unwrap();
        wire.as_object_mut().unwrap().remove("screen_state");
        let decoded: SessionSnapshot = serde_json::from_value(wire).unwrap();

        assert_eq!(decoded.screen_state, PtyScreenState::Unknown);
        // Same reasoning as the terminal-frame case: an old peer's silence
        // on this field must never be upgraded into a claim it never made.
        assert_ne!(decoded.screen_state, PtyScreenState::Ready);
    }

    #[test]
    fn every_pty_screen_state_variant_round_trips_through_serde() {
        let variants = [
            PtyScreenState::Unknown,
            PtyScreenState::NotAgent {
                observed_process: "npm".to_owned(),
            },
            PtyScreenState::OperatorGate { gate: sample_gate() },
            PtyScreenState::Failing {
                reason: "startup-crash".to_owned(),
            },
            PtyScreenState::Ready,
        ];
        for variant in variants {
            let json = serde_json::to_string(&variant).unwrap();
            assert_eq!(
                serde_json::from_str::<PtyScreenState>(&json).unwrap(),
                variant,
            );
        }
    }

    /// Refusal follows a FINDING, not the absence of one. The three states
    /// that carry something the matcher actually read still refuse; `Ready`
    /// and `Unknown` both admit, because "recognized nothing" is not a
    /// reason to treat a screen as an obstacle -- and every provider sits in
    /// `Unknown` for the frame or two before process identity resolves,
    /// which is not a state worth refusing.
    #[test]
    fn admits_blind_write_refuses_a_finding_and_admits_the_absence_of_one() {
        assert!(PtyScreenState::Ready.admits_blind_write());
        assert!(PtyScreenState::Unknown.admits_blind_write());
        assert!(!PtyScreenState::NotAgent {
            observed_process: "npm".to_owned(),
        }
        .admits_blind_write());
        assert!(!PtyScreenState::OperatorGate { gate: sample_gate() }.admits_blind_write());
        assert!(!PtyScreenState::Failing {
            reason: "startup-crash".to_owned(),
        }
        .admits_blind_write());
    }

    #[test]
    fn pty_screen_state_is_valid_rejects_oversized_empty_and_control_carrying_fields() {
        assert!(PtyScreenState::NotAgent {
            observed_process: "npm install".to_owned(),
        }
        .is_valid());
        assert!(!PtyScreenState::NotAgent {
            observed_process: "x".repeat(FOREGROUND_PROCESS_NAME_MAX_BYTES + 1),
        }
        .is_valid());
        assert!(!PtyScreenState::NotAgent {
            observed_process: String::new(),
        }
        .is_valid());
        assert!(!PtyScreenState::NotAgent {
            observed_process: "bad\u{0000}process".to_owned(),
        }
        .is_valid());

        assert!(PtyScreenState::OperatorGate { gate: sample_gate() }.is_valid());
        assert!(!PtyScreenState::OperatorGate {
            gate: sample_gate().with_subject(OperatorGateSubject::Directory {
                path: Some("x".repeat(OPERATOR_GATE_PATH_MAX_BYTES + 1)),
            }),
        }
        .is_valid());
        assert!(!PtyScreenState::OperatorGate {
            gate: sample_gate().with_subject(OperatorGateSubject::Directory {
                path: Some(String::new()),
            }),
        }
        .is_valid());
        assert!(!PtyScreenState::OperatorGate {
            gate: sample_gate().with_subject(OperatorGateSubject::Directory {
                path: Some("bad\u{0000}path".to_owned()),
            }),
        }
        .is_valid());
        assert!(!PtyScreenState::OperatorGate {
            gate: sample_gate().with_options(
                OperatorGateInput::NumberedList,
                vec![OperatorGateOption {
                    text: "x".repeat(OPERATOR_GATE_OPTION_TEXT_MAX_BYTES + 1),
                    semantics: OperatorGateOptionSemantics::Accept,
                    selected: false,
                }],
            ),
        }
        .is_valid());
        assert!(!PtyScreenState::OperatorGate {
            gate: sample_gate().with_options(
                OperatorGateInput::NumberedList,
                vec![OperatorGateOption {
                    text: String::new(),
                    semantics: OperatorGateOptionSemantics::Accept,
                    selected: false,
                }],
            ),
        }
        .is_valid());
        assert!(!PtyScreenState::OperatorGate {
            gate: sample_gate().with_options(
                OperatorGateInput::NumberedList,
                vec![OperatorGateOption {
                    text: "bad\u{0000}option".to_owned(),
                    semantics: OperatorGateOptionSemantics::Accept,
                    selected: false,
                }],
            ),
        }
        .is_valid());
        assert!(!PtyScreenState::OperatorGate {
            gate: sample_gate().with_options(
                OperatorGateInput::NumberedList,
                (0..=OPERATOR_GATE_OPTIONS_MAX)
                    .map(|index| OperatorGateOption {
                        text: format!("option {index}"),
                        semantics: OperatorGateOptionSemantics::Unknown,
                        selected: false,
                    })
                    .collect(),
            ),
        }
        .is_valid());

        assert!(PtyScreenState::Failing {
            reason: "startup-crash".to_owned(),
        }
        .is_valid());
        assert!(!PtyScreenState::Failing {
            reason: "x".repeat(PTY_SCREEN_GATE_NAME_MAX_BYTES + 1),
        }
        .is_valid());
        assert!(!PtyScreenState::Failing {
            reason: String::new(),
        }
        .is_valid());
        assert!(!PtyScreenState::Failing {
            reason: "bad\u{0000}reason".to_owned(),
        }
        .is_valid());

        assert!(PtyScreenState::Unknown.is_valid());
        assert!(PtyScreenState::Ready.is_valid());
    }

    #[test]
    fn provider_interactions_require_bounded_identity_and_question_payloads() {
        let question = ProviderEvent::InteractionRequested {
            request_id: Some("question-1".to_owned()),
            interaction_kind: ProviderInteractionKind::Question,
            tool_name: "AskUserQuestion".to_owned(),
            title: Some("Continue?".to_owned()),
            prompt: "{\"question\":\"Continue?\"}".to_owned(),
            options: vec![ProviderInteractionOption {
                option_id: "yes".to_owned(),
                name: "Yes".to_owned(),
                kind: "allow_once".to_owned(),
            }],
            agent_id: Some("child-1".to_owned()),
        };
        assert_eq!(question.validate_ingress(), Ok(()));

        assert!(matches!(
            ProviderEvent::InteractionRequested {
                request_id: Some("bad\nrequest".to_owned()),
                interaction_kind: ProviderInteractionKind::Approval,
                tool_name: "shell".to_owned(),
                title: None,
                prompt: String::new(),
                options: Vec::new(),
                agent_id: None,
            }
            .validate_ingress(),
            Err(ProviderEventValidationError::InvalidField {
                field: "interaction request id",
                ..
            })
        ));
        assert!(matches!(
            ProviderEvent::InteractionRequested {
                request_id: None,
                interaction_kind: ProviderInteractionKind::Question,
                tool_name: "AskUserQuestion".to_owned(),
                title: None,
                prompt: String::new(),
                options: Vec::new(),
                agent_id: None,
            }
            .validate_ingress(),
            Err(ProviderEventValidationError::Empty {
                field: "interaction prompt"
            })
        ));
        assert!(matches!(
            ProviderEvent::InteractionRequested {
                request_id: None,
                interaction_kind: ProviderInteractionKind::Approval,
                tool_name: "shell".to_owned(),
                title: None,
                prompt: String::new(),
                options: (0..PROVIDER_INTERACTION_OPTIONS_MAX + 1)
                    .map(|index| ProviderInteractionOption {
                        option_id: format!("option-{index}"),
                        name: format!("Option {index}"),
                        kind: "allow_once".to_owned(),
                    })
                    .collect(),
                agent_id: None,
            }
            .validate_ingress(),
            Err(ProviderEventValidationError::TooManyInteractionOptions {
                max: PROVIDER_INTERACTION_OPTIONS_MAX,
                ..
            })
        ));

        for outcome in [
            ProviderInteractionOutcome::Approved,
            ProviderInteractionOutcome::Denied,
        ] {
            assert_eq!(
                ProviderEvent::InteractionResolved {
                    request_id: "approval-1".to_owned(),
                    outcome,
                }
                .validate_ingress(),
                Ok(())
            );
        }
        assert!(matches!(
            ProviderEvent::InteractionResolved {
                request_id: "bad\nrequest".to_owned(),
                outcome: ProviderInteractionOutcome::Approved,
            }
            .validate_ingress(),
            Err(ProviderEventValidationError::InvalidField {
                field: "interaction request id",
                ..
            })
        ));
        assert_eq!(
            ProviderEvent::InteractionResolved {
                request_id: "approval-1".to_owned(),
                outcome: ProviderInteractionOutcome::TurnEnded,
            }
            .validate_ingress(),
            Err(
                ProviderEventValidationError::InvalidInteractionResolutionOutcome {
                    outcome: ProviderInteractionOutcome::TurnEnded,
                }
            )
        );
    }

    #[test]
    fn provider_interaction_responses_are_kind_checked_and_bounded() {
        assert_eq!(
            ProviderInteractionResponse::ApproveOnce
                .validate_for(ProviderInteractionKind::Approval),
            Ok(())
        );
        assert_eq!(
            ProviderInteractionResponse::Deny.validate_for(ProviderInteractionKind::Question),
            Ok(())
        );
        assert_eq!(
            ProviderInteractionResponse::Answer {
                text: "continue".to_owned(),
            }
            .validate_for(ProviderInteractionKind::Question),
            Ok(())
        );
        assert_eq!(
            ProviderInteractionResponse::ApproveOnce
                .validate_for(ProviderInteractionKind::Question),
            Err(ProviderInteractionResponseError::ApprovalRequiresApproval)
        );
        assert_eq!(
            ProviderInteractionResponse::Answer {
                text: String::new(),
            }
            .validate_for(ProviderInteractionKind::Question),
            Err(ProviderInteractionResponseError::EmptyAnswer)
        );
        assert_eq!(
            ProviderInteractionResponse::Answer {
                text: "x".repeat(PROVIDER_INTERACTION_RESPONSE_MAX_BYTES + 1),
            }
            .validate_for(ProviderInteractionKind::Question),
            Err(ProviderInteractionResponseError::InvalidAnswer {
                max: PROVIDER_INTERACTION_RESPONSE_MAX_BYTES,
            })
        );
    }

    #[test]
    fn provider_ingress_allows_multiline_text_but_rejects_control_bytes() {
        ProviderEvent::Text {
            text: "first line\n\tsecond line".to_owned(),
            is_delta: false,
        }
        .validate_ingress()
        .unwrap();

        assert!(matches!(
            ProviderEvent::Text {
                text: "unsafe\u{0000}text".to_owned(),
                is_delta: false,
            }
            .validate_ingress(),
            Err(ProviderEventValidationError::InvalidField { field: "text", .. })
        ));
        assert!(ProviderEvent::SessionStarted {
            session_id: "session\nother".to_owned(),
            model: "model".to_owned(),
            tools: Vec::new(),
        }
        .validate_ingress()
        .is_err());
    }

    #[test]
    fn provider_session_identity_is_typed_and_bounded_at_ingress() {
        let valid = ProviderEvent::SessionIdentityObserved {
            identity: ProviderSessionIdentity {
                key: ProviderSessionKey::ConversationId,
                id: "conversation-1".to_owned(),
                transcript_path: Some("C:/sessions/conversation-1.jsonl".to_owned()),
            },
        };
        assert_eq!(valid.validate_ingress(), Ok(()));

        for identity in [
            ProviderSessionIdentity {
                key: ProviderSessionKey::SessionId,
                id: "--help".to_owned(),
                transcript_path: None,
            },
            ProviderSessionIdentity {
                key: ProviderSessionKey::SessionId,
                id: "session-1".to_owned(),
                transcript_path: Some("bad\npath".to_owned()),
            },
        ] {
            assert!(ProviderEvent::SessionIdentityObserved { identity }
                .validate_ingress()
                .is_err());
        }
    }

    /// The agent-to-host request event must carry a non-empty, bounded
    /// method and a bounded params payload -- the same shape and bounds as
    /// `ToolStarted`'s `id`/`input_json`, since this event carries the same
    /// kind of vendor-controlled JSON.
    #[test]
    fn host_request_observed_is_bounded_at_ingress() {
        let valid = ProviderEvent::HostRequestObserved {
            method: "session/request_permission".to_owned(),
            params_json: "{\"toolName\":\"bash\"}".to_owned(),
            decision: HostRequestDecision::Denied { by: HostDecisionAuthority::Policy },
            outcome: HostRequestOutcome::Executed,
            reason: Some("session/request_permission denied by host policy".to_owned()),
        };
        assert_eq!(valid.validate_ingress(), Ok(()));

        assert!(matches!(
            ProviderEvent::HostRequestObserved {
                method: String::new(),
                params_json: String::new(),
                decision: HostRequestDecision::Denied { by: HostDecisionAuthority::Policy },
                outcome: HostRequestOutcome::Executed,
                reason: None,
            }
            .validate_ingress(),
            Err(ProviderEventValidationError::Empty { field: "host request method" })
        ));

        let oversized_method = "m".repeat(PROVIDER_EVENT_ID_MAX_BYTES + 1);
        assert!(matches!(
            ProviderEvent::HostRequestObserved {
                method: oversized_method,
                params_json: String::new(),
                decision: HostRequestDecision::Granted { by: HostDecisionAuthority::Policy },
                outcome: HostRequestOutcome::Executed,
                reason: None,
            }
            .validate_ingress(),
            Err(ProviderEventValidationError::InvalidField {
                field: "host request method",
                ..
            })
        ));

        let oversized_params = "p".repeat(PROVIDER_EVENT_TEXT_MAX_BYTES + 1);
        assert!(matches!(
            ProviderEvent::HostRequestObserved {
                method: "fs/read_text_file".to_owned(),
                params_json: oversized_params,
                decision: HostRequestDecision::Granted { by: HostDecisionAuthority::Policy },
                outcome: HostRequestOutcome::Executed,
                reason: None,
            }
            .validate_ingress(),
            Err(ProviderEventValidationError::InvalidField {
                field: "host request params",
                ..
            })
        ));

        let oversized_reason = "r".repeat(PROVIDER_EVENT_TEXT_MAX_BYTES + 1);
        assert!(matches!(
            ProviderEvent::HostRequestObserved {
                method: "terminal/create".to_owned(),
                params_json: String::new(),
                decision: HostRequestDecision::Denied { by: HostDecisionAuthority::Gate },
                outcome: HostRequestOutcome::Executed,
                reason: Some(oversized_reason),
            }
            .validate_ingress(),
            Err(ProviderEventValidationError::InvalidField {
                field: "host request reason",
                ..
            })
        ));

        let oversized_error = "e".repeat(PROVIDER_EVENT_TEXT_MAX_BYTES + 1);
        assert!(matches!(
            ProviderEvent::HostRequestObserved {
                method: "terminal/create".to_owned(),
                params_json: String::new(),
                decision: HostRequestDecision::Granted { by: HostDecisionAuthority::Policy },
                outcome: HostRequestOutcome::Failed { error: oversized_error },
                reason: None,
            }
            .validate_ingress(),
            Err(ProviderEventValidationError::InvalidField {
                field: "host request outcome error",
                ..
            })
        ));
    }

    /// A `Granted` request that failed WHILE EXECUTING (a spawn error, an
    /// I/O failure) carries `HostRequestOutcome::Failed` -- distinct from,
    /// and never collapsed into, a `Denied` decision: the request was
    /// authorized, it just did not run cleanly.
    #[test]
    fn host_request_execution_failure_is_a_distinct_bounded_outcome_not_a_denial() {
        let spawn_error = "terminal/create spawn failed: os error 3";
        let granted_but_failed = ProviderEvent::HostRequestObserved {
            method: "terminal/create".to_owned(),
            params_json: String::new(),
            decision: HostRequestDecision::Granted { by: HostDecisionAuthority::Policy },
            outcome: HostRequestOutcome::Failed { error: spawn_error.to_owned() },
            reason: None,
        };
        assert_eq!(granted_but_failed.validate_ingress(), Ok(()));
        assert!(matches!(
            granted_but_failed,
            ProviderEvent::HostRequestObserved {
                decision: HostRequestDecision::Granted { .. },
                outcome: HostRequestOutcome::Failed { .. },
                ..
            }
        ));
    }

    /// A `HostRequestObserved` record written before `outcome` existed
    /// (pre-K1d) carries no `outcome` field at all -- `#[serde(default)]`
    /// must still read it back, as `HostRequestOutcome::Executed`: before
    /// this field existed, an observed `Granted` request always meant it
    /// ran, so that is the only honest default for the old shape.
    #[test]
    fn host_request_observed_outcome_defaults_to_executed_for_pre_k1d_json() {
        let pre_k1d = serde_json::json!({
            "kind": "host-request-observed",
            "method": "session/request_permission",
            "params_json": "{\"toolName\":\"bash\"}",
            "decision": { "kind": "granted", "by": "policy" },
            "reason": null,
        });
        let decoded: ProviderEvent = serde_json::from_value(pre_k1d)
            .expect("pre-K1d shape without outcome must still deserialize");
        assert!(matches!(
            decoded,
            ProviderEvent::HostRequestObserved {
                decision: HostRequestDecision::Granted { by: HostDecisionAuthority::Policy },
                outcome: HostRequestOutcome::Executed,
                ..
            }
        ));
    }

    /// The refusal text a `Denied` decision carries is bounded, verbatim
    /// free text -- never the categorical `Error::detail` slug (see this
    /// module's own doc comment for the incident that rule fixes). `None`
    /// for a `Granted`/`Deferred` decision, or a `Denied` one nobody
    /// attached text to, is equally valid: this is the honest absence of a
    /// reason, not a value to reject.
    #[test]
    fn host_request_observed_reason_is_bounded_free_text_and_optional() {
        let gate_text =
            "blocked by dangerous-command gate: rule=filesystem-wipe, argument=rm -rf /";
        let with_reason = ProviderEvent::HostRequestObserved {
            method: "terminal/create".to_owned(),
            params_json: String::new(),
            decision: HostRequestDecision::Denied { by: HostDecisionAuthority::Gate },
            outcome: HostRequestOutcome::Executed,
            reason: Some(gate_text.to_owned()),
        };
        assert_eq!(with_reason.validate_ingress(), Ok(()));

        let without_reason = ProviderEvent::HostRequestObserved {
            method: "terminal/create".to_owned(),
            params_json: String::new(),
            decision: HostRequestDecision::Granted { by: HostDecisionAuthority::Policy },
            outcome: HostRequestOutcome::Executed,
            reason: None,
        };
        assert_eq!(without_reason.validate_ingress(), Ok(()));
    }

    /// The catch-all "protocol said something we don't parse" event must
    /// still enforce the same bounds as every other provider event carrying
    /// vendor JSON -- a hostile or garbled `session/update` payload cannot
    /// ride this fallback path past `PROVIDER_EVENT_TEXT_MAX_BYTES`.
    #[test]
    fn unrecognized_notification_is_bounded_at_ingress() {
        let valid = ProviderEvent::UnrecognizedNotification {
            method: "session/some_future_update".to_owned(),
            payload_json: "{\"unknown\":true}".to_owned(),
        };
        assert_eq!(valid.validate_ingress(), Ok(()));

        assert!(matches!(
            ProviderEvent::UnrecognizedNotification {
                method: String::new(),
                payload_json: String::new(),
            }
            .validate_ingress(),
            Err(ProviderEventValidationError::Empty {
                field: "unrecognized notification method"
            })
        ));

        let oversized_payload = "p".repeat(PROVIDER_EVENT_TEXT_MAX_BYTES + 1);
        assert!(matches!(
            ProviderEvent::UnrecognizedNotification {
                method: "session/update".to_owned(),
                payload_json: oversized_payload,
            }
            .validate_ingress(),
            Err(ProviderEventValidationError::InvalidField {
                field: "unrecognized notification payload",
                ..
            })
        ));
    }

    // -----------------------------------------------------------------------
    // ACP session/update coverage — Plan, AvailableCommandsUpdated,
    // ModeChanged, SessionInfoUpdated, UsageUpdated, ConfigOptionsUpdated,
    // UserMessage
    // -----------------------------------------------------------------------

    #[test]
    fn provider_user_message_is_bounded_at_ingress_like_text() {
        let valid = ProviderEvent::UserMessage { text: "hi".to_owned(), is_delta: true };
        assert_eq!(valid.validate_ingress(), Ok(()));

        assert!(matches!(
            ProviderEvent::UserMessage {
                text: "unsafe\u{0000}text".to_owned(),
                is_delta: true,
            }
            .validate_ingress(),
            Err(ProviderEventValidationError::InvalidField { field: "text", .. })
        ));
    }

    #[test]
    fn provider_plan_accepts_a_valid_snapshot_and_rejects_empty_step_content() {
        let valid = ProviderEvent::Plan {
            steps: vec![ProviderPlanStep {
                content: "read the file".to_owned(),
                priority: ProviderPlanPriority::High,
                status: ProviderPlanStatus::Completed,
            }],
        };
        assert_eq!(valid.validate_ingress(), Ok(()));

        assert!(matches!(
            ProviderEvent::Plan {
                steps: vec![ProviderPlanStep {
                    content: String::new(),
                    priority: ProviderPlanPriority::Low,
                    status: ProviderPlanStatus::Pending,
                }],
            }
            .validate_ingress(),
            Err(ProviderEventValidationError::Empty { field: "plan step content" })
        ));
    }

    #[test]
    fn provider_plan_rejects_too_many_steps() {
        let steps = (0..=PROVIDER_PLAN_STEPS_MAX)
            .map(|i| ProviderPlanStep {
                content: format!("step {i}"),
                priority: ProviderPlanPriority::Medium,
                status: ProviderPlanStatus::Pending,
            })
            .collect();
        assert!(matches!(
            ProviderEvent::Plan { steps }.validate_ingress(),
            Err(ProviderEventValidationError::TooManyPlanSteps {
                max: PROVIDER_PLAN_STEPS_MAX,
                ..
            })
        ));
    }

    #[test]
    fn provider_available_commands_updated_is_bounded_at_ingress() {
        let valid = ProviderEvent::AvailableCommandsUpdated {
            commands: vec![ProviderAvailableCommand {
                name: "review".to_owned(),
                description: "Review the diff".to_owned(),
                input_hint: Some("<file>".to_owned()),
            }],
        };
        assert_eq!(valid.validate_ingress(), Ok(()));

        assert!(matches!(
            ProviderEvent::AvailableCommandsUpdated {
                commands: vec![ProviderAvailableCommand {
                    name: String::new(),
                    description: String::new(),
                    input_hint: None,
                }],
            }
            .validate_ingress(),
            Err(ProviderEventValidationError::Empty { field: "command name" })
        ));

        let too_many = (0..=PROVIDER_AVAILABLE_COMMANDS_MAX)
            .map(|i| ProviderAvailableCommand {
                name: format!("cmd{i}"),
                description: String::new(),
                input_hint: None,
            })
            .collect();
        assert!(matches!(
            ProviderEvent::AvailableCommandsUpdated { commands: too_many }.validate_ingress(),
            Err(ProviderEventValidationError::TooManyAvailableCommands {
                max: PROVIDER_AVAILABLE_COMMANDS_MAX,
                ..
            })
        ));
    }

    #[test]
    fn provider_mode_changed_requires_a_mode_id() {
        assert_eq!(
            ProviderEvent::ModeChanged {
                mode_id: "architect".to_owned(),
                available: Vec::new(),
            }
            .validate_ingress(),
            Ok(())
        );
        assert!(matches!(
            ProviderEvent::ModeChanged { mode_id: String::new(), available: Vec::new() }
                .validate_ingress(),
            Err(ProviderEventValidationError::Empty { field: "mode id" })
        ));
    }

    #[test]
    fn provider_mode_changed_available_catalog_is_bounded_at_ingress() {
        let valid = ProviderEvent::ModeChanged {
            mode_id: "architect".to_owned(),
            available: vec![ProviderModeInfo {
                id: "architect".to_owned(),
                name: "Architect".to_owned(),
                description: Some("Plans before it edits".to_owned()),
            }],
        };
        assert_eq!(valid.validate_ingress(), Ok(()));

        assert!(matches!(
            ProviderEvent::ModeChanged {
                mode_id: "architect".to_owned(),
                available: vec![ProviderModeInfo {
                    id: String::new(),
                    name: "Architect".to_owned(),
                    description: None,
                }],
            }
            .validate_ingress(),
            Err(ProviderEventValidationError::Empty { field: "available mode id" })
        ));

        let too_many = (0..=PROVIDER_MODE_CATALOG_MAX)
            .map(|i| ProviderModeInfo {
                id: format!("mode{i}"),
                name: format!("Mode {i}"),
                description: None,
            })
            .collect();
        assert!(matches!(
            ProviderEvent::ModeChanged {
                mode_id: "architect".to_owned(),
                available: too_many,
            }
            .validate_ingress(),
            Err(ProviderEventValidationError::TooManyModes {
                max: PROVIDER_MODE_CATALOG_MAX,
                ..
            })
        ));
    }

    #[test]
    fn provider_session_info_updated_allows_no_title_and_rejects_control_bytes() {
        assert_eq!(
            ProviderEvent::SessionInfoUpdated { title: None }.validate_ingress(),
            Ok(())
        );
        assert!(matches!(
            ProviderEvent::SessionInfoUpdated {
                title: Some("bad\u{0000}title".to_owned()),
            }
            .validate_ingress(),
            Err(ProviderEventValidationError::InvalidField { field: "session title", .. })
        ));
    }

    #[test]
    fn provider_usage_updated_accepts_optional_cost_and_bounds_currency() {
        let valid = ProviderEvent::UsageUpdated {
            used_tokens: Some(100),
            context_window: Some(200_000),
            cost_amount: Some("0.42".to_owned()),
            cost_currency: Some("USD".to_owned()),
        };
        assert_eq!(valid.validate_ingress(), Ok(()));

        let no_cost = ProviderEvent::UsageUpdated {
            used_tokens: None,
            context_window: None,
            cost_amount: None,
            cost_currency: None,
        };
        assert_eq!(no_cost.validate_ingress(), Ok(()));

        assert!(matches!(
            ProviderEvent::UsageUpdated {
                used_tokens: None,
                context_window: None,
                cost_amount: None,
                cost_currency: Some("bad\ncurrency".to_owned()),
            }
            .validate_ingress(),
            Err(ProviderEventValidationError::InvalidField { field: "usage cost currency", .. })
        ));
    }

    #[test]
    fn provider_config_options_updated_is_typed_and_bounded_at_ingress() {
        let valid = ProviderEvent::ConfigOptionsUpdated {
            options: vec![ProviderConfigOption {
                id: "model".to_owned(),
                name: "Model".to_owned(),
                description: Some("Which model to use".to_owned()),
                category: Some("generation".to_owned()),
                kind: ProviderConfigOptionKind::Select,
                value_json: "\"opus\"".to_owned(),
                choices: vec![ProviderConfigChoice {
                    value_json: "\"opus\"".to_owned(),
                    label: Some("Opus".to_owned()),
                }],
            }],
        };
        assert_eq!(valid.validate_ingress(), Ok(()));

        assert!(matches!(
            ProviderEvent::ConfigOptionsUpdated {
                options: vec![ProviderConfigOption {
                    id: String::new(),
                    name: "Model".to_owned(),
                    description: None,
                    category: None,
                    kind: ProviderConfigOptionKind::Boolean,
                    value_json: "true".to_owned(),
                    choices: Vec::new(),
                }],
            }
            .validate_ingress(),
            Err(ProviderEventValidationError::Empty { field: "config option id" })
        ));
    }

    #[test]
    fn tool_completed_non_execution_kind_is_optional_and_bounded() {
        let none = ProviderEvent::ToolCompleted {
            id: "t1".to_owned(),
            output: "denied".to_owned(),
            is_error: true,
            duration_ms: None,
            agent_id: None,
            non_execution_kind: None,
        };
        assert_eq!(none.validate_ingress(), Ok(()));

        let typed = ProviderEvent::ToolCompleted {
            id: "t1".to_owned(),
            output: "denied".to_owned(),
            is_error: true,
            duration_ms: None,
            agent_id: None,
            non_execution_kind: Some("permission-rule".to_owned()),
        };
        assert_eq!(typed.validate_ingress(), Ok(()));

        let oversized = "k".repeat(PROVIDER_EVENT_ID_MAX_BYTES + 1);
        assert!(matches!(
            ProviderEvent::ToolCompleted {
                id: "t1".to_owned(),
                output: "denied".to_owned(),
                is_error: true,
                duration_ms: None,
                agent_id: None,
                non_execution_kind: Some(oversized),
            }
            .validate_ingress(),
            Err(ProviderEventValidationError::InvalidField {
                field: "tool non-execution kind",
                ..
            })
        ));
    }

    #[test]
    fn session_ended_stop_reason_is_optional_and_each_variant_validates() {
        use super::ProviderStopReason;
        for stop_reason in [
            None,
            Some(ProviderStopReason::EndTurn),
            Some(ProviderStopReason::MaxTokens),
            Some(ProviderStopReason::MaxTurnRequests),
            Some(ProviderStopReason::Refusal),
            Some(ProviderStopReason::Cancelled),
            Some(ProviderStopReason::Other { value: "some-vendor-code".to_owned() }),
            Some(ProviderStopReason::ProviderError {
                code: -32603,
                message: "You've hit your usage limit.".to_owned(),
                vendor_code: Some("usageLimitExceeded".to_owned()),
            }),
        ] {
            let event = ProviderEvent::SessionEnded {
                result: "end_turn".to_owned(),
                cost_usd: None,
                is_error: false,
                stop_reason,
            };
            assert_eq!(event.validate_ingress(), Ok(()));
            let encoded = serde_json::to_vec(&event).expect("serialize");
            let decoded: ProviderEvent = serde_json::from_slice(&encoded).expect("deserialize");
            assert_eq!(decoded, event);
        }
    }

    #[test]
    fn session_ended_provider_error_message_and_vendor_code_are_bounded() {
        use super::ProviderStopReason;
        let oversized_message = "m".repeat(PROVIDER_EVENT_TEXT_MAX_BYTES + 1);
        assert!(matches!(
            ProviderEvent::SessionEnded {
                result: "provider_error".to_owned(),
                cost_usd: None,
                is_error: true,
                stop_reason: Some(ProviderStopReason::ProviderError {
                    code: -32603,
                    message: oversized_message,
                    vendor_code: None,
                }),
            }
            .validate_ingress(),
            Err(ProviderEventValidationError::InvalidField {
                field: "provider error message",
                ..
            })
        ));

        let oversized_code = "c".repeat(PROVIDER_EVENT_ID_MAX_BYTES + 1);
        assert!(matches!(
            ProviderEvent::SessionEnded {
                result: "provider_error".to_owned(),
                cost_usd: None,
                is_error: true,
                stop_reason: Some(ProviderStopReason::ProviderError {
                    code: -32603,
                    message: "usage limit exceeded".to_owned(),
                    vendor_code: Some(oversized_code),
                }),
            }
            .validate_ingress(),
            Err(ProviderEventValidationError::InvalidField {
                field: "provider error vendor code",
                ..
            })
        ));
    }
}