genai-rs 0.8.0

A Rust client library for Google's Generative AI (Gemini) API with streaming, function calling, and multi-turn conversations
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
//! Proto-JSON wire types for the localharness WebSocket protocol.
//!
//! Everything after the stdio handshake travels as **proto-JSON** (the
//! protobuf JSON mapping) over a localhost WebSocket:
//!
//! - field names are `camelCase`;
//! - enums are `SCREAMING_SNAKE_CASE` strings;
//! - 64-bit integers are emitted as JSON *strings* by the harness (this
//!   module accepts both strings and numbers, and re-serializes as numbers —
//!   value-preserving, accepted by the harness's parser);
//! - a `oneof` sets at most one of its fields.
//!
//! Types follow the crate's Evergreen philosophy: unrecognized oneof
//! variants deserialize into `Unknown` variants, unrecognized enum strings
//! are preserved, and unrecognized fields on harness-emitted messages are
//! captured in `extra` maps so they roundtrip.
//!
//! Message and field shapes are verified against the descriptor set shipped
//! in the `google-antigravity` 0.1.5 wheel (`localharness.proto`, package
//! `antigravity.localharness`).

use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use std::collections::BTreeMap;

// =============================================================================
// Flexible numeric deserialization (proto-JSON int64/uint64 arrive as strings)
// =============================================================================

pub(crate) mod flex_num {
    use serde::{Deserialize, Deserializer, de::Error};
    use serde_json::Value;

    fn value_to_i64<E: Error>(value: &Value) -> Result<i64, E> {
        match value {
            Value::Number(n) => n
                .as_i64()
                .ok_or_else(|| E::custom(format!("number {n} does not fit in i64"))),
            Value::String(s) => s
                .parse::<i64>()
                .map_err(|e| E::custom(format!("invalid i64 string {s:?}: {e}"))),
            other => Err(E::custom(format!("expected i64, got {other}"))),
        }
    }

    fn value_to_u64<E: Error>(value: &Value) -> Result<u64, E> {
        match value {
            Value::Number(n) => n
                .as_u64()
                .ok_or_else(|| E::custom(format!("number {n} does not fit in u64"))),
            Value::String(s) => s
                .parse::<u64>()
                .map_err(|e| E::custom(format!("invalid u64 string {s:?}: {e}"))),
            other => Err(E::custom(format!("expected u64, got {other}"))),
        }
    }

    pub fn opt_u64<'de, D: Deserializer<'de>>(d: D) -> Result<Option<u64>, D::Error> {
        match Option::<Value>::deserialize(d)? {
            None | Some(Value::Null) => Ok(None),
            Some(v) => value_to_u64(&v).map(Some),
        }
    }

    pub fn opt_u32<'de, D: Deserializer<'de>>(d: D) -> Result<Option<u32>, D::Error> {
        match Option::<Value>::deserialize(d)? {
            None | Some(Value::Null) => Ok(None),
            Some(v) => {
                let raw = value_to_u64(&v)?;
                u32::try_from(raw)
                    .map(Some)
                    .map_err(|_| Error::custom(format!("value {raw} does not fit in u32")))
            }
        }
    }

    pub fn opt_i32<'de, D: Deserializer<'de>>(d: D) -> Result<Option<i32>, D::Error> {
        match Option::<Value>::deserialize(d)? {
            None | Some(Value::Null) => Ok(None),
            Some(v) => {
                let raw = value_to_i64(&v)?;
                i32::try_from(raw)
                    .map(Some)
                    .map_err(|_| Error::custom(format!("value {raw} does not fit in i32")))
            }
        }
    }
}

// =============================================================================
// String-valued wire enums (Evergreen: unknown values are preserved)
// =============================================================================

/// Generates a proto-JSON string enum with an `Unknown` variant that
/// preserves unrecognized wire values, plus the crate-standard helper
/// methods (`is_unknown`, `unknown_<context>_type`, `unknown_data`).
macro_rules! wire_string_enum {
    (
        $(#[$meta:meta])*
        $name:ident, $ctx:ident, $unknown_type_fn:ident {
            $( $(#[$vmeta:meta])* $variant:ident => $wire:literal ),+ $(,)?
        }
    ) => {
        $(#[$meta])*
        #[derive(Debug, Clone, PartialEq)]
        #[non_exhaustive]
        pub enum $name {
            $( $(#[$vmeta])* $variant, )+
            /// A wire value this crate does not recognize (Evergreen).
            Unknown {
                /// The unrecognized enum string from the harness.
                $ctx: String,
                /// The raw JSON value, preserved for roundtrip.
                data: Value,
            },
        }

        impl $name {
            /// Returns the proto-JSON wire string for this value.
            #[must_use]
            pub fn as_wire_str(&self) -> &str {
                match self {
                    $( Self::$variant => $wire, )+
                    Self::Unknown { $ctx, .. } => $ctx,
                }
            }

            /// Check if this is an unknown value.
            #[must_use]
            pub const fn is_unknown(&self) -> bool {
                matches!(self, Self::Unknown { .. })
            }

            /// Returns the unrecognized wire string if this is an unknown value.
            #[must_use]
            pub fn $unknown_type_fn(&self) -> Option<&str> {
                match self {
                    Self::Unknown { $ctx, .. } => Some($ctx),
                    _ => None,
                }
            }

            /// Returns the preserved raw JSON if this is an unknown value.
            #[must_use]
            pub fn unknown_data(&self) -> Option<&Value> {
                match self {
                    Self::Unknown { data, .. } => Some(data),
                    _ => None,
                }
            }
        }

        impl Serialize for $name {
            fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
                serializer.serialize_str(self.as_wire_str())
            }
        }

        impl<'de> Deserialize<'de> for $name {
            fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
                let value = Value::deserialize(deserializer)?;
                if let Value::String(s) = &value {
                    match s.as_str() {
                        $( $wire => return Ok(Self::$variant), )+
                        _ => {}
                    }
                }
                let $ctx = match &value {
                    Value::String(s) => s.clone(),
                    other => other.to_string(),
                };
                tracing::warn!(
                    concat!("Unknown ", stringify!($name), " wire value: '{}'. \
                     Preserving in Unknown variant."),
                    $ctx
                );
                Ok(Self::Unknown { $ctx, data: value })
            }
        }
    };
}

wire_string_enum!(
    /// `StepUpdate.State` — lifecycle state of one agent step.
    StepState, state_type, unknown_state_type {
        /// `STATE_UNSPECIFIED`.
        Unspecified => "STATE_UNSPECIFIED",
        /// The step is executing.
        Active => "STATE_ACTIVE",
        /// The step completed successfully.
        Done => "STATE_DONE",
        /// The step is blocked on client input (confirmation or questions).
        WaitingForUser => "STATE_WAITING_FOR_USER",
        /// The step failed.
        Error => "STATE_ERROR",
    }
);

wire_string_enum!(
    /// `StepUpdate.Source` — who produced a step.
    StepSource, source_type, unknown_source_type {
        /// `SOURCE_UNSPECIFIED`.
        Unspecified => "SOURCE_UNSPECIFIED",
        /// Emitted by the platform (e.g. system errors).
        System => "SOURCE_SYSTEM",
        /// Emitted on behalf of the user.
        User => "SOURCE_USER",
        /// Emitted by the model.
        Model => "SOURCE_MODEL",
    }
);

wire_string_enum!(
    /// `StepUpdate.Target` — who a step is directed at.
    StepTarget, target_type, unknown_target_type {
        /// `TARGET_UNSPECIFIED`.
        Unspecified => "TARGET_UNSPECIFIED",
        /// Directed at the user (e.g. final response text).
        User => "TARGET_USER",
        /// Directed at the model.
        Model => "TARGET_MODEL",
        /// Directed at the environment (e.g. tool executions).
        Environment => "TARGET_ENVIRONMENT",
    }
);

wire_string_enum!(
    /// `TrajectoryStateUpdate.State` — lifecycle state of one trajectory.
    TrajectoryState, state_type, unknown_state_type {
        /// `STATE_UNSPECIFIED`.
        Unspecified => "STATE_UNSPECIFIED",
        /// The trajectory is processing a turn.
        Running => "STATE_RUNNING",
        /// The trajectory finished the turn and is awaiting input.
        Idle => "STATE_IDLE",
        /// The turn was cancelled (halt request or pre-turn hook denial).
        Cancelled => "STATE_CANCELLED",
    }
);

wire_string_enum!(
    /// `ModelType` — the roles a configured model can serve.
    ModelType, model_type, unknown_model_type {
        /// `MODEL_TYPE_UNSPECIFIED`.
        Unspecified => "MODEL_TYPE_UNSPECIFIED",
        /// Text generation model.
        Text => "MODEL_TYPE_TEXT",
        /// Image generation model.
        Image => "MODEL_TYPE_IMAGE",
    }
);

wire_string_enum!(
    /// `LifecycleHook` — hook points the harness can call back into.
    LifecycleHook, hook_type, unknown_hook_type {
        /// `LIFECYCLE_HOOK_UNSPECIFIED`.
        Unspecified => "LIFECYCLE_HOOK_UNSPECIFIED",
        /// Fired when the session starts.
        OnSessionStart => "LIFECYCLE_HOOK_ON_SESSION_START",
        /// Fired when the session ends.
        OnSessionEnd => "LIFECYCLE_HOOK_ON_SESSION_END",
        /// Fired before each user turn.
        PreTurn => "LIFECYCLE_HOOK_PRE_TURN",
        /// Fired after each user turn.
        PostTurn => "LIFECYCLE_HOOK_POST_TURN",
        /// Fired before each tool call (may deny it).
        PreTool => "LIFECYCLE_HOOK_PRE_TOOL",
        /// Fired after each successful tool call.
        PostTool => "LIFECYCLE_HOOK_POST_TOOL",
        /// Fired when a tool call errors.
        OnToolError => "LIFECYCLE_HOOK_ON_TOOL_ERROR",
    }
);

wire_string_enum!(
    /// `PreToolResult.Decision` / `PreTurnResult.Decision` — hook verdicts.
    HookDecision, decision_type, unknown_decision_type {
        /// `DECISION_UNSPECIFIED`.
        Unspecified => "DECISION_UNSPECIFIED",
        /// Allow the operation.
        Allow => "ALLOW",
        /// Deny the operation.
        Deny => "DENY",
    }
);

wire_string_enum!(
    /// `ActionEditFile.DiffLine.LineAction` — per-line diff operation.
    LineAction, action_type, unknown_action_type {
        /// `LINE_ACTION_UNSPECIFIED`.
        Unspecified => "LINE_ACTION_UNSPECIFIED",
        /// The line was inserted.
        Insert => "LINE_ACTION_INSERT",
        /// The line was deleted.
        Delete => "LINE_ACTION_DELETE",
        /// The line is unchanged context.
        None => "LINE_ACTION_NONE",
    }
);

// =============================================================================
// Harness configuration (client -> harness, sent once at init)
// =============================================================================

/// The first WebSocket message: `InitializeConversationEvent`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct InitializeConversationEvent {
    /// The full agent configuration for this conversation.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub config: Option<HarnessConfig>,
}

/// `HarnessConfig` — everything the harness needs to run the agent.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct HarnessConfig {
    /// Conversation id to resume, when restoring a saved session.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cascade_id: Option<String>,
    /// System instructions for the agent.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub system_instructions: Option<SystemInstructions>,
    /// Custom (client-executed) tool declarations.
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub tools: Vec<Tool>,
    /// Per-builtin enable flags for harness-executed tools.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub harness_side_tools: Option<HarnessSideTools>,
    /// History compaction threshold in tokens (`0` = harness default).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub compaction_threshold: Option<u32>,
    /// Workspace directories the agent may operate in.
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub workspaces: Vec<Workspace>,
    /// Paths to search for agent skills.
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub skills_paths: Vec<String>,
    /// JSON schema (as a JSON string) for structured final output.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub finish_tool_schema_json: Option<String>,
    /// Serialized trajectory to resume from (base64 bytes).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub initial_trajectory: Option<String>,
    /// Directory for harness application data.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub app_data_dir: Option<String>,
    /// MCP servers the harness should connect to.
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub mcp_servers: Vec<McpServerConfig>,
    /// Model configurations. The harness requires at least one text model.
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub models: Vec<ModelConfig>,
    /// Lifecycle hooks the client wants callbacks for.
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub enabled_hooks: Vec<LifecycleHook>,
    /// Static subagent configurations.
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub custom_subagents: Vec<CustomAgent>,
}

/// `SystemInstructions` (oneof `type`): custom or appended instructions.
///
/// Modeled as a struct of options (proto-JSON sets at most one field).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct SystemInstructions {
    /// Fully custom instructions, replacing the harness's defaults.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub custom: Option<CustomSystemInstructions>,
    /// Sections appended to the harness's default instructions.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub appended: Option<AppendedSystemInstructions>,
}

impl SystemInstructions {
    /// Custom instructions consisting of a single text part.
    #[must_use]
    pub fn custom_text(text: impl Into<String>) -> Self {
        Self {
            custom: Some(CustomSystemInstructions {
                part: vec![SystemInstructionPart {
                    text: Some(text.into()),
                }],
            }),
            appended: None,
        }
    }
}

/// `CustomSystemInstructions` — a list of instruction parts.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct CustomSystemInstructions {
    /// Instruction parts. Note the singular wire name (`part`) — the proto
    /// field is a *repeated message* named `part`.
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub part: Vec<SystemInstructionPart>,
}

/// `CustomSystemInstructions.Part` (oneof `part`, currently text-only).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct SystemInstructionPart {
    /// Text content of this part.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text: Option<String>,
}

/// `AppendedSystemInstructions` — identity plus appended sections.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct AppendedSystemInstructions {
    /// Custom identity line for the agent.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub custom_identity: Option<String>,
    /// Titled sections appended after the default instructions.
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub appended_sections: Vec<InstructionSection>,
}

/// `AppendedSystemInstructions.Section`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct InstructionSection {
    /// Section title.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    /// Section body.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content: Option<String>,
}

/// `Tool` — a custom, client-executed tool declaration.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct Tool {
    /// Tool name (what the model calls).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Human/model-readable description.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// Parameter JSON schema, serialized as a JSON *string*.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub parameters_json_schema: Option<String>,
    /// Response JSON schema, serialized as a JSON *string*.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub response_json_schema: Option<String>,
}

/// Enable/disable flag for one harness-side tool.
///
/// Several `*ToolConfig` messages exist on the wire; this crate writes only
/// their common `enabled` field.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct ToolToggle {
    /// Whether the tool is available to the agent.
    pub enabled: bool,
}

impl ToolToggle {
    /// Convenience constructor.
    #[must_use]
    pub const fn new(enabled: bool) -> Self {
        Self { enabled }
    }
}

/// `HarnessSideTools` — per-builtin enable flags.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct HarnessSideTools {
    /// `find_file` builtin.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub find: Option<ToolToggle>,
    /// `run_command` builtin (shell access).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub run_command: Option<ToolToggle>,
    /// `start_subagent` builtin.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub subagents: Option<ToolToggle>,
    /// `ask_question` builtin.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub user_questions: Option<ToolToggle>,
    /// `edit_file` builtin.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub file_edit: Option<ToolToggle>,
    /// `view_file` builtin.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub view_file: Option<ToolToggle>,
    /// `create_file` builtin.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub write_to_file: Option<ToolToggle>,
    /// `search_directory` (grep) builtin.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub grep_search: Option<ToolToggle>,
    /// `list_directory` builtin.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub list_dir: Option<ToolToggle>,
    /// Workspace path validation enforcement.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub permissions: Option<PermissionsConfig>,
    /// `generate_image` builtin.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub generate_image: Option<ToolToggle>,
    /// `search_web` builtin.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub search_web: Option<ToolToggle>,
}

/// `PermissionsConfig`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct PermissionsConfig {
    /// Reject file operations targeting paths outside configured workspaces.
    pub enforce_workspace_validation: bool,
}

/// `Workspace` (oneof `workspace_type`, currently filesystem-only).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct Workspace {
    /// A directory on the local filesystem.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub filesystem_workspace: Option<FilesystemWorkspace>,
}

impl Workspace {
    /// A filesystem workspace rooted at `directory`.
    #[must_use]
    pub fn filesystem(directory: impl Into<String>) -> Self {
        Self {
            filesystem_workspace: Some(FilesystemWorkspace {
                directory: Some(directory.into()),
            }),
        }
    }
}

/// `FilesystemWorkspace`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct FilesystemWorkspace {
    /// Absolute directory path.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub directory: Option<String>,
}

/// `ModelConfig` — one model the harness may call.
///
/// The endpoint fields form a oneof (`endpoint`): set at most one of
/// `gemini_api_endpoint` / `vertex_endpoint`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct ModelConfig {
    /// Model name, e.g. `gemini-3-flash-preview`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Roles this model serves ([`ModelType::Text`] is required for chat).
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub types: Vec<ModelType>,
    /// Gemini API endpoint (API-key auth).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub gemini_api_endpoint: Option<GeminiApiEndpoint>,
    /// Vertex AI endpoint (project/location auth). Present for wire
    /// completeness; the tested path is the Gemini API endpoint.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub vertex_endpoint: Option<VertexEndpoint>,
}

/// `GeminiAPIEndpoint`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct GeminiApiEndpoint {
    /// Override for the Gemini API base URL.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub base_url: Option<String>,
    /// Extra HTTP headers sent with model requests.
    #[serde(skip_serializing_if = "BTreeMap::is_empty", default)]
    pub http_headers: BTreeMap<String, String>,
    /// Gemini API key.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub api_key: Option<String>,
    /// Model options (thinking level).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub options: Option<GeminiModelOptions>,
}

/// `VertexEndpoint`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct VertexEndpoint {
    /// Override for the Vertex AI base URL.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub base_url: Option<String>,
    /// Extra HTTP headers sent with model requests.
    #[serde(skip_serializing_if = "BTreeMap::is_empty", default)]
    pub http_headers: BTreeMap<String, String>,
    /// Google Cloud project id.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub project: Option<String>,
    /// Google Cloud location.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub location: Option<String>,
    /// Model options (thinking level).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub options: Option<GeminiModelOptions>,
}

/// `GeminiModelOptions`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct GeminiModelOptions {
    /// Thinking level (e.g. `"low"`, `"high"`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub thinking_level: Option<String>,
}

/// `McpServerConfig` — one MCP server the harness connects to.
///
/// `stdio` / `http` form a oneof (`transport`): set at most one.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct McpServerConfig {
    /// Server name; also the prefix in policy targets (`mcp_<name>_<tool>`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Stdio transport: the harness spawns the server as a subprocess.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stdio: Option<McpStdioTransport>,
    /// Streamable-HTTP transport.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub http: Option<McpHttpTransport>,
    /// Allow-list of tool names (empty = all).
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub enabled_tools: Vec<String>,
    /// Deny-list of tool names.
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub disabled_tools: Vec<String>,
    /// Per-call timeout in seconds (`0` = harness default).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub timeout_seconds: Option<i32>,
}

/// `McpStdioTransport`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct McpStdioTransport {
    /// Executable to spawn.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub command: Option<String>,
    /// Command-line arguments.
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub args: Vec<String>,
    /// Environment variables for the subprocess.
    #[serde(skip_serializing_if = "BTreeMap::is_empty", default)]
    pub env: BTreeMap<String, String>,
}

/// `McpHttpTransport`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct McpHttpTransport {
    /// Server URL.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,
    /// Extra HTTP headers.
    #[serde(skip_serializing_if = "BTreeMap::is_empty", default)]
    pub headers: BTreeMap<String, String>,
}

/// `CustomAgent` — a static subagent configuration.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct CustomAgent {
    /// Subagent name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Subagent description (shown to the parent model).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// Subagent system instructions.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub system_instructions: Option<SystemInstructions>,
    /// Subagent builtin-tool flags.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub harness_side_tools: Option<HarnessSideTools>,
    /// Custom tools available to the subagent (must also be registered on
    /// the main agent).
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub tools: Vec<Tool>,
}

// =============================================================================
// Client -> harness events (InputEvent oneof)
// =============================================================================

/// `InputEvent` — the client-to-harness message envelope (oneof `event`).
///
/// Serializes to a single-key proto-JSON object, e.g.
/// `{"userInput": "hello"}` or `{"toolResponse": {...}}`.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum InputEvent {
    /// Plain-text user message; starts a new turn.
    UserInput(String),
    /// Multi-part user message (text, media, slash commands).
    ComplexUserInput(UserInput),
    /// Approve/reject a harness-side tool awaiting confirmation.
    ToolConfirmation(ToolConfirmation),
    /// Result of a client-executed custom tool call.
    ToolResponse(ToolResponse),
    /// Answers to a `questions_request`.
    QuestionResponse(UserQuestionsResponse),
    /// Cancel the current turn.
    HaltRequest(bool),
    /// Message injected by a client-side trigger.
    AutomatedTrigger(String),
    /// Reply to a `call_hook_request`.
    CallHookResponse(CallHookResponse),
    /// Ask the harness to run session-end hooks.
    SessionEndRequest(bool),
    /// An event variant this crate does not recognize (Evergreen).
    Unknown {
        /// The unrecognized oneof field name.
        event_type: String,
        /// The raw JSON payload, preserved for roundtrip.
        data: Value,
    },
}

impl InputEvent {
    /// Check if this is an unknown event.
    #[must_use]
    pub const fn is_unknown(&self) -> bool {
        matches!(self, Self::Unknown { .. })
    }

    /// Returns the unrecognized oneof field name if this is an unknown event.
    #[must_use]
    pub fn unknown_event_type(&self) -> Option<&str> {
        match self {
            Self::Unknown { event_type, .. } => Some(event_type),
            _ => None,
        }
    }

    /// Returns the preserved raw JSON if this is an unknown event.
    #[must_use]
    pub fn unknown_data(&self) -> Option<&Value> {
        match self {
            Self::Unknown { data, .. } => Some(data),
            _ => None,
        }
    }

    fn oneof_key(&self) -> &str {
        match self {
            Self::UserInput(_) => "userInput",
            Self::ComplexUserInput(_) => "complexUserInput",
            Self::ToolConfirmation(_) => "toolConfirmation",
            Self::ToolResponse(_) => "toolResponse",
            Self::QuestionResponse(_) => "questionResponse",
            Self::HaltRequest(_) => "haltRequest",
            Self::AutomatedTrigger(_) => "automatedTrigger",
            Self::CallHookResponse(_) => "callHookResponse",
            Self::SessionEndRequest(_) => "sessionEndRequest",
            Self::Unknown { event_type, .. } => event_type,
        }
    }

    fn oneof_value(&self) -> Result<Value, serde_json::Error> {
        match self {
            Self::UserInput(s) | Self::AutomatedTrigger(s) => Ok(Value::String(s.clone())),
            Self::ComplexUserInput(v) => serde_json::to_value(v),
            Self::ToolConfirmation(v) => serde_json::to_value(v),
            Self::ToolResponse(v) => serde_json::to_value(v),
            Self::QuestionResponse(v) => serde_json::to_value(v),
            Self::HaltRequest(b) | Self::SessionEndRequest(b) => Ok(Value::Bool(*b)),
            Self::CallHookResponse(v) => serde_json::to_value(v),
            Self::Unknown { data, .. } => Ok(data.clone()),
        }
    }
}

impl Serialize for InputEvent {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        use serde::ser::SerializeMap;
        let value = self.oneof_value().map_err(serde::ser::Error::custom)?;
        let mut map = serializer.serialize_map(Some(1))?;
        map.serialize_entry(self.oneof_key(), &value)?;
        map.end()
    }
}

impl<'de> Deserialize<'de> for InputEvent {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        use serde::de::Error;
        let map = Map::deserialize(deserializer)?;
        let (key, value) = map
            .into_iter()
            .next()
            .ok_or_else(|| D::Error::custom("InputEvent must have exactly one field set"))?;
        let event = match key.as_str() {
            "userInput" => Self::UserInput(
                value
                    .as_str()
                    .ok_or_else(|| D::Error::custom("userInput must be a string"))?
                    .to_string(),
            ),
            "complexUserInput" => {
                Self::ComplexUserInput(serde_json::from_value(value).map_err(D::Error::custom)?)
            }
            "toolConfirmation" => {
                Self::ToolConfirmation(serde_json::from_value(value).map_err(D::Error::custom)?)
            }
            "toolResponse" => {
                Self::ToolResponse(serde_json::from_value(value).map_err(D::Error::custom)?)
            }
            "questionResponse" => {
                Self::QuestionResponse(serde_json::from_value(value).map_err(D::Error::custom)?)
            }
            "haltRequest" => Self::HaltRequest(value.as_bool().unwrap_or_default()),
            "automatedTrigger" => Self::AutomatedTrigger(
                value
                    .as_str()
                    .ok_or_else(|| D::Error::custom("automatedTrigger must be a string"))?
                    .to_string(),
            ),
            "callHookResponse" => {
                Self::CallHookResponse(serde_json::from_value(value).map_err(D::Error::custom)?)
            }
            "sessionEndRequest" => Self::SessionEndRequest(value.as_bool().unwrap_or_default()),
            _ => Self::Unknown {
                event_type: key,
                data: value,
            },
        };
        Ok(event)
    }
}

/// `UserInput` — multi-part user content.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct UserInput {
    /// The content parts, in order.
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub parts: Vec<UserInputPart>,
}

/// `UserInput.Part` (oneof `part`): text, media, or a slash command.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct UserInputPart {
    /// Plain text.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text: Option<String>,
    /// Inline media (image, document, audio, video).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub media: Option<Media>,
    /// A named slash command.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub slash_command: Option<SlashCommand>,
}

impl UserInputPart {
    /// A text part.
    #[must_use]
    pub fn text(text: impl Into<String>) -> Self {
        Self {
            text: Some(text.into()),
            ..Self::default()
        }
    }
}

/// `Media` — inline binary content (proto-JSON encodes `data` as base64).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct Media {
    /// MIME type of the data.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mime_type: Option<String>,
    /// Optional human-readable description.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// Base64-encoded content.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data: Option<String>,
}

/// `UserInput.SlashCommand`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct SlashCommand {
    /// Command name (without the slash).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
}

/// `ToolConfirmation` — approve or reject a pending harness-side tool step.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct ToolConfirmation {
    /// Trajectory of the waiting step.
    pub trajectory_id: String,
    /// Index of the waiting step.
    pub step_index: u32,
    /// `true` to run the tool, `false` to reject it.
    pub accepted: bool,
}

/// `ToolResponse` — the result of a client-executed custom tool call.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct ToolResponse {
    /// Correlates with [`ToolCall::id`].
    pub id: String,
    /// The result, serialized as a JSON string.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub response_json: Option<String>,
    /// Media attachments accompanying the result.
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub supplemental_media: Vec<Media>,
}

/// `UserQuestionsResponse` — answers to a `questions_request`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct UserQuestionsResponse {
    /// Trajectory of the asking step.
    pub trajectory_id: String,
    /// Index of the asking step.
    pub step_index: u32,
    /// Set to cancel the questions instead of answering.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cancelled: Option<bool>,
    /// The answers (oneof with `cancelled`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub response: Option<QuestionsResponse>,
}

/// `UserQuestionsResponse.QuestionsResponse`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct QuestionsResponse {
    /// One answer per question, in order.
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub answers: Vec<UserQuestionAnswer>,
}

/// `UserQuestionAnswer` (oneof `answer`).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct UserQuestionAnswer {
    /// The question was left unanswered.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub unanswered: Option<bool>,
    /// A multiple-choice answer.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub multiple_choice_answer: Option<MultipleChoiceAnswer>,
}

impl UserQuestionAnswer {
    /// An explicit "unanswered" answer.
    #[must_use]
    pub fn unanswered() -> Self {
        Self {
            unanswered: Some(true),
            multiple_choice_answer: None,
        }
    }
}

/// `MultipleChoiceAnswer`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct MultipleChoiceAnswer {
    /// Zero-based indices of the selected choices.
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub selected_choice_indices: Vec<i32>,
    /// Optional freeform text response.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub freeform_response: Option<String>,
}

/// `CallHookResponse` — the client's reply to a hook callback.
///
/// The result fields form a oneof (`result`): set exactly one.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct CallHookResponse {
    /// Correlates with [`CallHookRequest::request_id`].
    pub request_id: String,
    /// Verdict for a pre-turn hook.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pre_turn_result: Option<HookVerdict>,
    /// Verdict for a pre-tool hook.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pre_tool_result: Option<HookVerdict>,
    /// Acknowledgement for observe-only hooks.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub empty_result: Option<EmptyResult>,
    /// Hook execution failed on the client.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error_message: Option<String>,
}

/// `PreToolResult` / `PreTurnResult` — an allow/deny verdict with a reason.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct HookVerdict {
    /// The decision.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub decision: Option<HookDecision>,
    /// Human-readable reason (surfaced to the model on deny).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
}

/// `EmptyResult`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct EmptyResult {}

// =============================================================================
// Harness -> client events (OutputEvent oneof)
// =============================================================================

/// `OutputEvent` — the harness-to-client message envelope.
///
/// Carries envelope metadata (`seq_num`, `timestamp_micros`,
/// `usage_metadata`) alongside the oneof payload.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct OutputEvent {
    /// Monotonic sequence number.
    pub seq_num: Option<i64>,
    /// Event timestamp in microseconds since the Unix epoch.
    pub timestamp_micros: Option<i64>,
    /// Token usage, attached to some step updates.
    pub usage_metadata: Option<UsageMetadata>,
    /// The event payload (`None` if the oneof was empty).
    pub payload: Option<OutputPayload>,
}

/// The oneof payload of an [`OutputEvent`].
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum OutputPayload {
    /// Progress on one agent step. Boxed: `StepUpdate` is by far the
    /// largest message in the protocol.
    StepUpdate(Box<StepUpdate>),
    /// A trajectory changed lifecycle state.
    TrajectoryStateUpdate(TrajectoryStateUpdate),
    /// The model called a client-executed custom tool.
    ToolCall(ToolCall),
    /// Reply to the initial `InitializeConversationEvent`.
    InitializeConversationResponse(InitializeConversationResponse),
    /// The harness is invoking a client-side lifecycle hook.
    CallHookRequest(CallHookRequest),
    /// Session-end hooks completed.
    SessionEndResponse(bool),
    /// An event variant this crate does not recognize (Evergreen).
    Unknown {
        /// The unrecognized oneof field name.
        event_type: String,
        /// The raw JSON payload, preserved for roundtrip.
        data: Value,
    },
}

impl OutputPayload {
    /// Check if this is an unknown event.
    #[must_use]
    pub const fn is_unknown(&self) -> bool {
        matches!(self, Self::Unknown { .. })
    }

    /// Returns the unrecognized oneof field name if this is an unknown event.
    #[must_use]
    pub fn unknown_event_type(&self) -> Option<&str> {
        match self {
            Self::Unknown { event_type, .. } => Some(event_type),
            _ => None,
        }
    }

    /// Returns the preserved raw JSON if this is an unknown event.
    #[must_use]
    pub fn unknown_data(&self) -> Option<&Value> {
        match self {
            Self::Unknown { data, .. } => Some(data),
            _ => None,
        }
    }
}

const OUTPUT_PAYLOAD_KEYS: &[&str] = &[
    "stepUpdate",
    "trajectoryStateUpdate",
    "toolCall",
    "initializeConversationResponse",
    "callHookRequest",
    "sessionEndResponse",
];

impl Serialize for OutputEvent {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        use serde::ser::{Error, SerializeMap};
        let mut len = 0;
        len += usize::from(self.seq_num.is_some());
        len += usize::from(self.timestamp_micros.is_some());
        len += usize::from(self.usage_metadata.is_some());
        len += usize::from(self.payload.is_some());
        let mut map = serializer.serialize_map(Some(len))?;
        if let Some(seq_num) = self.seq_num {
            map.serialize_entry("seqNum", &seq_num)?;
        }
        if let Some(timestamp_micros) = self.timestamp_micros {
            map.serialize_entry("timestampMicros", &timestamp_micros)?;
        }
        if let Some(payload) = &self.payload {
            let (key, value) = match payload {
                OutputPayload::StepUpdate(v) => (
                    "stepUpdate",
                    serde_json::to_value(v).map_err(S::Error::custom)?,
                ),
                OutputPayload::TrajectoryStateUpdate(v) => (
                    "trajectoryStateUpdate",
                    serde_json::to_value(v).map_err(S::Error::custom)?,
                ),
                OutputPayload::ToolCall(v) => (
                    "toolCall",
                    serde_json::to_value(v).map_err(S::Error::custom)?,
                ),
                OutputPayload::InitializeConversationResponse(v) => (
                    "initializeConversationResponse",
                    serde_json::to_value(v).map_err(S::Error::custom)?,
                ),
                OutputPayload::CallHookRequest(v) => (
                    "callHookRequest",
                    serde_json::to_value(v).map_err(S::Error::custom)?,
                ),
                OutputPayload::SessionEndResponse(b) => ("sessionEndResponse", Value::Bool(*b)),
                OutputPayload::Unknown { event_type, data } => (event_type.as_str(), data.clone()),
            };
            map.serialize_entry(key, &value)?;
        }
        if let Some(usage_metadata) = &self.usage_metadata {
            map.serialize_entry("usageMetadata", usage_metadata)?;
        }
        map.end()
    }
}

impl<'de> Deserialize<'de> for OutputEvent {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        use serde::de::Error;
        let mut map = Map::deserialize(deserializer)?;

        fn take_i64<E: Error>(map: &mut Map<String, Value>, key: &str) -> Result<Option<i64>, E> {
            match map.remove(key) {
                None | Some(Value::Null) => Ok(None),
                Some(Value::Number(n)) => n
                    .as_i64()
                    .map(Some)
                    .ok_or_else(|| E::custom(format!("{key}: number does not fit in i64"))),
                Some(Value::String(s)) => s
                    .parse::<i64>()
                    .map(Some)
                    .map_err(|e| E::custom(format!("{key}: invalid i64 string: {e}"))),
                Some(other) => Err(E::custom(format!("{key}: expected i64, got {other}"))),
            }
        }

        let seq_num = take_i64(&mut map, "seqNum")?;
        let timestamp_micros = take_i64(&mut map, "timestampMicros")?;
        let usage_metadata = match map.remove("usageMetadata") {
            None | Some(Value::Null) => None,
            Some(v) => Some(serde_json::from_value(v).map_err(D::Error::custom)?),
        };

        let mut payload = None;
        for key in OUTPUT_PAYLOAD_KEYS {
            if let Some(value) = map.remove(*key) {
                payload = Some(match *key {
                    "stepUpdate" => OutputPayload::StepUpdate(Box::new(
                        serde_json::from_value(value).map_err(D::Error::custom)?,
                    )),
                    "trajectoryStateUpdate" => OutputPayload::TrajectoryStateUpdate(
                        serde_json::from_value(value).map_err(D::Error::custom)?,
                    ),
                    "toolCall" => OutputPayload::ToolCall(
                        serde_json::from_value(value).map_err(D::Error::custom)?,
                    ),
                    "initializeConversationResponse" => {
                        OutputPayload::InitializeConversationResponse(
                            serde_json::from_value(value).map_err(D::Error::custom)?,
                        )
                    }
                    "callHookRequest" => OutputPayload::CallHookRequest(
                        serde_json::from_value(value).map_err(D::Error::custom)?,
                    ),
                    "sessionEndResponse" => {
                        OutputPayload::SessionEndResponse(value.as_bool().unwrap_or_default())
                    }
                    _ => unreachable!("key list is exhaustive"),
                });
                break;
            }
        }
        // Any leftover field is an unrecognized oneof variant: preserve it.
        if payload.is_none()
            && let Some((event_type, data)) = map.into_iter().next()
        {
            tracing::warn!(
                "Unknown OutputEvent variant: '{}'. Preserving in Unknown variant.",
                event_type
            );
            payload = Some(OutputPayload::Unknown { event_type, data });
        }

        Ok(Self {
            seq_num,
            timestamp_micros,
            usage_metadata,
            payload,
        })
    }
}

/// `InitializeConversationResponse`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct InitializeConversationResponse {
    /// The conversation id (persist to resume this session later).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cascade_id: Option<String>,
    /// Restored steps when resuming a saved conversation.
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub history: Vec<StepUpdate>,
    /// Unrecognized fields, preserved for roundtrip (Evergreen).
    #[serde(flatten)]
    pub extra: Map<String, Value>,
}

/// `UsageMetadata` — token accounting for a step.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct UsageMetadata {
    /// Prompt tokens.
    #[serde(
        default,
        deserialize_with = "flex_num::opt_u64",
        skip_serializing_if = "Option::is_none"
    )]
    pub prompt_token_count: Option<u64>,
    /// Cached-content tokens.
    #[serde(
        default,
        deserialize_with = "flex_num::opt_u64",
        skip_serializing_if = "Option::is_none"
    )]
    pub cached_content_token_count: Option<u64>,
    /// Response candidate tokens.
    #[serde(
        default,
        deserialize_with = "flex_num::opt_u64",
        skip_serializing_if = "Option::is_none"
    )]
    pub candidates_token_count: Option<u64>,
    /// Thinking tokens.
    #[serde(
        default,
        deserialize_with = "flex_num::opt_u64",
        skip_serializing_if = "Option::is_none"
    )]
    pub thoughts_token_count: Option<u64>,
    /// Total tokens.
    #[serde(
        default,
        deserialize_with = "flex_num::opt_u64",
        skip_serializing_if = "Option::is_none"
    )]
    pub total_token_count: Option<u64>,
    /// Unrecognized fields, preserved for roundtrip (Evergreen).
    #[serde(flatten)]
    pub extra: Map<String, Value>,
}

/// `StepUpdate` — progress on one agent step.
///
/// The per-tool action fields (`run_command`, `edit_file`, ...) are plain
/// optional fields on the wire (not a oneof); at most one is set in
/// practice.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct StepUpdate {
    /// Conversation id.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cascade_id: Option<String>,
    /// Trajectory this step belongs to (subagents get their own).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub trajectory_id: Option<String>,
    /// Step index within the trajectory.
    #[serde(
        default,
        deserialize_with = "flex_num::opt_u32",
        skip_serializing_if = "Option::is_none"
    )]
    pub step_index: Option<u32>,
    /// Lifecycle state.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub state: Option<StepState>,
    /// Who produced this step.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub source: Option<StepSource>,
    /// Who this step is directed at.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub target: Option<StepTarget>,
    /// Error description when `state` is `Error`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error_message: Option<String>,
    /// Accumulated thinking text.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub thinking: Option<String>,
    /// Incremental response text.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text_delta: Option<String>,
    /// Incremental thinking text.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub thinking_delta: Option<String>,
    /// Accumulated response text.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text: Option<String>,
    /// `list_directory` action details.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub list_directory: Option<ActionListDirectory>,
    /// `find_file` action details.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub find_file: Option<ActionFindFile>,
    /// `search_directory` (grep) action details.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub search_directory: Option<ActionSearchDirectory>,
    /// `view_file` action details.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub view_file: Option<ActionViewFile>,
    /// `create_file` action details.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub create_file: Option<ActionCreateFile>,
    /// `edit_file` action details.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub edit_file: Option<ActionEditFile>,
    /// `run_command` action details.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub run_command: Option<ActionRunCommand>,
    /// History compaction marker.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub compaction: Option<ActionCompaction>,
    /// Subagent invocation marker.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub invoke_subagent: Option<ActionInvokeSubagent>,
    /// `generate_image` action details.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub generate_image: Option<ActionGenerateImage>,
    /// Finish marker with structured output.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub finish: Option<ActionFinish>,
    /// Step-level error details.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<ActionError>,
    /// MCP tool invocation details.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mcp_tool: Option<ActionMcpTool>,
    /// `search_web` action details.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub search_web: Option<ActionSearchWeb>,
    /// Free-text description of a pending request (confirmation prompts).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub request_text: Option<String>,
    /// Present while the step waits for a tool confirmation.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool_confirmation_request: Option<ToolConfirmationRequest>,
    /// Present while the step waits for question answers.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub questions_request: Option<UserQuestionsRequest>,
    /// Unrecognized fields, preserved for roundtrip (Evergreen).
    #[serde(flatten)]
    pub extra: Map<String, Value>,
}

/// `ToolConfirmationRequest` — currently an empty marker message.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct ToolConfirmationRequest {
    /// Unrecognized fields, preserved for roundtrip (Evergreen).
    #[serde(flatten)]
    pub extra: Map<String, Value>,
}

/// `UserQuestionsRequest`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct UserQuestionsRequest {
    /// The questions to answer.
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub questions: Vec<UserQuestion>,
    /// Unrecognized fields, preserved for roundtrip (Evergreen).
    #[serde(flatten)]
    pub extra: Map<String, Value>,
}

/// `UserQuestion` (oneof `question_type`, currently multiple-choice only).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct UserQuestion {
    /// A multiple-choice question.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub multiple_choice: Option<MultipleChoice>,
    /// Unrecognized fields (including future question types), preserved
    /// for roundtrip (Evergreen).
    #[serde(flatten)]
    pub extra: Map<String, Value>,
}

/// `MultipleChoice`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct MultipleChoice {
    /// The question text.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub question: Option<String>,
    /// The choices.
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub choices: Vec<String>,
    /// Whether multiple choices may be selected.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub is_multi_select: Option<bool>,
}

/// `TrajectoryStateUpdate`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct TrajectoryStateUpdate {
    /// The trajectory that changed state.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub trajectory_id: Option<String>,
    /// The new state.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub state: Option<TrajectoryState>,
    /// Error message (e.g. why the turn was cancelled).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
    /// Unrecognized fields, preserved for roundtrip (Evergreen).
    #[serde(flatten)]
    pub extra: Map<String, Value>,
}

/// `ToolCall` — the model invoking a client-executed custom tool.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct ToolCall {
    /// Correlation id; echo it in the [`ToolResponse`].
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
    /// The tool name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Arguments, serialized as a JSON string.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub arguments_json: Option<String>,
    /// Arguments as a structured value (protobuf `Struct`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub arguments: Option<Value>,
    /// Unrecognized fields, preserved for roundtrip (Evergreen).
    #[serde(flatten)]
    pub extra: Map<String, Value>,
}

/// `CallHookRequest` — the harness invoking a client-side lifecycle hook.
///
/// The `*_args` fields form a oneof (`args`): at most one is set.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct CallHookRequest {
    /// Correlation id; echo it in the [`CallHookResponse`].
    #[serde(skip_serializing_if = "Option::is_none")]
    pub request_id: Option<String>,
    /// Hook name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Which lifecycle point fired.
    #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
    pub hook_type: Option<LifecycleHook>,
    /// Pre-turn arguments.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pre_turn_args: Option<PreTurnArgs>,
    /// Post-turn arguments.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub post_turn_args: Option<PostTurnArgs>,
    /// Pre-tool arguments (the hook may deny the call).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pre_tool_args: Option<PreToolArgs>,
    /// Post-tool arguments.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub post_tool_args: Option<PostToolArgs>,
    /// Unrecognized fields, preserved for roundtrip (Evergreen).
    #[serde(flatten)]
    pub extra: Map<String, Value>,
}

/// `PreToolArgs`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct PreToolArgs {
    /// The tool about to run.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool_name: Option<String>,
    /// Its arguments, serialized as a JSON string.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub arguments_json: Option<String>,
}

/// `PostToolArgs`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct PostToolArgs {
    /// The tool that ran.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool_name: Option<String>,
    /// Its result.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub result: Option<String>,
    /// The error, if it failed.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
}

/// `PreTurnArgs`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct PreTurnArgs {
    /// The user input starting the turn.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub user_input: Option<UserInput>,
}

/// `PostTurnArgs`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct PostTurnArgs {
    /// The final response text of the turn.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub response_text: Option<String>,
}

// =============================================================================
// StepUpdate action submessages
// =============================================================================

/// `ActionListDirectory`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct ActionListDirectory {
    /// The listed directory.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub directory_path: Option<String>,
    /// The entries (populated when the step completes).
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub results: Vec<ListDirectoryEntry>,
    /// Unrecognized fields, preserved for roundtrip (Evergreen).
    #[serde(flatten)]
    pub extra: Map<String, Value>,
}

/// `ActionListDirectory.Result` (oneof `info`: directory flag or file size).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct ListDirectoryEntry {
    /// Entry name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Set when the entry is a directory.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub is_directory: Option<bool>,
    /// Set (byte size) when the entry is a file.
    #[serde(
        default,
        deserialize_with = "flex_num::opt_u64",
        skip_serializing_if = "Option::is_none"
    )]
    pub file_size: Option<u64>,
}

/// `ActionFindFile`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct ActionFindFile {
    /// The searched directory.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub directory_path: Option<String>,
    /// The filename query.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub query: Option<String>,
    /// Raw find output (populated when the step completes).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub output: Option<String>,
    /// Unrecognized fields, preserved for roundtrip (Evergreen).
    #[serde(flatten)]
    pub extra: Map<String, Value>,
}

/// `ActionSearchDirectory`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct ActionSearchDirectory {
    /// The searched directory.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub directory_path: Option<String>,
    /// The grep query.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub query: Option<String>,
    /// Result count (populated when the step completes).
    #[serde(
        default,
        deserialize_with = "flex_num::opt_i32",
        skip_serializing_if = "Option::is_none"
    )]
    pub num_results: Option<i32>,
    /// Unrecognized fields, preserved for roundtrip (Evergreen).
    #[serde(flatten)]
    pub extra: Map<String, Value>,
}

/// `ActionViewFile`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct ActionViewFile {
    /// The viewed file.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub file_path: Option<String>,
    /// First viewed line.
    #[serde(
        default,
        deserialize_with = "flex_num::opt_u32",
        skip_serializing_if = "Option::is_none"
    )]
    pub start_line: Option<u32>,
    /// Last viewed line.
    #[serde(
        default,
        deserialize_with = "flex_num::opt_u32",
        skip_serializing_if = "Option::is_none"
    )]
    pub end_line: Option<u32>,
    /// Unrecognized fields, preserved for roundtrip (Evergreen).
    #[serde(flatten)]
    pub extra: Map<String, Value>,
}

/// `ActionCreateFile`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct ActionCreateFile {
    /// The created file.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub file_path: Option<String>,
    /// Its contents.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub contents: Option<String>,
    /// Unrecognized fields, preserved for roundtrip (Evergreen).
    #[serde(flatten)]
    pub extra: Map<String, Value>,
}

/// `ActionEditFile`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct ActionEditFile {
    /// The edited file.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub file_path: Option<String>,
    /// The applied diff blocks.
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub diff_block: Vec<DiffBlock>,
    /// Unrecognized fields, preserved for roundtrip (Evergreen).
    #[serde(flatten)]
    pub extra: Map<String, Value>,
}

/// `ActionEditFile.DiffBlock`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct DiffBlock {
    /// First affected line.
    #[serde(
        default,
        deserialize_with = "flex_num::opt_i32",
        skip_serializing_if = "Option::is_none"
    )]
    pub start_line: Option<i32>,
    /// Last affected line.
    #[serde(
        default,
        deserialize_with = "flex_num::opt_i32",
        skip_serializing_if = "Option::is_none"
    )]
    pub end_line: Option<i32>,
    /// The diff lines.
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub lines: Vec<DiffLine>,
}

/// `ActionEditFile.DiffLine`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct DiffLine {
    /// The line text.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text: Option<String>,
    /// What happened to the line.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub action: Option<LineAction>,
}

/// `ActionRunCommand`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct ActionRunCommand {
    /// The shell command.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub command_line: Option<String>,
    /// The working directory.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub working_dir: Option<String>,
    /// Exit code (populated when the step completes).
    #[serde(
        default,
        deserialize_with = "flex_num::opt_i32",
        skip_serializing_if = "Option::is_none"
    )]
    pub exit_code: Option<i32>,
    /// Combined stdout/stderr (populated when the step completes).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub combined_output: Option<String>,
    /// Unrecognized fields, preserved for roundtrip (Evergreen).
    #[serde(flatten)]
    pub extra: Map<String, Value>,
}

/// `ActionCompaction` — history compaction marker (no fields).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct ActionCompaction {
    /// Unrecognized fields, preserved for roundtrip (Evergreen).
    #[serde(flatten)]
    pub extra: Map<String, Value>,
}

/// `ActionInvokeSubagent` — subagent invocation marker.
///
/// The invoked subagent's `name` is modeled as an optional typed field, but
/// **harness 0.1.5 does not populate it**: the `invokeSubagent` step action
/// is an empty message on the wire (verified with `LOUD_WIRE=1` — the step
/// only carries the generic text `"Invoke subagent"`). The field is here so
/// that a future harness emitting the name surfaces it without an API break;
/// until then it stays `None`, and any unexpected field is preserved in
/// `extra` (Evergreen).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct ActionInvokeSubagent {
    /// The invoked subagent's name, when the harness reports it (see the
    /// type docs — `None` on harness 0.1.5).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Unrecognized fields, preserved for roundtrip (Evergreen).
    #[serde(flatten)]
    pub extra: Map<String, Value>,
}

/// `ActionGenerateImage`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct ActionGenerateImage {
    /// The image prompt.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub prompt: Option<String>,
    /// Input image paths (for edits).
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub image_paths: Vec<String>,
    /// Output image name (populated when the step completes).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub image_name: Option<String>,
    /// Requested aspect ratio.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub aspect_ratio: Option<String>,
    /// Unrecognized fields, preserved for roundtrip (Evergreen).
    #[serde(flatten)]
    pub extra: Map<String, Value>,
}

/// `ActionFinish` — the agent finished with structured output.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct ActionFinish {
    /// The structured output, serialized as a JSON string.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub output_string: Option<String>,
    /// Unrecognized fields, preserved for roundtrip (Evergreen).
    #[serde(flatten)]
    pub extra: Map<String, Value>,
}

/// `ActionError`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct ActionError {
    /// The error message.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error_message: Option<String>,
    /// HTTP status code of the underlying model call, when applicable.
    #[serde(
        default,
        deserialize_with = "flex_num::opt_u32",
        skip_serializing_if = "Option::is_none"
    )]
    pub http_code: Option<u32>,
    /// Unrecognized fields, preserved for roundtrip (Evergreen).
    #[serde(flatten)]
    pub extra: Map<String, Value>,
}

/// `ActionMcpTool`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct ActionMcpTool {
    /// The MCP server name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub server_name: Option<String>,
    /// The tool name on that server.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool_name: Option<String>,
    /// Arguments, serialized as a JSON string.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub arguments_json: Option<String>,
    /// Unrecognized fields, preserved for roundtrip (Evergreen).
    #[serde(flatten)]
    pub extra: Map<String, Value>,
}

/// `ActionSearchWeb`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct ActionSearchWeb {
    /// The search query.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub query: Option<String>,
    /// Restrict results to this domain.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub domain: Option<String>,
    /// Result summary (populated when the step completes).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub summary: Option<String>,
    /// Unrecognized fields, preserved for roundtrip (Evergreen).
    #[serde(flatten)]
    pub extra: Map<String, Value>,
}

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

    // -------------------------------------------------------------------
    // Golden proto-JSON fixtures generated with the reference
    // implementation (google-antigravity 0.1.5, protobuf json_format).
    // -------------------------------------------------------------------

    #[test]
    fn test_input_event_user_input_golden() {
        let event = InputEvent::UserInput("hello".to_string());
        assert_eq!(
            serde_json::to_value(&event).unwrap(),
            json!({"userInput": "hello"})
        );
    }

    #[test]
    fn test_input_event_tool_response_golden() {
        let event = InputEvent::ToolResponse(ToolResponse {
            id: "1".to_string(),
            response_json: Some(r#"{"a":1}"#.to_string()),
            supplemental_media: vec![],
        });
        assert_eq!(
            serde_json::to_value(&event).unwrap(),
            json!({"toolResponse": {"id": "1", "responseJson": "{\"a\":1}"}})
        );
    }

    #[test]
    fn test_input_event_halt_request_golden() {
        let event = InputEvent::HaltRequest(true);
        assert_eq!(
            serde_json::to_value(&event).unwrap(),
            json!({"haltRequest": true})
        );
    }

    #[test]
    fn test_input_event_tool_confirmation_golden() {
        let event = InputEvent::ToolConfirmation(ToolConfirmation {
            trajectory_id: "t".to_string(),
            step_index: 2,
            accepted: true,
        });
        assert_eq!(
            serde_json::to_value(&event).unwrap(),
            json!({"toolConfirmation": {"trajectoryId": "t", "stepIndex": 2, "accepted": true}})
        );
    }

    #[test]
    fn test_input_event_call_hook_response_golden() {
        let event = InputEvent::CallHookResponse(CallHookResponse {
            request_id: "r".to_string(),
            pre_tool_result: Some(HookVerdict {
                decision: Some(HookDecision::Allow),
                reason: Some("ok".to_string()),
            }),
            ..Default::default()
        });
        assert_eq!(
            serde_json::to_value(&event).unwrap(),
            json!({"callHookResponse": {"requestId": "r", "preToolResult": {"decision": "ALLOW", "reason": "ok"}}})
        );
    }

    #[test]
    fn test_initialize_conversation_event_golden() {
        // Matches the reference SDK's json_format.MessageToJson output for
        // an equivalent HarnessConfig (field-by-field; ordering differs).
        let event = InitializeConversationEvent {
            config: Some(HarnessConfig {
                cascade_id: Some("cid".to_string()),
                system_instructions: Some(SystemInstructions::custom_text("hi")),
                tools: vec![Tool {
                    name: Some("t".to_string()),
                    description: Some("d".to_string()),
                    parameters_json_schema: Some("{}".to_string()),
                    response_json_schema: Some("{}".to_string()),
                }],
                harness_side_tools: Some(HarnessSideTools {
                    run_command: Some(ToolToggle::new(false)),
                    view_file: Some(ToolToggle::new(true)),
                    ..Default::default()
                }),
                workspaces: vec![Workspace::filesystem("/w")],
                mcp_servers: vec![McpServerConfig {
                    name: Some("git".to_string()),
                    stdio: Some(McpStdioTransport {
                        command: Some("uvx".to_string()),
                        args: vec!["x".to_string()],
                        env: BTreeMap::from([("K".to_string(), "V".to_string())]),
                    }),
                    ..Default::default()
                }],
                models: vec![ModelConfig {
                    name: Some("gemini-3-flash-preview".to_string()),
                    types: vec![ModelType::Text],
                    gemini_api_endpoint: Some(GeminiApiEndpoint {
                        api_key: Some("k".to_string()),
                        http_headers: BTreeMap::from([("a".to_string(), "b".to_string())]),
                        ..Default::default()
                    }),
                    ..Default::default()
                }],
                enabled_hooks: vec![LifecycleHook::PreTool],
                ..Default::default()
            }),
        };
        let expected = json!({"config": {
            "cascadeId": "cid",
            "systemInstructions": {"custom": {"part": [{"text": "hi"}]}},
            "tools": [{"name": "t", "description": "d", "parametersJsonSchema": "{}", "responseJsonSchema": "{}"}],
            "harnessSideTools": {"runCommand": {"enabled": false}, "viewFile": {"enabled": true}},
            "workspaces": [{"filesystemWorkspace": {"directory": "/w"}}],
            "mcpServers": [{"name": "git", "stdio": {"command": "uvx", "args": ["x"], "env": {"K": "V"}}}],
            "models": [{"name": "gemini-3-flash-preview", "types": ["MODEL_TYPE_TEXT"], "geminiApiEndpoint": {"httpHeaders": {"a": "b"}, "apiKey": "k"}}],
            "enabledHooks": ["LIFECYCLE_HOOK_PRE_TOOL"],
        }});
        assert_eq!(serde_json::to_value(&event).unwrap(), expected);
    }

    #[test]
    fn test_output_event_step_update_golden() {
        // Verbatim harness-side encoding: int64/uint64 as strings.
        let raw = r#"{"seqNum": "12345678901234", "timestampMicros": "2", "stepUpdate": {"trajectoryId": "traj", "stepIndex": 3, "state": "STATE_DONE", "source": "SOURCE_MODEL", "target": "TARGET_USER", "text": "hello", "runCommand": {"commandLine": "ls", "exitCode": 0, "combinedOutput": "a\n"}}, "usageMetadata": {"promptTokenCount": "10", "totalTokenCount": "20"}}"#;
        let event: OutputEvent = serde_json::from_str(raw).unwrap();
        assert_eq!(event.seq_num, Some(12_345_678_901_234));
        assert_eq!(event.timestamp_micros, Some(2));
        let usage = event.usage_metadata.as_ref().unwrap();
        assert_eq!(usage.prompt_token_count, Some(10));
        assert_eq!(usage.total_token_count, Some(20));
        let Some(OutputPayload::StepUpdate(step)) = &event.payload else {
            panic!("expected StepUpdate, got {:?}", event.payload);
        };
        assert_eq!(step.trajectory_id.as_deref(), Some("traj"));
        assert_eq!(step.step_index, Some(3));
        assert_eq!(step.state, Some(StepState::Done));
        assert_eq!(step.source, Some(StepSource::Model));
        assert_eq!(step.target, Some(StepTarget::User));
        assert_eq!(step.text.as_deref(), Some("hello"));
        let run = step.run_command.as_ref().unwrap();
        assert_eq!(run.command_line.as_deref(), Some("ls"));
        assert_eq!(run.exit_code, Some(0));
        assert_eq!(run.combined_output.as_deref(), Some("a\n"));
    }

    #[test]
    fn test_output_event_tool_call_golden() {
        let raw = r#"{"seqNum": "1", "toolCall": {"id": "abc", "name": "get_weather", "argumentsJson": "{\"city\":\"SF\"}"}}"#;
        let event: OutputEvent = serde_json::from_str(raw).unwrap();
        let Some(OutputPayload::ToolCall(call)) = &event.payload else {
            panic!("expected ToolCall");
        };
        assert_eq!(call.id.as_deref(), Some("abc"));
        assert_eq!(call.name.as_deref(), Some("get_weather"));
        assert_eq!(call.arguments_json.as_deref(), Some(r#"{"city":"SF"}"#));
    }

    #[test]
    fn test_output_event_init_response_golden() {
        let raw = r#"{"initializeConversationResponse": {"cascadeId": "cid"}}"#;
        let event: OutputEvent = serde_json::from_str(raw).unwrap();
        let Some(OutputPayload::InitializeConversationResponse(resp)) = &event.payload else {
            panic!("expected InitializeConversationResponse");
        };
        assert_eq!(resp.cascade_id.as_deref(), Some("cid"));
        assert!(resp.history.is_empty());
    }

    // -------------------------------------------------------------------
    // Roundtrips and Evergreen preservation
    // -------------------------------------------------------------------

    fn roundtrip_output(event: &OutputEvent) -> OutputEvent {
        let json = serde_json::to_string(event).unwrap();
        serde_json::from_str(&json).unwrap()
    }

    fn roundtrip_input(event: &InputEvent) -> InputEvent {
        let json = serde_json::to_string(event).unwrap();
        serde_json::from_str(&json).unwrap()
    }

    #[test]
    fn test_input_event_roundtrip_all_variants() {
        let events = vec![
            InputEvent::UserInput("hi".to_string()),
            InputEvent::ComplexUserInput(UserInput {
                parts: vec![
                    UserInputPart::text("a"),
                    UserInputPart {
                        media: Some(Media {
                            mime_type: Some("image/png".to_string()),
                            description: Some("d".to_string()),
                            data: Some("aGVsbG8=".to_string()),
                        }),
                        ..Default::default()
                    },
                    UserInputPart {
                        slash_command: Some(SlashCommand {
                            name: Some("compact".to_string()),
                        }),
                        ..Default::default()
                    },
                ],
            }),
            InputEvent::ToolConfirmation(ToolConfirmation {
                trajectory_id: "t".to_string(),
                step_index: 7,
                accepted: false,
            }),
            InputEvent::ToolResponse(ToolResponse {
                id: "id".to_string(),
                response_json: Some("{}".to_string()),
                supplemental_media: vec![Media::default()],
            }),
            InputEvent::QuestionResponse(UserQuestionsResponse {
                trajectory_id: "t".to_string(),
                step_index: 1,
                cancelled: None,
                response: Some(QuestionsResponse {
                    answers: vec![
                        UserQuestionAnswer::unanswered(),
                        UserQuestionAnswer {
                            multiple_choice_answer: Some(MultipleChoiceAnswer {
                                selected_choice_indices: vec![0, 2],
                                freeform_response: Some("f".to_string()),
                            }),
                            ..Default::default()
                        },
                    ],
                }),
            }),
            InputEvent::HaltRequest(true),
            InputEvent::AutomatedTrigger("tick".to_string()),
            InputEvent::CallHookResponse(CallHookResponse {
                request_id: "r".to_string(),
                empty_result: Some(EmptyResult {}),
                ..Default::default()
            }),
            InputEvent::SessionEndRequest(true),
            InputEvent::Unknown {
                event_type: "futureEvent".to_string(),
                data: json!({"x": 1}),
            },
        ];
        for event in events {
            assert_eq!(roundtrip_input(&event), event);
        }
    }

    #[test]
    fn test_input_event_unknown_variant_preserves_wire_format() {
        let raw = r#"{"futureEvent": {"payload": 42}}"#;
        let event: InputEvent = serde_json::from_str(raw).unwrap();
        assert!(event.is_unknown());
        assert_eq!(event.unknown_event_type(), Some("futureEvent"));
        assert_eq!(event.unknown_data(), Some(&json!({"payload": 42})));
        // Roundtrips back to the original single-key object.
        assert_eq!(
            serde_json::to_value(&event).unwrap(),
            json!({"futureEvent": {"payload": 42}})
        );
    }

    #[test]
    fn test_output_event_roundtrip_all_variants() {
        let events = vec![
            OutputEvent {
                seq_num: Some(1),
                timestamp_micros: Some(2),
                usage_metadata: Some(UsageMetadata {
                    prompt_token_count: Some(1),
                    total_token_count: Some(2),
                    ..Default::default()
                }),
                payload: Some(OutputPayload::StepUpdate(Box::new(StepUpdate {
                    trajectory_id: Some("t".to_string()),
                    step_index: Some(1),
                    state: Some(StepState::Active),
                    text_delta: Some("d".to_string()),
                    ..Default::default()
                }))),
            },
            OutputEvent {
                payload: Some(OutputPayload::TrajectoryStateUpdate(
                    TrajectoryStateUpdate {
                        trajectory_id: Some("t".to_string()),
                        state: Some(TrajectoryState::Idle),
                        error: None,
                        extra: Map::new(),
                    },
                )),
                ..Default::default()
            },
            OutputEvent {
                payload: Some(OutputPayload::ToolCall(ToolCall {
                    id: Some("i".to_string()),
                    name: Some("n".to_string()),
                    arguments_json: Some("{}".to_string()),
                    ..Default::default()
                })),
                ..Default::default()
            },
            OutputEvent {
                payload: Some(OutputPayload::InitializeConversationResponse(
                    InitializeConversationResponse {
                        cascade_id: Some("c".to_string()),
                        history: vec![StepUpdate::default()],
                        extra: Map::new(),
                    },
                )),
                ..Default::default()
            },
            OutputEvent {
                payload: Some(OutputPayload::CallHookRequest(CallHookRequest {
                    request_id: Some("r".to_string()),
                    hook_type: Some(LifecycleHook::PreTool),
                    pre_tool_args: Some(PreToolArgs {
                        tool_name: Some("run_command".to_string()),
                        arguments_json: Some("{}".to_string()),
                    }),
                    ..Default::default()
                })),
                ..Default::default()
            },
            OutputEvent {
                payload: Some(OutputPayload::SessionEndResponse(true)),
                ..Default::default()
            },
            OutputEvent {
                payload: Some(OutputPayload::Unknown {
                    event_type: "newThing".to_string(),
                    data: json!({"a": [1, 2]}),
                }),
                ..Default::default()
            },
            OutputEvent::default(),
        ];
        for event in events {
            assert_eq!(roundtrip_output(&event), event);
        }
    }

    #[test]
    fn test_output_event_unknown_variant_preserved() {
        let raw = r#"{"seqNum": "5", "brandNewEvent": {"k": "v"}}"#;
        let event: OutputEvent = serde_json::from_str(raw).unwrap();
        assert_eq!(event.seq_num, Some(5));
        let payload = event.payload.as_ref().unwrap();
        assert!(payload.is_unknown());
        assert_eq!(payload.unknown_event_type(), Some("brandNewEvent"));
        assert_eq!(payload.unknown_data(), Some(&json!({"k": "v"})));
        // Reserialization preserves the unknown payload.
        let json = serde_json::to_value(&event).unwrap();
        assert_eq!(json["brandNewEvent"], json!({"k": "v"}));
        assert_eq!(json["seqNum"], json!(5));
    }

    #[test]
    fn test_step_update_unknown_fields_preserved() {
        let raw = r#"{"trajectoryId": "t", "futureField": {"nested": true}}"#;
        let step: StepUpdate = serde_json::from_str(raw).unwrap();
        assert_eq!(
            step.extra.get("futureField"),
            Some(&json!({"nested": true}))
        );
        let json = serde_json::to_value(&step).unwrap();
        assert_eq!(json["futureField"], json!({"nested": true}));
    }

    #[test]
    fn test_wire_enum_unknown_value_preserved() {
        let state: StepState = serde_json::from_value(json!("STATE_HIBERNATING")).unwrap();
        assert!(state.is_unknown());
        assert_eq!(state.unknown_state_type(), Some("STATE_HIBERNATING"));
        assert_eq!(state.unknown_data(), Some(&json!("STATE_HIBERNATING")));
        assert_eq!(
            serde_json::to_value(&state).unwrap(),
            json!("STATE_HIBERNATING")
        );
    }

    #[test]
    fn test_wire_enum_known_values_roundtrip() {
        for (value, wire) in [
            (StepState::Unspecified, "STATE_UNSPECIFIED"),
            (StepState::Active, "STATE_ACTIVE"),
            (StepState::Done, "STATE_DONE"),
            (StepState::WaitingForUser, "STATE_WAITING_FOR_USER"),
            (StepState::Error, "STATE_ERROR"),
        ] {
            assert_eq!(serde_json::to_value(&value).unwrap(), json!(wire));
            let parsed: StepState = serde_json::from_value(json!(wire)).unwrap();
            assert_eq!(parsed, value);
            assert!(!parsed.is_unknown());
            assert_eq!(parsed.as_wire_str(), wire);
        }
    }

    #[test]
    fn test_usage_metadata_accepts_numbers_and_strings() {
        let from_strings: UsageMetadata =
            serde_json::from_value(json!({"promptTokenCount": "7", "totalTokenCount": "9"}))
                .unwrap();
        let from_numbers: UsageMetadata =
            serde_json::from_value(json!({"promptTokenCount": 7, "totalTokenCount": 9})).unwrap();
        assert_eq!(from_strings.prompt_token_count, Some(7));
        assert_eq!(from_strings, from_numbers);
    }

    #[test]
    fn test_questions_request_deserializes() {
        let raw = r#"{"questions": [{"multipleChoice": {"question": "q?", "choices": ["a", "b"], "isMultiSelect": true}}, {"holographicQuestion": {"q": 1}}]}"#;
        let req: UserQuestionsRequest = serde_json::from_str(raw).unwrap();
        assert_eq!(req.questions.len(), 2);
        let mc = req.questions[0].multiple_choice.as_ref().unwrap();
        assert_eq!(mc.question.as_deref(), Some("q?"));
        assert_eq!(mc.choices, vec!["a", "b"]);
        assert_eq!(mc.is_multi_select, Some(true));
        // Unknown question type preserved via extra.
        assert!(req.questions[1].multiple_choice.is_none());
        assert!(req.questions[1].extra.contains_key("holographicQuestion"));
    }

    #[test]
    fn test_edit_file_diff_structure() {
        let raw = r#"{"filePath": "/f", "diffBlock": [{"startLine": 1, "endLine": 2, "lines": [{"text": "x", "action": "LINE_ACTION_INSERT"}]}]}"#;
        let action: ActionEditFile = serde_json::from_str(raw).unwrap();
        assert_eq!(action.file_path.as_deref(), Some("/f"));
        assert_eq!(
            action.diff_block[0].lines[0].action,
            Some(LineAction::Insert)
        );
    }

    #[test]
    fn test_tool_call_arguments_struct_preserved() {
        let raw = r#"{"id": "1", "name": "n", "arguments": {"fields": [{"name": "city", "value": {"stringValue": "SF"}}]}}"#;
        let call: ToolCall = serde_json::from_str(raw).unwrap();
        assert!(call.arguments.is_some());
        let json = serde_json::to_value(&call).unwrap();
        assert_eq!(json["arguments"]["fields"][0]["name"], "city");
    }

    #[test]
    fn test_flex_num_rejects_garbage() {
        let result: Result<UsageMetadata, _> =
            serde_json::from_value(json!({"promptTokenCount": "not-a-number"}));
        assert!(result.is_err());
        let result: Result<UsageMetadata, _> =
            serde_json::from_value(json!({"promptTokenCount": true}));
        assert!(result.is_err());
    }

    #[test]
    fn test_flex_num_null_is_none() {
        let usage: UsageMetadata =
            serde_json::from_value(json!({"promptTokenCount": null})).unwrap();
        assert_eq!(usage.prompt_token_count, None);
    }

    #[test]
    fn test_output_event_seq_num_string_and_number() {
        let a: OutputEvent = serde_json::from_str(r#"{"seqNum": "3"}"#).unwrap();
        let b: OutputEvent = serde_json::from_str(r#"{"seqNum": 3}"#).unwrap();
        assert_eq!(a.seq_num, Some(3));
        assert_eq!(a, b);
    }
}